solid-optimizer 0.2.0 → 0.3.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.
Files changed (51) hide show
  1. package/README.md +269 -14
  2. package/dist/compile-BroGlagZ.d.mts +172 -0
  3. package/dist/compile-BroGlagZ.d.mts.map +1 -0
  4. package/dist/compile-ocDYvJUW.mjs +3910 -0
  5. package/dist/compile-ocDYvJUW.mjs.map +1 -0
  6. package/dist/index.d.mts +2 -0
  7. package/dist/index.mjs +2 -0
  8. package/dist/vite.d.mts +35 -0
  9. package/dist/vite.d.mts.map +1 -0
  10. package/dist/vite.mjs +1465 -0
  11. package/dist/vite.mjs.map +1 -0
  12. package/package.json +60 -58
  13. package/src/ast.ts +263 -0
  14. package/src/compile.ts +304 -0
  15. package/src/constants.ts +249 -0
  16. package/src/context.ts +87 -0
  17. package/src/fold.ts +850 -0
  18. package/src/index.ts +4 -107
  19. package/src/inline.ts +2028 -0
  20. package/src/jsx.ts +170 -0
  21. package/src/memo.ts +383 -0
  22. package/src/provider.ts +842 -0
  23. package/src/scope.ts +588 -0
  24. package/src/server.ts +275 -0
  25. package/src/size.ts +307 -0
  26. package/src/value.ts +386 -0
  27. package/src/vite/index.ts +1135 -0
  28. package/src/vite/inject.ts +311 -0
  29. package/src/vite/namespace.ts +66 -0
  30. package/src/vite/runtime.ts +390 -0
  31. package/src/vite/usage.ts +405 -0
  32. package/dist/cjs/development/index.cjs +0 -228
  33. package/dist/cjs/development/index.cjs.map +0 -7
  34. package/dist/cjs/production/index.cjs +0 -1
  35. package/dist/esm/development/index.mjs +0 -197
  36. package/dist/esm/development/index.mjs.map +0 -7
  37. package/dist/esm/production/index.mjs +0 -1
  38. package/dist/types/checks.d.ts +0 -9
  39. package/dist/types/checks.d.ts.map +0 -1
  40. package/dist/types/index.d.ts +0 -3
  41. package/dist/types/index.d.ts.map +0 -1
  42. package/dist/types/path-references-import.d.ts +0 -3
  43. package/dist/types/path-references-import.d.ts.map +0 -1
  44. package/dist/types/unwrap-node.d.ts +0 -7
  45. package/dist/types/unwrap-node.d.ts.map +0 -1
  46. package/dist/types/unwrap-path.d.ts +0 -6
  47. package/dist/types/unwrap-path.d.ts.map +0 -1
  48. package/src/checks.ts +0 -42
  49. package/src/path-references-import.ts +0 -82
  50. package/src/unwrap-node.ts +0 -27
  51. package/src/unwrap-path.ts +0 -18
package/src/server.ts ADDED
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The server pass: rewrites Solid's reactive primitives to what they do on the server.
3
+ *
4
+ * It runs once, after the other passes. Running it first would change what
5
+ * the inliner and fold pass see on the server but not on the client, and the
6
+ * two builds would render different trees. A component whose only statement
7
+ * is `onMount(...)` would inline on the server and stay a component on the
8
+ * client, which breaks hydration. It still runs while modules are
9
+ * transformed, so the bundler drops whatever only the removed calls used.
10
+ *
11
+ * On the server, Solid renders once and never updates, so most primitives
12
+ * reduce to a plain call (`solid-js/dist/server.js` in Solid 1.9):
13
+ *
14
+ * - `createEffect(fn)` and `onMount(fn)` do nothing, so they are removed.
15
+ * Anything only they used, like a charting library, can then be dropped
16
+ * from the server bundle.
17
+ * - `untrack(fn)` and `batch(fn)` return `fn()`.
18
+ * - `startTransition(fn)` calls `fn()` and returns nothing.
19
+ * - `createDeferred(source)` returns `source`.
20
+ * - `getListener()` returns `null`.
21
+ * - `createMemo(fn, value)` runs `fn(value)` once and returns a getter for the
22
+ * result. `createRenderEffect(fn, value)` and `createComputed(fn, value)`
23
+ * run `fn(value)` once.
24
+ *
25
+ * A call with a spread argument is left alone, and so is a removed call whose
26
+ * arguments have side effects beyond creating functions.
27
+ *
28
+ * # Accepted differences
29
+ *
30
+ * `createMemo`, `createRenderEffect`, and `createComputed` run their function
31
+ * inside a new owner, and send an error to the nearest error handler. After
32
+ * the rewrite the function runs in the enclosing owner:
33
+ *
34
+ * - An `onCleanup` inside it registers on the enclosing owner.
35
+ * - Inside a `catchError` or `<ErrorBoundary>`, an error thrown by it stops
36
+ * the component that holds it, instead of leaving the memo `undefined` and
37
+ * rendering on. Without an error handler, both throw.
38
+ */
39
+ import type { CallExpression, Expression, Node } from 'oxc-parser';
40
+ import { forEachChild, isPrimary, unwrap } from './ast';
41
+ import type { PassContext } from './context';
42
+ import { solidExport, textOf } from './context';
43
+ import { acceptsAnyExpression } from './inline';
44
+ import { isSideEffectFree } from './value';
45
+
46
+ /** Calls the server does not run. */
47
+ const REMOVED = new Set(['createEffect', 'onMount']);
48
+
49
+ /** Calls the server runs once, in place. */
50
+ const RUN_ONCE = new Set(['createRenderEffect', 'createComputed']);
51
+
52
+ /**
53
+ * Whether a statement starting with `text` could join the statement before
54
+ * it when that one has no semicolon.
55
+ */
56
+ function continuesPreviousStatement(text: string): boolean {
57
+ return /^[([`+\-/]/.test(text);
58
+ }
59
+
60
+ class ServerSimplifier {
61
+ changed = false;
62
+
63
+ constructor(private readonly context: PassContext) {}
64
+
65
+ /**
66
+ * The Solid export a callee refers to, through a named import, an alias,
67
+ * or a namespace import like `solid.untrack`.
68
+ */
69
+ private calleeName(callee: Node): string | undefined {
70
+ const { references } = this.context.scopes;
71
+ if (callee.type === 'Identifier') {
72
+ const binding = references.get(callee);
73
+ return binding ? solidExport(binding, this.context.options) : undefined;
74
+ }
75
+ if (callee.type !== 'MemberExpression' || callee.object.type !== 'Identifier') {
76
+ return undefined;
77
+ }
78
+ const binding = references.get(callee.object);
79
+ if (
80
+ binding?.kind !== 'import' ||
81
+ binding.imported !== '*' ||
82
+ binding.source === undefined ||
83
+ !this.context.options.moduleSources.includes(binding.source)
84
+ ) {
85
+ return undefined;
86
+ }
87
+ if (!callee.computed && callee.property.type === 'Identifier') {
88
+ return callee.property.name;
89
+ }
90
+ if (
91
+ callee.computed &&
92
+ callee.property.type === 'Literal' &&
93
+ typeof callee.property.value === 'string'
94
+ ) {
95
+ return callee.property.value;
96
+ }
97
+ return undefined;
98
+ }
99
+
100
+ /**
101
+ * Whether dropping `node` loses nothing observable. Solid's `on` only
102
+ * creates a function, so `createEffect(on(source, fn))` can go too.
103
+ */
104
+ private isDiscardable(node: Node): boolean {
105
+ if (isSideEffectFree(node)) {
106
+ return true;
107
+ }
108
+ const inner = node.type === 'ParenthesizedExpression' ? unwrap(node) : node;
109
+ return (
110
+ inner.type === 'CallExpression' &&
111
+ this.calleeName(inner.callee) === 'on' &&
112
+ inner.arguments.every(
113
+ (argument) => argument.type !== 'SpreadElement' && this.isDiscardable(argument),
114
+ )
115
+ );
116
+ }
117
+
118
+ /**
119
+ * The text of calling `fn` with `args`, the way Solid's server calls it,
120
+ * and whether it binds as tightly as a call does.
121
+ */
122
+ private callText(fn: Expression, args: readonly Expression[]): { text: string; call: boolean } {
123
+ const inner = unwrap(fn);
124
+ const argsText = args.map((argument) => textOf(this.context, argument)).join(', ');
125
+ if (
126
+ inner.type === 'ArrowFunctionExpression' &&
127
+ inner.expression &&
128
+ inner.params.length === 0 &&
129
+ args.length === 0 &&
130
+ inner.body.type !== 'BlockStatement'
131
+ ) {
132
+ // `() => value` called with nothing is `value`.
133
+ const { body } = inner;
134
+ return {
135
+ text: textOf(this.context, body),
136
+ call: isPrimary(body) || body.type === 'CallExpression',
137
+ };
138
+ }
139
+ const text = textOf(this.context, fn);
140
+ if (inner.type === 'Identifier') {
141
+ return { text: `${text}(${argsText})`, call: true };
142
+ }
143
+ if (
144
+ inner.type === 'ArrowFunctionExpression' ||
145
+ inner.type === 'FunctionExpression' ||
146
+ fn.type === 'ParenthesizedExpression'
147
+ ) {
148
+ return { text: `(${text})(${argsText})`, call: true };
149
+ }
150
+ // `(0, obj.method)()` calls without `obj` as `this`, like Solid does.
151
+ return { text: `(0, ${text})(${argsText})`, call: true };
152
+ }
153
+
154
+ /**
155
+ * Whether a statement at `position` could be read as a continuation of
156
+ * the one before it, which happens when that one has no semicolon.
157
+ */
158
+ private followsOpenStatement(position: number): boolean {
159
+ const before = this.context.code.slice(0, position).trimEnd();
160
+ return before !== '' && !before.endsWith(';') && !before.endsWith('{');
161
+ }
162
+
163
+ private replace(call: CallExpression, text: string | undefined, primary = false): void {
164
+ const parent = this.context.parents.get(call);
165
+ if (parent?.type === 'ExpressionStatement') {
166
+ if (text === undefined) {
167
+ // A statement in a list can go. One that is the whole body of an
168
+ // `if` or a loop has to leave an empty statement behind.
169
+ const list = this.context.parents.get(parent)?.type;
170
+ const inList =
171
+ list === 'Program' ||
172
+ list === 'BlockStatement' ||
173
+ list === 'StaticBlock' ||
174
+ list === 'SwitchCase';
175
+ if (inList) {
176
+ this.context.s.remove(parent.start, parent.end);
177
+ } else {
178
+ this.context.s.overwrite(parent.start, parent.end, ';');
179
+ }
180
+ } else {
181
+ let statement = text;
182
+ // A statement cannot start with `{`, `function`, or `class`.
183
+ if (/^(\{|function\b|async function\b|class\b)/.test(statement)) {
184
+ statement = `(${statement})`;
185
+ }
186
+ const guarded =
187
+ continuesPreviousStatement(statement) && this.followsOpenStatement(parent.start);
188
+ this.context.s.overwrite(call.start, call.end, guarded ? `;${statement}` : statement);
189
+ }
190
+ } else {
191
+ const value = text ?? 'void 0';
192
+ // `new (f())()` is not `new f()()`.
193
+ const isNewCallee = parent?.type === 'NewExpression' && parent.callee === call;
194
+ const bare = !isNewCallee && (primary || acceptsAnyExpression(this.context, call));
195
+ this.context.s.overwrite(call.start, call.end, bare ? value : `(${value})`);
196
+ }
197
+ this.changed = true;
198
+ }
199
+
200
+ private simplify(call: CallExpression): void {
201
+ const name = this.calleeName(call.callee);
202
+ if (name === undefined || call.arguments.some((arg) => arg.type === 'SpreadElement')) {
203
+ return;
204
+ }
205
+ // Spread arguments were ruled out above.
206
+ const args = call.arguments.filter((arg): arg is Expression => arg.type !== 'SpreadElement');
207
+ const first = args.at(0);
208
+ const second = args.at(1);
209
+ const rest = args.slice(2);
210
+ const inStatement = this.context.parents.get(call)?.type === 'ExpressionStatement';
211
+
212
+ if (REMOVED.has(name)) {
213
+ if (args.every((arg) => this.isDiscardable(arg))) {
214
+ this.replace(call, undefined);
215
+ }
216
+ return;
217
+ }
218
+ switch (name) {
219
+ case 'getListener':
220
+ if (args.length === 0) {
221
+ this.replace(call, 'null');
222
+ }
223
+ return;
224
+ case 'untrack':
225
+ case 'batch':
226
+ if (first && args.length === 1) {
227
+ const run = this.callText(first, []);
228
+ this.replace(call, run.text, run.call);
229
+ }
230
+ return;
231
+ case 'startTransition':
232
+ if (first && args.length === 1) {
233
+ const { text } = this.callText(first, []);
234
+ this.replace(call, inStatement ? text : `(${text}, void 0)`, !inStatement);
235
+ }
236
+ return;
237
+ case 'createDeferred':
238
+ if (first && args.slice(1).every((arg) => this.isDiscardable(arg))) {
239
+ const text = textOf(this.context, first);
240
+ this.replace(call, text, isPrimary(first));
241
+ }
242
+ return;
243
+ case 'createMemo':
244
+ // `createMemo(fn, value, options)`: the options only matter for updates.
245
+ if (first && rest.every((arg) => this.isDiscardable(arg))) {
246
+ const { text } = this.callText(first, second ? [second] : []);
247
+ this.replace(call, `((value) => () => value)(${text})`, true);
248
+ }
249
+ return;
250
+ default:
251
+ if (RUN_ONCE.has(name) && first && rest.length === 0) {
252
+ const { text } = this.callText(first, second ? [second] : []);
253
+ this.replace(call, inStatement ? text : `(${text}, void 0)`, !inStatement);
254
+ }
255
+ }
256
+ }
257
+
258
+ walk(node: Node): void {
259
+ forEachChild(node, (child) => {
260
+ this.walk(child);
261
+ });
262
+ if (node.type === 'CallExpression') {
263
+ this.simplify(node);
264
+ }
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Runs the server pass over a parsed program. Returns whether anything changed.
270
+ */
271
+ export function simplifyServer(context: PassContext): boolean {
272
+ const simplifier = new ServerSimplifier(context);
273
+ simplifier.walk(context.program);
274
+ return simplifier.changed;
275
+ }
package/src/size.ts ADDED
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Estimates how many bytes code takes once Solid's JSX transform has
3
+ * lowered it and a minifier has compacted it.
4
+ *
5
+ * The inline pass compares the call sites of a component with the copies
6
+ * that would replace them. A copy merges its elements into the template
7
+ * around it and drops the component call, but repeats the component's own
8
+ * code at every call. The estimate only has to rank the two, so it counts
9
+ * what lowering adds to the JSX as written:
10
+ *
11
+ * - each template: its declaration and the clone that renders it;
12
+ * - each dynamic attribute, child, spread, or event handler of an element:
13
+ * the effect or `insert` that sets it, and the walk to its element;
14
+ * - each component element: the `createComponent` call, and a getter for
15
+ * each prop that is not a literal.
16
+ *
17
+ * Other code counts as its text without the whitespace a minifier removes.
18
+ */
19
+ import type {
20
+ JSXAttribute,
21
+ JSXAttributeItem,
22
+ JSXChild,
23
+ JSXElement,
24
+ JSXElementName,
25
+ JSXFragment,
26
+ Node,
27
+ } from 'oxc-parser';
28
+ import MagicString from 'magic-string';
29
+ import {
30
+ collectParents,
31
+ forEachChild,
32
+ isInsignificant,
33
+ isIntrinsicTag,
34
+ parse,
35
+ unwrap,
36
+ } from './ast';
37
+ import type { ResolvedOptions } from './context';
38
+ import { fold } from './fold';
39
+ import { analyzeScopes } from './scope';
40
+
41
+ /** A template's declaration, and the function that clones and returns it. */
42
+ const TEMPLATE = 40;
43
+ /** A walk to an element, like `e.firstChild.nextSibling`. */
44
+ const WALK = 12;
45
+ /** An `insert()` of a dynamic child. */
46
+ const INSERT = 12;
47
+ /** A render effect that sets an attribute, like `createRenderEffect(() => setAttribute(...))`. */
48
+ const EFFECT = 24;
49
+ /** An event handler assignment, like `e.$$click = ...`. */
50
+ const HANDLER = 10;
51
+ /** A `spread()` of props onto an element. */
52
+ const SPREAD = 16;
53
+ /** A `createComponent(Name, {})` call. */
54
+ const COMPONENT = 8;
55
+ /** A getter, `get name() { return ... }`. */
56
+ const GETTER = 16;
57
+ /** A `mergeProps()` around the props of a component with a spread. */
58
+ const MERGE = 6;
59
+
60
+ /**
61
+ * The length of `text` once a minifier removes the whitespace it does not need.
62
+ */
63
+ export function compactLength(text: string): number {
64
+ return text.replaceAll(/\s*([{}()[\];,:=<>+\-*/?&|!.])\s*/g, '$1').replaceAll(/\s+/g, ' ').length;
65
+ }
66
+
67
+ function nameLength(name: JSXElementName): number {
68
+ switch (name.type) {
69
+ case 'JSXIdentifier':
70
+ return name.name.length;
71
+ case 'JSXNamespacedName':
72
+ return name.namespace.name.length + name.name.name.length + 1;
73
+ case 'JSXMemberExpression':
74
+ return nameLength(name.object) + name.property.name.length + 1;
75
+ default:
76
+ return 4;
77
+ }
78
+ }
79
+
80
+ function isIntrinsic(element: JSXElement): boolean {
81
+ const { name } = element.openingElement;
82
+ return name.type === 'JSXIdentifier' && isIntrinsicTag(name.name);
83
+ }
84
+
85
+ function attributeName(attribute: JSXAttribute): string {
86
+ const { name } = attribute;
87
+ return name.type === 'JSXIdentifier' ? name.name : `${name.namespace.name}:${name.name.name}`;
88
+ }
89
+
90
+ /**
91
+ * Estimates lowered sizes in one piece of code.
92
+ */
93
+ export class SizeEstimator {
94
+ constructor(private readonly code: string) {}
95
+
96
+ private text(node: Node): number {
97
+ return compactLength(this.code.slice(node.start, node.end));
98
+ }
99
+
100
+ /**
101
+ * The size of any node: JSX as lowered, other code as its compact text
102
+ * with the JSX in it as lowered.
103
+ */
104
+ node(node: Node): number {
105
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
106
+ return this.jsx(node, false);
107
+ }
108
+ let size = this.text(node);
109
+ const visit = (child: Node): void => {
110
+ if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
111
+ size += this.jsx(child, false) - this.text(child);
112
+ return;
113
+ }
114
+ forEachChild(child, visit);
115
+ };
116
+ forEachChild(node, visit);
117
+ return size;
118
+ }
119
+
120
+ /**
121
+ * The size of a JSX element or fragment. `inTemplate` is whether it sits
122
+ * directly in an element, whose template it joins.
123
+ */
124
+ jsx(node: JSXElement | JSXFragment, inTemplate: boolean): number {
125
+ if (node.type === 'JSXFragment') {
126
+ return this.children(node.children) + 2;
127
+ }
128
+ if (!isIntrinsic(node)) {
129
+ return (inTemplate ? INSERT + WALK : 0) + this.component(node);
130
+ }
131
+ const tag = nameLength(node.openingElement.name);
132
+ let size = (inTemplate ? 0 : TEMPLATE) + tag * 2 + 5;
133
+ let dynamic = false;
134
+ for (const attribute of node.openingElement.attributes) {
135
+ const cost = this.elementAttribute(attribute);
136
+ size += cost.size;
137
+ dynamic ||= cost.dynamic;
138
+ }
139
+ for (const child of node.children) {
140
+ if (isInsignificant(child)) {
141
+ continue;
142
+ }
143
+ if (child.type === 'JSXText') {
144
+ size += compactLength(child.value);
145
+ } else if (child.type === 'JSXElement') {
146
+ size += this.jsx(child, true);
147
+ } else {
148
+ size += INSERT + this.child(child);
149
+ dynamic = true;
150
+ }
151
+ }
152
+ return size + (dynamic ? WALK : 0);
153
+ }
154
+
155
+ private elementAttribute(attribute: JSXAttributeItem): { size: number; dynamic: boolean } {
156
+ if (attribute.type === 'JSXSpreadAttribute') {
157
+ return { size: SPREAD + this.node(attribute.argument), dynamic: true };
158
+ }
159
+ const name = attributeName(attribute);
160
+ const { value } = attribute;
161
+ if (!value || value.type === 'Literal') {
162
+ return { size: name.length + (value ? this.text(value) : 0) + 1, dynamic: false };
163
+ }
164
+ if (value.type !== 'JSXExpressionContainer') {
165
+ return { size: name.length + 1 + this.jsx(value, false), dynamic: true };
166
+ }
167
+ const { expression } = value;
168
+ if (expression.type === 'JSXEmptyExpression') {
169
+ return { size: 0, dynamic: false };
170
+ }
171
+ const inner = unwrap(expression);
172
+ // A literal in braces lowers like a quoted value.
173
+ if (
174
+ inner.type === 'Literal' ||
175
+ (inner.type === 'TemplateLiteral' && inner.expressions.length === 0)
176
+ ) {
177
+ return { size: name.length + this.text(inner) + 1, dynamic: false };
178
+ }
179
+ const extra = /^on[A-Z:]/.test(name) || name === 'ref' ? HANDLER : EFFECT;
180
+ return { size: extra + name.length + this.node(inner), dynamic: true };
181
+ }
182
+
183
+ private child(child: JSXChild): number {
184
+ if (child.type === 'JSXExpressionContainer') {
185
+ return child.expression.type === 'JSXEmptyExpression' ? 0 : this.node(child.expression);
186
+ }
187
+ if (child.type === 'JSXSpreadChild') {
188
+ return this.node(child.expression);
189
+ }
190
+ if (child.type === 'JSXText') {
191
+ return compactLength(child.value) + 2;
192
+ }
193
+ return this.jsx(child, false);
194
+ }
195
+
196
+ /**
197
+ * Children outside a template, which lower to an array of values.
198
+ */
199
+ private children(children: readonly JSXChild[]): number {
200
+ let size = 0;
201
+ for (const child of children) {
202
+ if (!isInsignificant(child)) {
203
+ size += this.child(child) + 1;
204
+ }
205
+ }
206
+ return size;
207
+ }
208
+
209
+ private component(element: JSXElement): number {
210
+ let size = COMPONENT + nameLength(element.openingElement.name);
211
+ let spread = false;
212
+ for (const attribute of element.openingElement.attributes) {
213
+ if (attribute.type === 'JSXSpreadAttribute') {
214
+ spread = true;
215
+ size += this.node(attribute.argument) + 1;
216
+ continue;
217
+ }
218
+ const name = attributeName(attribute);
219
+ const { value } = attribute;
220
+ if (!value || value.type === 'Literal') {
221
+ size += name.length + 1 + (value ? this.text(value) : 4);
222
+ } else if (value.type === 'JSXExpressionContainer') {
223
+ const { expression } = value;
224
+ if (expression.type !== 'JSXEmptyExpression') {
225
+ const inner = unwrap(expression);
226
+ const literal =
227
+ inner.type === 'Literal' ||
228
+ inner.type === 'Identifier' ||
229
+ inner.type === 'ArrowFunctionExpression' ||
230
+ inner.type === 'FunctionExpression';
231
+ size += name.length + 1 + (literal ? 0 : GETTER) + this.node(inner);
232
+ }
233
+ } else {
234
+ size += name.length + GETTER + this.jsx(value, false);
235
+ }
236
+ }
237
+ const significant = element.children.filter((child) => !isInsignificant(child));
238
+ if (significant.length > 0) {
239
+ size += GETTER + 'children'.length + this.children(significant);
240
+ }
241
+ return size + (spread ? MERGE : 0);
242
+ }
243
+ }
244
+
245
+ /** The name of the function a copy is wrapped in to be folded and measured. */
246
+ const WRAPPER = '__so_size__';
247
+
248
+ export interface Copy {
249
+ /** The statements the copy hoists out of the JSX. */
250
+ readonly statements: readonly string[];
251
+ /** The JSX that replaces the call site. */
252
+ readonly root: string;
253
+ }
254
+
255
+ /**
256
+ * The size of a component's copy at one call site, once its props have
257
+ * folded. `header` declares the names the fold pass needs to know, like
258
+ * imports of Solid. `inTemplate` is whether the call site sits directly in
259
+ * an element.
260
+ */
261
+ export function copySize(
262
+ filename: string,
263
+ header: string,
264
+ copy: Copy,
265
+ inTemplate: boolean,
266
+ options: ResolvedOptions,
267
+ ): number {
268
+ let code = `${header}\nfunction ${WRAPPER}() {\n${copy.statements.join('\n')}\nreturn (${copy.root});\n}\n`;
269
+ // Constant props fold the copy's conditions, as later passes would.
270
+ for (let round = 0; round < 3; round += 1) {
271
+ const program = parse(filename, code);
272
+ const s = new MagicString(code);
273
+ const changed = fold({
274
+ code,
275
+ filename,
276
+ s,
277
+ program,
278
+ parents: collectParents(program),
279
+ scopes: analyzeScopes(program),
280
+ options,
281
+ });
282
+ if (!changed) {
283
+ break;
284
+ }
285
+ code = s.toString();
286
+ }
287
+ const program = parse(filename, code);
288
+ const wrapper = program.body.at(-1);
289
+ if (wrapper?.type !== 'FunctionDeclaration' || !wrapper.body) {
290
+ return Number.POSITIVE_INFINITY;
291
+ }
292
+ const estimator = new SizeEstimator(code);
293
+ let size = 0;
294
+ for (const statement of wrapper.body.body) {
295
+ if (statement.type !== 'ReturnStatement') {
296
+ size += estimator.node(statement);
297
+ continue;
298
+ }
299
+ const argument = statement.argument ? unwrap(statement.argument) : undefined;
300
+ if (argument?.type === 'JSXElement' || argument?.type === 'JSXFragment') {
301
+ size += estimator.jsx(argument, inTemplate);
302
+ } else if (argument) {
303
+ size += (inTemplate ? INSERT + WALK : 0) + estimator.node(argument);
304
+ }
305
+ }
306
+ return size;
307
+ }