solid-optimizer 1.0.0-next.1 → 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/README.md CHANGED
@@ -45,6 +45,7 @@ The input and the output both keep their JSX. Run the JSX transform after `compi
45
45
  - `fold` turns constant folding and control-flow resolution on or off. Defaults to `true`.
46
46
  - `inline` turns component inlining on or off. Defaults to `true`.
47
47
  - `alwaysInline` inlines every component that can be, even where the copies are larger than the calls they replace. Defaults to `false`. See [Only where it is smaller](#only-where-it-is-smaller).
48
+ - `alwaysInlineComponents` lists top-level components to inline wherever they can be, like `alwaysInline` does for every component. The Vite plugin lists the copies from `optimizer.packages` here.
48
49
  - `sharedComponents` maps top-level components that other modules use too to the number of modules that use them, this one included. Inlining one only counts its share of the declaration. `0` keeps the declaration whatever is inlined.
49
50
  - `contexts` turns context provider removal on or off. Defaults to `true`.
50
51
  - `memos` turns memo inlining on or off. Defaults to `true`.
@@ -95,7 +96,7 @@ export default defineConfig({
95
96
 
96
97
  The plugin optimizes in one of two modes.
97
98
 
98
- - **Chunk mode** is for client builds that do not hydrate. Constants fold and memos inline in each module first, so a branch that folds away takes its imports and `lazy()` chunks out of the bundle. Components imported from other modules are inlined there too, so the bundler drops them and the runtime code only they used. JSX is then kept through bundling. Each chunk is optimized as a whole and then lowered by Solid's JSX transform, so a component inlines anywhere in its chunk.
99
+ - **Chunk mode** is for client builds that do not hydrate. Constants fold and memos inline in each module first, so a branch that folds away takes its imports and `lazy()` chunks out of the bundle. Components imported from other modules are inlined there too, so the bundler drops them and the runtime code only they used. JSX is then kept through bundling. Each chunk is optimized as a whole and then lowered by Solid's JSX transform, so a component inlines anywhere in its chunk. Each chunk is also built with every component inlined that can be, and the smaller of the two, minified and gzipped, is kept. See [Only where it is smaller](#only-where-it-is-smaller).
99
100
  - **Module mode** is for everything else. Each module is optimized before the official plugin lowers it, with the components it imports from other modules copied in first. A server build and its client build split chunks differently, and hydration needs both to render the same tree, so every decision depends only on the modules. Two modules that import each other do not copy each other's components.
100
101
 
101
102
  Both modes fold constants imported from other modules in the project.
@@ -116,6 +117,7 @@ The plugin takes every option of `@solidjs/vite-plugin`, plus `optimizer`.
116
117
  - `optimizer.mode` is `'auto'` by default. Set it to `'module'` to never keep JSX through bundling.
117
118
  - `optimizer.dev` also optimizes while serving. Defaults to `false`.
118
119
  - `optimizer.report` reports what stays as written in each build, and why. `true` prints it. A function receives it instead, once per build environment. Defaults to `false`.
120
+ - `optimizer.packages` lists packages whose components are copied into the modules that use them, like `['@kobalte/core']`. A package has to publish its JSX, as most Solid libraries do through the `solid` export condition. Re-exports and aliases like `const Button = ButtonRoot` are followed. Their copies inline wherever they can be, whatever the estimate says, since it cannot see what the package's other modules and the runtime code only they use add up to. The bundler then drops the originals, even when the package lands in another chunk. A listed package has to be bundled in every build, or the server and client builds copy different components. Defaults to `[]`.
119
121
 
120
122
  ### Report
121
123
 
@@ -128,15 +130,16 @@ solid-optimizer: what stays as written in client
128
130
  inline no-host 1 Home
129
131
  ```
130
132
 
131
- Each line is a pass, a reason, how many times it happened, and the names it happened to. The reasons for the inline pass:
133
+ Each line is a pass, a reason, how many times it happened, and the names it happened to. A package's own modules are compiled too, but what they leave alone is not reported, since the app cannot change it. The app's calls of a package's components are. In chunk mode, a chunk is reported as a whole, so it also lists the package code bundled into it. The reasons for the inline pass:
132
134
 
133
135
  - `props-use` and `view-use` mean the component uses its props in a way other than `props.name`, a spread onto an element, or a `merge()` or `omit()` view, such as passing them to a function.
134
136
  - `component-params`, `component-body`, `component-return`, `component-async`, `component-recursive`, and `component-this` mean the component's own shape is not supported.
135
- - `call-spread` and `call-namespace` mean the call site passes a spread or a namespaced attribute. `call-ref` means its `ref` is an expression other than a name or a function, and `ref-use` means the component uses `props.ref` other than as a `ref`.
137
+ - `component-write` means the component's statements assign to something declared outside it, like a counter at the top of the module. A copy's statements run before the JSX around the call, so that JSX would see the write too early.
138
+ - `call-spread` and `call-namespace` mean the call site passes a spread or a namespaced attribute. `call-ref` means its `ref` is an expression other than a name, a function, or an array of them, and `ref-use` means the component uses `props.ref` other than as a `ref`.
136
139
  - `no-host` means the component has statements, and the call is not in JSX that a component or one of Solid's callbacks returns. A `<Show>` child or a `fallback` is one such place.
137
140
  - `size` means the copies would be larger than the calls.
138
141
  - `lazy`, `imported`, `nested`, and `not-a-function` mean the tag is not a component declared at the top of the same module or chunk.
139
- - A reason that starts with `copy-` is about copying a component from another module. `copy-package` means it comes from `node_modules`, `copy-cycle` means the two modules import each other, `copy-wrapper` means the component only returns a call of another component in its module, and `copy-size` means the copy was larger.
142
+ - A reason that starts with `copy-` is about copying a component from another module. `copy-package` means it comes from a package in `node_modules` that `optimizer.packages` does not list, `copy-cycle` means the two modules import each other, `copy-wrapper` means the component only returns a call of another component in its module, and `copy-size` means the copy was larger.
140
143
 
141
144
  The provider pass reports `open-component`, `open-call`, `open-new`, `open-spread`, and `open-outer` for code under the provider that it cannot see into, and `provider-value`, `provider-undefined`, and `provider-shape` for a value or provider it cannot handle. The memo pass reports `memo-reads`, `memo-read-place`, `memo-constant`, and a few more for a memo it keeps.
142
145
 
@@ -145,7 +148,7 @@ The provider pass reports `open-component`, `open-call`, `open-new`, `open-sprea
145
148
  - Chunk mode is skipped when the `babel` option is set or `compiler` is `'babel'`, since those passes need each module.
146
149
  - An export named `__so_local$name` is added to a module for each local binding its exported components need, so a copy in another module can import it. In chunk mode, entry modules get none.
147
150
  - A component used in several chunks is copied into each of them, where each copy is no larger than its call.
148
- - Components from dependencies in `node_modules` are not copied.
151
+ - Components from dependencies in `node_modules` are only copied from the packages `optimizer.packages` lists.
149
152
  - `.tsrx` modules are lowered by the official plugin and are not optimized.
150
153
 
151
154
  ## Features
@@ -191,16 +194,16 @@ Solid then creates one template for `<main>` instead of two.
191
194
  - the child callback of `<Show>` or `<Match>`, when it takes the value;
192
195
  - the callback given to `render`.
193
196
  - Bindings declared in the component get fresh names in every copy.
194
- - A component nothing else uses is removed.
197
+ - A component nothing else uses is removed, with any alias of it that nothing uses.
195
198
 
196
199
  A component inlines when all of these hold:
197
200
 
198
- - It is declared once at the top level, with a capitalized name.
201
+ - It is declared once at the top level, with a capitalized name. A call through an alias, like `const Separator = SeparatorRoot`, is a call of the component it names.
199
202
  - Its parameter is one identifier that is only read as `props.name`, spread onto an element as `{...props}`, or passed to `merge()` and `omit()`. See below.
200
203
  - Its body ends in the only `return`, and that `return` returns JSX.
201
204
  - It does not use `this`, `arguments`, `super`, or `new.target`.
202
205
  - The call site has no spread attribute and no namespaced attribute.
203
- - A `ref` at the call site moves to the element the component gives `props.ref` to, when its value is a name, a function, or an array of them, and the component only uses `props.ref` as the `ref` of an element, of another component, or in a spread. Both run while the element is made, untracked, so the element gets the same ref.
206
+ - A `ref` at the call site moves to the element the component gives `props.ref` to, when its value is a name, a function, or an array of them, and the component only uses `props.ref` as the `ref` of an element, of another component, or in a spread. Both run while the element is made, untracked, so the element gets the same ref. In an array, `void 0` and `untrack(() => ...)` around a name or a function count too: Solid skips an empty entry, and runs the whole `ref` untracked.
204
207
 
205
208
  The props can go through `merge()` and `omit()` first, declared as a `const` in the component:
206
209
 
@@ -236,9 +239,12 @@ Every copy repeats the component's own code, so inlining a component at many cal
236
239
  - A copy costs the component's statements, its dynamic attributes and children, and the elements that cannot join a template. Constant props are folded first, so a branch they rule out costs nothing.
237
240
  - When every call inlines and nothing else uses the component, its declaration goes away too.
238
241
  - A call in its children that can only inline once it does, because that component has statements to hoist, counts too.
242
+ - A call in its body that can only inline in a copy counts too, such as a call that spreads a `merge()` or `omit()` view, which each call site resolves. The copy is measured with that call inlined, and the called component's declaration goes away when nothing else uses it.
239
243
 
240
244
  A component inlines only when its copies are no larger. A small component, or one used once, inlines at every call. A wrapper used many times, whose root is another component, like most wrappers of a component library, stays a component.
241
245
 
246
+ The estimate weighs each component on its own, so it cannot see runtime code that only goes once every call that needs it is inlined, like `<Dynamic>`, `merge()`, and `omit()` behind a headless library's components. In chunk mode, the Vite plugin also builds each chunk with every component inlined that can be, as `alwaysInline` does, minifies and gzips both, and keeps the smaller one. The runtime only shrinks when it is in the same chunk as the calls.
247
+
242
248
  In the Vite plugin, a component copied from another module counts the module's share of its declaration: all of it when the importer is its only user, and one part in n when n modules use it, since it goes away once every one of them copies it. The plugin reads which modules use each export from the files the entries reach, and from the module scripts of an HTML entry. A re-export, a dynamic import, a use as a value, or a user the component's module imports back keeps the declaration whole.
243
249
 
244
250
  Set `alwaysInline` to inline every component that can be.
@@ -340,6 +346,7 @@ This follows the `optimize` option of `@solidjs/compiler` ([solidjs/solid#3231](
340
346
  - `<Repeat count>` becomes its `fallback` when `count` is below one.
341
347
  - `<Switch>` drops each `<Match>` that is always false, and becomes the first `<Match>` that is always true.
342
348
  - `<Dynamic component="div">` becomes `<div>`. `<Dynamic component={Card}>` becomes `<Card>` when `Card` is a capitalized component declared at the top level, as a function or with `lazy`, that nothing reassigns. An imported component stays, since an import could hold a tag name.
349
+ - `untrack(() => value)` becomes the value when the value is a constant. A component inlined with a literal prop can leave one, like `untrack(() => props.as)`.
343
350
  - A call of an arrow function whose body is JSX, such as a render prop left by inlining, becomes the JSX when it is an element's child and each argument is a constant or a binding nothing reassigns. `{((n) => <li>{n}</li>)(1)}` becomes `<li>{1}</li>`. A `ref` or a spread in the JSX keeps the call, since both run while the JSX is made.
344
351
 
345
352
  A built-in only folds when the tag resolves to Solid's component. The tag must bind to nothing, or be imported from one of `moduleSources`. A tag with a spread attribute or a function child never folds. `<Portal>`, `<Loading>`, `<Errored>`, and `<Reveal>` never fold.
@@ -123,6 +123,12 @@ interface CompileOptions {
123
123
  * @default false
124
124
  */
125
125
  alwaysInline?: boolean;
126
+ /**
127
+ * Top-level components to inline wherever they can be, like
128
+ * `alwaysInline` does for every component. The Vite plugin lists the
129
+ * copies of components from `optimizer.packages` here.
130
+ */
131
+ alwaysInlineComponents?: readonly string[];
126
132
  /**
127
133
  * The most passes to run. One pass can expose work for the next, such as
128
134
  * an inlined component whose props now fold. Compilation stops early once
@@ -189,4 +195,4 @@ interface ModuleConstants {
189
195
  declare function readModuleConstants(code: string, options?: Pick<CompileOptions, 'filename' | 'importedConstants' | 'globalConstants'>): ModuleConstants;
190
196
  //#endregion
191
197
  export { readModuleConstants as a, SkipPass as c, compile as i, Primitive as l, CompileResult as n, ImportedConstants as o, ModuleConstants as r, Skip as s, CompileOptions as t };
192
- //# sourceMappingURL=compile-BRCj4UN7.d.mts.map
198
+ //# sourceMappingURL=compile-CwH9mvHD.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-CwH9mvHD.d.mts","names":[],"sources":["../src/value.ts","../src/context.ts","../src/constants.ts","../src/compile.ts"],"mappings":";;;;KAUY;;;;KC4DA;;;;;UAMK;WACN,MAAM;;WAEN;;WAEA;;;;;;;;KC9DC,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;;;;;;EAMA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;EAOA;;UAGe;EACf;;EAEA,KAAK;;;;;EAKL,UAAU;;;;;;;;;;;;;iBAoGI,QAAQ,cAAc,UAAS,iBAAsB;UA0DpD;;;;;EAKf;;;;;;EAMA,SAAS,eAAe;;;;;;;;iBASV,oBACd,cACA,UAAS,KAAK,wEACb"}
@@ -1433,7 +1433,9 @@ var Folder = class {
1433
1433
  case "MemberExpression":
1434
1434
  if (!isWriteTarget(node, this.context.parents)) this.foldConstant(node);
1435
1435
  break;
1436
- case "CallExpression": this.annotatePure(node);
1436
+ case "CallExpression":
1437
+ this.annotatePure(node);
1438
+ this.foldUntrack(node);
1437
1439
  }
1438
1440
  }
1439
1441
  isJSXChildOrAttribute(node) {
@@ -1461,9 +1463,23 @@ var Folder = class {
1461
1463
  this.context.s.prependLeft(call.start, "/* @__PURE__ */ ");
1462
1464
  this.changed = true;
1463
1465
  }
1464
- foldConstant(node) {
1466
+ /**
1467
+ * `untrack(() => value)` is the value, when the value is a constant.
1468
+ * Nothing is read, so there is nothing to untrack. A component inlined
1469
+ * with a literal prop leaves this, like Kobalte's `untrack(() => props.as)`.
1470
+ */
1471
+ foldUntrack(call) {
1472
+ if (call.callee.type !== "Identifier" || call.arguments.length !== 1) return;
1473
+ const binding = this.context.scopes.references.get(call.callee);
1474
+ const identity = binding ? solidExport(binding, this.context.options) : void 0;
1475
+ const callback = call.arguments.at(0);
1476
+ if (identity !== "untrack" || callback?.type !== "ArrowFunctionExpression" || callback.async || callback.params.length > 0 || !callback.expression || callback.body.type === "BlockStatement") return;
1477
+ const value = evaluate(callback.body, this.lookup);
1478
+ if (value) this.foldConstant(call, value);
1479
+ }
1480
+ foldConstant(node, known) {
1465
1481
  if (isLiteralForm(node)) return;
1466
- const value = evaluate(node, this.lookup);
1482
+ const value = known ?? evaluate(node, this.lookup);
1467
1483
  if (!value) return;
1468
1484
  let text = literalText(value.value);
1469
1485
  if (text === void 0) return;
@@ -2581,34 +2597,61 @@ function removeProviders(context) {
2581
2597
  //#endregion
2582
2598
  //#region src/copy-size.ts
2583
2599
  /**
2584
- * Measures a component's copy at a call site: folds it as the passes after
2585
- * inlining would, then estimates its size with `SizeEstimator`.
2600
+ * Measures a component's copy at a call site: folds it, and inlines the
2601
+ * components it calls, as the passes after inlining would. Then it estimates
2602
+ * its size with `SizeEstimator`.
2586
2603
  */
2587
- /** The name of the function a copy is wrapped in to be folded and measured. */
2588
- const WRAPPER = "__so_size__";
2604
+ /**
2605
+ * The name of the function a copy is wrapped in to be folded and measured.
2606
+ * It is capitalized, so the inline pass can move statements into it.
2607
+ */
2608
+ const WRAPPER = "SoSize$$";
2609
+ /**
2610
+ * How many copies are being measured inside each other. Components that
2611
+ * call each other would otherwise measure each other without end.
2612
+ */
2613
+ let depth = 0;
2614
+ const MAX_DEPTH = 3;
2589
2615
  /**
2590
2616
  * The size of a component's copy at one call site, once its props have
2591
2617
  * folded. `header` declares the names the fold pass needs to know, like
2592
- * imports of Solid. `inTemplate` is whether the call site sits directly in
2593
- * an element.
2618
+ * imports of Solid. `called` holds the module's components the copy calls,
2619
+ * which inline into it when its props resolve their call sites.
2620
+ * `inTemplate` is whether the call site sits directly in an element.
2621
+ * `measured` receives the code that was measured.
2594
2622
  */
2595
- function copySize(filename, header, copy, inTemplate, options) {
2596
- let code = `${header}\nfunction ${WRAPPER}() {\n${copy.statements.join("\n")}\nreturn (${copy.root});\n}\n`;
2597
- for (let round = 0; round < 3; round += 1) {
2598
- const program = parse(filename, code);
2599
- const s = new MagicString(code);
2600
- if (!fold({
2601
- code,
2602
- filename,
2603
- s,
2604
- program,
2605
- parents: collectParents(program),
2606
- scopes: analyzeScopes(program),
2607
- options,
2608
- skips: void 0
2609
- })) break;
2610
- code = s.toString();
2623
+ function copySize(filename, header, copy, inTemplate, options, called, measured) {
2624
+ const calls = depth < MAX_DEPTH ? called : void 0;
2625
+ let code = `${header}\n${calls?.declarations ?? ""}\nfunction ${WRAPPER}() {\n${copy.statements.join("\n")}\nreturn (${copy.root});\n}\n`;
2626
+ for (let round = 0; round < 4; round += 1) {
2627
+ let changed = false;
2628
+ for (const pass of calls ? [fold, calls.inline] : [fold]) {
2629
+ const program = parse(filename, code);
2630
+ const s = new MagicString(code);
2631
+ depth += 1;
2632
+ let passChanged;
2633
+ try {
2634
+ passChanged = pass({
2635
+ code,
2636
+ filename,
2637
+ s,
2638
+ program,
2639
+ parents: collectParents(program),
2640
+ scopes: analyzeScopes(program),
2641
+ options,
2642
+ skips: void 0
2643
+ });
2644
+ } finally {
2645
+ depth -= 1;
2646
+ }
2647
+ if (passChanged) {
2648
+ code = s.toString();
2649
+ changed = true;
2650
+ }
2651
+ }
2652
+ if (!changed) break;
2611
2653
  }
2654
+ if (measured) measured.code = code;
2612
2655
  const wrapper = parse(filename, code).body.at(-1);
2613
2656
  if (wrapper?.type !== "FunctionDeclaration" || !wrapper.body) return Number.POSITIVE_INFINITY;
2614
2657
  const estimator = new SizeEstimator(code);
@@ -2634,7 +2677,9 @@ function copySize(filename, header, copy, inTemplate, options) {
2634
2677
  * A component inlines when its shape keeps the result equivalent:
2635
2678
  *
2636
2679
  * - It is declared once at the top level of the module, with a capitalized
2637
- * name, as a function declaration or a `const` bound to a function.
2680
+ * name, as a function declaration or a `const` bound to a function. A
2681
+ * tag of an alias, like `const Separator = SeparatorRoot`, is renamed to
2682
+ * the component first. See `renameAliasTags`.
2638
2683
  * - It takes no parameter, or one identifier that is only read as `props.name`,
2639
2684
  * or spread onto an element as `{...props}`.
2640
2685
  * - Its body is statements followed by one final `return` of JSX, or an arrow
@@ -2722,6 +2767,12 @@ const UNDEFINED = {
2722
2767
  text: "void 0",
2723
2768
  primary: false
2724
2769
  };
2770
+ /** The function a copy is wrapped in when it is measured. See `copy-size.ts`. */
2771
+ const COPY_WRAPPER = "function SoSize$$(";
2772
+ /** Whether code has a JSX tag named `name`. */
2773
+ function hasTag(code, name) {
2774
+ return new RegExp(`<${name.replaceAll("$", String.raw`\$`)}[\\s/>]`).test(code);
2775
+ }
2725
2776
  function isCapitalized(name) {
2726
2777
  return /^[A-Z]/.test(name);
2727
2778
  }
@@ -2777,6 +2828,38 @@ function containsReturn(node) {
2777
2828
  return found;
2778
2829
  }
2779
2830
  /**
2831
+ * Collects the nodes an assignment target writes through: an identifier, or
2832
+ * the root of a member chain, like `cache` in `cache.items[0] = x`. A root
2833
+ * that is not a name, like a call, is collected as it is.
2834
+ */
2835
+ function collectWriteRoots(target, roots) {
2836
+ switch (target.type) {
2837
+ case "MemberExpression":
2838
+ collectWriteRoots(target.object, roots);
2839
+ break;
2840
+ case "ParenthesizedExpression":
2841
+ case "TSAsExpression":
2842
+ case "TSSatisfiesExpression":
2843
+ case "TSNonNullExpression":
2844
+ case "TSTypeAssertion":
2845
+ collectWriteRoots(target.expression, roots);
2846
+ break;
2847
+ case "ObjectPattern":
2848
+ for (const property of target.properties) collectWriteRoots(property.type === "RestElement" ? property.argument : property.value, roots);
2849
+ break;
2850
+ case "ArrayPattern":
2851
+ for (const element of target.elements) if (element) collectWriteRoots(element, roots);
2852
+ break;
2853
+ case "AssignmentPattern":
2854
+ collectWriteRoots(target.left, roots);
2855
+ break;
2856
+ case "RestElement":
2857
+ collectWriteRoots(target.argument, roots);
2858
+ break;
2859
+ default: roots.push(target);
2860
+ }
2861
+ }
2862
+ /**
2780
2863
  * Whether Solid would pass an attribute expression as a getter. The JSX
2781
2864
  * transform wraps any expression that reads a member or calls a function.
2782
2865
  */
@@ -2838,10 +2921,10 @@ function functionOf(binding, options) {
2838
2921
  /**
2839
2922
  * The attributes of a call site by name, or `undefined` when one cannot be inlined.
2840
2923
  */
2841
- function attributesOf(element) {
2924
+ function attributesOf(context, element) {
2842
2925
  const attributes = /* @__PURE__ */ new Map();
2843
2926
  for (const attribute of element.openingElement.attributes) {
2844
- if (attribute.type !== "JSXAttribute" || attribute.name.type !== "JSXIdentifier" || attribute.name.name === "ref" && !isForwardableRef(attribute) || attributes.has(attribute.name.name)) return;
2927
+ if (attribute.type !== "JSXAttribute" || attribute.name.type !== "JSXIdentifier" || attribute.name.name === "ref" && !isForwardableRef(context, attribute) || attributes.has(attribute.name.name)) return;
2845
2928
  attributes.set(attribute.name.name, attribute);
2846
2929
  }
2847
2930
  return attributes;
@@ -2878,16 +2961,30 @@ function isMemberRead(read) {
2878
2961
  * assigned the element, so it has to stay the name itself. Anything else
2879
2962
  * would be evaluated when the element is made, outside the `untrack` the
2880
2963
  * component's `ref` runs it in.
2964
+ *
2965
+ * Inside an array, `void 0` and `untrack(() => target)` count too. Solid
2966
+ * skips an empty entry of a ref array, and evaluates the whole `ref`
2967
+ * untracked. They come from a component that forwards `props.ref` in an
2968
+ * array, once a call site that passes no `ref` is inlined.
2881
2969
  */
2882
- function isForwardableRef(attribute) {
2970
+ function isForwardableRef(context, attribute) {
2883
2971
  const { value } = attribute;
2884
2972
  if (value?.type !== "JSXExpressionContainer" || value.expression.type === "JSXEmptyExpression") return false;
2885
- const isTarget = (node) => {
2973
+ const isTarget = (node, inArray) => {
2886
2974
  const inner = unwrap(node);
2887
- if (inner.type === "ArrayExpression") return inner.elements.every((element) => element !== null && element.type !== "SpreadElement" && isTarget(element));
2975
+ if (inner.type === "ArrayExpression") return inner.elements.every((element) => element !== null && element.type !== "SpreadElement" && isTarget(element, true));
2976
+ if (inArray && isVoidZero(inner)) return true;
2977
+ if (inArray && inner.type === "CallExpression" && solidCallee(context, inner) === "untrack") {
2978
+ const callback = inner.arguments.at(0);
2979
+ return inner.arguments.length === 1 && callback?.type === "ArrowFunctionExpression" && callback.expression && callback.params.length === 0 && callback.body.type !== "BlockStatement" && isTarget(callback.body, true);
2980
+ }
2888
2981
  return inner.type === "Identifier" || inner.type === "ArrowFunctionExpression" || inner.type === "FunctionExpression";
2889
2982
  };
2890
- return isTarget(value.expression);
2983
+ return isTarget(value.expression, false);
2984
+ }
2985
+ /** Whether an expression is `void 0`. */
2986
+ function isVoidZero(node) {
2987
+ return node.type === "UnaryExpression" && node.operator === "void" && node.argument.type === "Literal" && node.argument.value === 0;
2891
2988
  }
2892
2989
  /**
2893
2990
  * Why `attributesOf` turns down a call site, for the report.
@@ -2928,6 +3025,9 @@ var Inliner = class {
2928
3025
  this.hosts = /* @__PURE__ */ new Map();
2929
3026
  this.transparent = /* @__PURE__ */ new Map();
2930
3027
  this.reason = "";
3028
+ this.components = [];
3029
+ this.sites = [];
3030
+ this.blocked = /* @__PURE__ */ new Map();
2931
3031
  }
2932
3032
  /**
2933
3033
  * Whether a binding holds a component made by Solid's `lazy`, for the
@@ -2963,6 +3063,27 @@ var Inliner = class {
2963
3063
  const statement = this.context.parents.get(declaration);
2964
3064
  if (statement?.type === "VariableDeclaration" && statement.declarations.length === 1 && this.context.parents.get(statement)?.type === "Program") return statement;
2965
3065
  }
3066
+ /**
3067
+ * Whether statements assign, update, or delete through a binding declared
3068
+ * outside `scope`, or through a global. Writes inside nested functions
3069
+ * count too, since a function can run right away, like a memo's.
3070
+ */
3071
+ writesOutside(statements, scope) {
3072
+ const roots = [];
3073
+ const visit = (node) => {
3074
+ if (node.type === "AssignmentExpression") collectWriteRoots(node.left, roots);
3075
+ else if (node.type === "UpdateExpression") collectWriteRoots(node.argument, roots);
3076
+ else if (node.type === "UnaryExpression" && node.operator === "delete") collectWriteRoots(node.argument, roots);
3077
+ forEachChild(node, visit);
3078
+ };
3079
+ for (const statement of statements) visit(statement);
3080
+ for (const root of roots) {
3081
+ if (root.type !== "Identifier") return true;
3082
+ const target = this.context.scopes.references.get(root);
3083
+ if (!target || !isWithinScope(target.scope, scope)) return true;
3084
+ }
3085
+ return false;
3086
+ }
2966
3087
  analyzeComponent(binding) {
2967
3088
  if (!isCapitalized(binding.name)) return;
2968
3089
  if (binding.mutated) {
@@ -3019,6 +3140,10 @@ var Inliner = class {
3019
3140
  this.reason = "component-this";
3020
3141
  return;
3021
3142
  }
3143
+ if (this.writesOutside(statements, scope)) {
3144
+ this.reason = "component-write";
3145
+ return;
3146
+ }
3022
3147
  const param = fn.params.at(0);
3023
3148
  let paramBinding;
3024
3149
  if (param) {
@@ -3492,7 +3617,7 @@ var Inliner = class {
3492
3617
  * when it cannot be inlined there. Nothing is written until `commit`.
3493
3618
  */
3494
3619
  prepare(component, element) {
3495
- const attributes = attributesOf(element);
3620
+ const attributes = attributesOf(this.context, element);
3496
3621
  if (!attributes) {
3497
3622
  this.reason = callSiteReason(element);
3498
3623
  return;
@@ -3832,14 +3957,27 @@ var Inliner = class {
3832
3957
  byComponent.set(site.component, elements);
3833
3958
  }
3834
3959
  const result = /* @__PURE__ */ new Set();
3835
- if (this.context.options.alwaysInline) {
3836
- for (const component of byComponent.keys()) result.add(component);
3837
- return result;
3960
+ const { alwaysInline, alwaysInlineComponents } = this.context.options;
3961
+ for (const component of byComponent.keys()) if (alwaysInline || alwaysInlineComponents.has(component.binding.name)) {
3962
+ result.add(component);
3963
+ byComponent.delete(component);
3838
3964
  }
3965
+ if (byComponent.size === 0) return result;
3839
3966
  this.scratchNames = new Set(this.context.scopes.names);
3840
3967
  try {
3841
3968
  const copiesOf = /* @__PURE__ */ new Map();
3842
3969
  for (const [component, elements] of byComponent) copiesOf.set(component, new Map(elements.map((element) => [element, this.prepare(component, element)])));
3970
+ this.sites = sites;
3971
+ this.otherUses = otherUses;
3972
+ this.blocked = /* @__PURE__ */ new Map();
3973
+ for (const [inner, byElement] of copiesOf) for (const [element, copy] of byElement) {
3974
+ const outer = copy ? void 0 : this.components.find((item) => item !== inner && isWithin(element, item.fn));
3975
+ if (outer) {
3976
+ const list = this.blocked.get(outer) ?? [];
3977
+ list.push(inner);
3978
+ this.blocked.set(outer, list);
3979
+ }
3980
+ }
3843
3981
  for (const [component, byElement] of copiesOf) {
3844
3982
  const copies = [...byElement.values()].filter((copy) => copy !== void 0);
3845
3983
  if (copies.length === 0) continue;
@@ -3847,6 +3985,8 @@ var Inliner = class {
3847
3985
  }
3848
3986
  } finally {
3849
3987
  this.scratchNames = void 0;
3988
+ this.otherUses = void 0;
3989
+ this.blocked = /* @__PURE__ */ new Map();
3850
3990
  }
3851
3991
  return result;
3852
3992
  }
@@ -3901,14 +4041,52 @@ var Inliner = class {
3901
4041
  const estimator = this.estimator();
3902
4042
  let calls = share > 0 && component.declaration ? share * estimator.node(component.declaration) : 0;
3903
4043
  let inlined = 0;
4044
+ const blocked = this.blockedWithin(component);
4045
+ const kept = /* @__PURE__ */ new Set();
3904
4046
  for (const copy of copies) {
3905
4047
  const inTemplate = this.sitsInTemplate(copy.element);
3906
4048
  calls += estimator.jsx(copy.element, inTemplate);
3907
- inlined += copySize(this.context.filename, this.sizeHeader(), copy, inTemplate, this.context.options);
4049
+ const measured = { code: "" };
4050
+ inlined += copySize(this.context.filename, this.sizeHeader(), copy, inTemplate, this.context.options, blocked.length > 0 ? {
4051
+ declarations: this.declarationsOf(blocked),
4052
+ inline
4053
+ } : void 0, measured);
4054
+ const body = measured.code.slice(measured.code.lastIndexOf(COPY_WRAPPER));
4055
+ for (const inner of blocked) if (hasTag(body, inner.binding.name)) kept.add(inner);
4056
+ }
4057
+ if (share > 0) {
4058
+ for (const inner of blocked) if (!kept.has(inner) && inner.declaration && this.onlyUsedWithin(inner, component)) calls += share * estimator.node(inner.declaration);
3908
4059
  }
3909
4060
  return calls - inlined;
3910
4061
  }
3911
4062
  /**
4063
+ * The components whose calls in a component's body cannot be inlined
4064
+ * there, but may be in a copy, once the call site resolves the props
4065
+ * they are given. Those they call in turn count too.
4066
+ */
4067
+ blockedWithin(component) {
4068
+ const found = [];
4069
+ const pending = [component];
4070
+ for (let outer = pending.pop(); outer; outer = pending.pop()) for (const inner of this.blocked.get(outer) ?? []) if (inner !== component && !found.includes(inner)) {
4071
+ found.push(inner);
4072
+ pending.push(inner);
4073
+ }
4074
+ return found;
4075
+ }
4076
+ /** The declarations of components, for a copy measured on its own. */
4077
+ declarationsOf(components) {
4078
+ const texts = [];
4079
+ for (const component of components) {
4080
+ const statement = this.topLevelStatement(component.binding.declaration);
4081
+ if (statement) texts.push(textOf(this.context, statement));
4082
+ }
4083
+ return texts.join("\n");
4084
+ }
4085
+ /** Whether every call of `inner` is in `outer`, and nothing else uses it. */
4086
+ onlyUsedWithin(inner, outer) {
4087
+ return this.otherUses?.get(inner) === 0 && this.sites.every((site) => site.component !== inner || isWithin(site.element, outer.fn));
4088
+ }
4089
+ /**
3912
4090
  * Whether an element sits directly in an intrinsic element, whose
3913
4091
  * template its copy joins. A provider this pass makes transparent is
3914
4092
  * removed once its consumers are inlined, so the element above it counts.
@@ -3923,6 +4101,15 @@ var Inliner = class {
3923
4101
  this.sizeEstimator ??= new SizeEstimator(this.context.code);
3924
4102
  return this.sizeEstimator;
3925
4103
  }
4104
+ /** The top-level statement a node is part of, without an `export`. */
4105
+ topLevelStatement(node) {
4106
+ let current = node;
4107
+ for (let parent = this.context.parents.get(current); parent;) {
4108
+ if (parent.type === "Program") return current.type === "ExportNamedDeclaration" || current.type === "ExportDefaultDeclaration" ? current.declaration ?? void 0 : current;
4109
+ current = parent;
4110
+ parent = this.context.parents.get(current);
4111
+ }
4112
+ }
3926
4113
  /**
3927
4114
  * What a copy measured on its own needs to know: the module's imports,
3928
4115
  * and the names that alias Solid's exports.
@@ -3936,8 +4123,56 @@ var Inliner = class {
3936
4123
  }
3937
4124
  return this.header;
3938
4125
  }
4126
+ /**
4127
+ * The component a top-level alias like `const Button = ButtonRoot` names,
4128
+ * or `undefined` when the binding is not one.
4129
+ */
4130
+ aliasTarget(binding) {
4131
+ const { declaration } = binding;
4132
+ if (!isCapitalized(binding.name) || !isConstantDeclaration(binding, this.context.options) || declaration.type !== "VariableDeclarator" || declaration.id !== binding.identifier || !declaration.init) return;
4133
+ const init = unwrap(declaration.init);
4134
+ if (init.type !== "Identifier") return;
4135
+ const target = this.context.scopes.references.get(init);
4136
+ return target && target !== binding && target.scope.parent === void 0 && !target.mutated && isCapitalized(target.name) ? target : void 0;
4137
+ }
4138
+ /**
4139
+ * The statement of an alias nothing uses that `reference` is the value
4140
+ * of, like `const Separator = SeparatorRoot` once its tags are renamed.
4141
+ * It does not keep the component, and goes away with it.
4142
+ */
4143
+ unusedAlias(reference) {
4144
+ const declarator = this.context.parents.get(reference);
4145
+ if (declarator?.type !== "VariableDeclarator" || declarator.id.type !== "Identifier") return;
4146
+ const alias = this.context.scopes.root.bindings.get(declarator.id.name);
4147
+ const statement = this.context.parents.get(declarator);
4148
+ return alias?.declaration === declarator && this.aliasTarget(alias) !== void 0 && alias.references.length === 0 && statement?.type === "VariableDeclaration" && statement.declarations.length === 1 && this.context.parents.get(statement)?.type === "Program" ? statement : void 0;
4149
+ }
4150
+ /**
4151
+ * Renames each tag of an alias to the component it names, where that name
4152
+ * means the same. Libraries often export a component under a second name,
4153
+ * like `const Separator = SeparatorRoot`. The next pass inlines the calls.
4154
+ */
4155
+ renameAliasTags() {
4156
+ let renamed = false;
4157
+ for (const binding of this.context.scopes.root.bindings.values()) {
4158
+ const target = this.aliasTarget(binding);
4159
+ if (!target) continue;
4160
+ for (const reference of binding.references) {
4161
+ const parent = this.context.parents.get(reference);
4162
+ if (parent?.type !== "JSXOpeningElement" && parent?.type !== "JSXClosingElement" || parent.name !== reference) continue;
4163
+ if (lookup(scopeAt(this.context.scopes, this.context.parents, reference), target.name) !== target) continue;
4164
+ this.context.s.overwrite(reference.start, reference.end, target.name);
4165
+ renamed = true;
4166
+ }
4167
+ }
4168
+ return renamed;
4169
+ }
3939
4170
  run() {
3940
- const components = [];
4171
+ if (this.renameAliasTags()) {
4172
+ this.changed = true;
4173
+ return;
4174
+ }
4175
+ const { components } = this;
3941
4176
  const rejected = /* @__PURE__ */ new Map();
3942
4177
  for (const binding of this.context.scopes.root.bindings.values()) {
3943
4178
  this.reason = "not-a-function";
@@ -3952,16 +4187,19 @@ var Inliner = class {
3952
4187
  }
3953
4188
  const sites = [];
3954
4189
  const otherUses = /* @__PURE__ */ new Map();
4190
+ const aliases = /* @__PURE__ */ new Map();
3955
4191
  for (const component of components) {
3956
4192
  let uses = 0;
3957
4193
  for (const reference of component.binding.references) {
3958
4194
  const parent = this.context.parents.get(reference);
3959
4195
  if (parent?.type === "JSXClosingElement") continue;
3960
4196
  const element = parent ? this.context.parents.get(parent) : void 0;
4197
+ const alias = this.unusedAlias(reference);
3961
4198
  if (parent?.type === "JSXOpeningElement" && element?.type === "JSXElement") sites.push({
3962
4199
  component,
3963
4200
  element
3964
4201
  });
4202
+ else if (alias) aliases.set(component, [...aliases.get(component) ?? [], alias]);
3965
4203
  else uses += 1;
3966
4204
  }
3967
4205
  otherUses.set(component, uses);
@@ -3993,7 +4231,10 @@ var Inliner = class {
3993
4231
  const copied = [...inlined.keys()];
3994
4232
  for (const [component, elements] of inlined) {
3995
4233
  const insideCopy = elements.some((element) => copied.some((other) => other !== component && element.start >= other.fn.start && element.end <= other.fn.end));
3996
- if (component.declaration && otherUses.get(component) === 0 && !insideCopy) this.context.s.remove(component.declaration.start, component.declaration.end);
4234
+ if (component.declaration && otherUses.get(component) === 0 && !insideCopy) {
4235
+ this.context.s.remove(component.declaration.start, component.declaration.end);
4236
+ for (const alias of aliases.get(component) ?? []) this.context.s.remove(alias.start, alias.end);
4237
+ }
3997
4238
  }
3998
4239
  }
3999
4240
  /**
@@ -4423,7 +4664,8 @@ function resolveOptions(options) {
4423
4664
  globalConstants: new Map(Object.entries(options.globalConstants ?? {})),
4424
4665
  importedContexts: new Map(Object.entries(options.importedContexts ?? {}).map(([source, names]) => [source, new Set(names)])),
4425
4666
  sharedComponents: new Map(Object.entries(options.sharedComponents ?? {})),
4426
- alwaysInline: options.alwaysInline ?? false
4667
+ alwaysInline: options.alwaysInline ?? false,
4668
+ alwaysInlineComponents: new Set(options.alwaysInlineComponents ?? [])
4427
4669
  };
4428
4670
  }
4429
4671
  function parseCode(code, filename) {
@@ -4531,4 +4773,4 @@ function readModuleConstants(code, options = {}) {
4531
4773
  //#endregion
4532
4774
  export { lookup as a, forEachChild as c, unwrap as d, analyzeScopes as i, isIntrinsicTag as l, readModuleConstants as n, scopeAt as o, CONTEXT_SAFE_PRIMITIVES as r, collectParents as s, compile as t, parse as u };
4533
4775
 
4534
- //# sourceMappingURL=compile-BpoiBa6b.mjs.map
4776
+ //# sourceMappingURL=compile-sCZdwEKG.mjs.map