solid-optimizer 1.0.0-next.6 → 1.0.0-next.8

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.
@@ -1,6 +1,7 @@
1
1
  import remapping from "@jridgewell/remapping";
2
2
  import MagicString from "magic-string";
3
3
  import { parseSync, rawTransferSupported, visitorKeys } from "oxc-parser";
4
+ import { parse, parseFragment, serialize } from "parse5";
4
5
  //#region src/ast.ts
5
6
  /**
6
7
  * Keys that only hold TypeScript types. Types never run, so no pass reads or rewrites them.
@@ -65,7 +66,7 @@ function collectParents(program) {
65
66
  * is several times faster to read. It is not in the options' type yet.
66
67
  */
67
68
  const RAW_TRANSFER = rawTransferSupported();
68
- function parse(filename, code) {
69
+ function parse$1(filename, code) {
69
70
  const options = {
70
71
  lang: getLanguage(filename),
71
72
  sourceType: "module",
@@ -923,6 +924,16 @@ function namedImportSources(program, scopes = analyzeScopes(program)) {
923
924
  return [...sources];
924
925
  }
925
926
  /**
927
+ * The modules a module still imports once its types are stripped: the
928
+ * sources of `namedImportSources`, and imports for side effects only, like
929
+ * `import './setup'`.
930
+ */
931
+ function runtimeImportSources(program, scopes = analyzeScopes(program)) {
932
+ const sources = new Set(namedImportSources(program, scopes));
933
+ for (const statement of program.body) if (statement.type === "ImportDeclaration" && statement.importKind !== "type" && statement.specifiers.length === 0) sources.add(statement.source.value);
934
+ return [...sources];
935
+ }
936
+ /**
926
937
  * Whether the module reads one of these import bindings as a value. Scope
927
938
  * analysis skips type positions, so a binding used only in types has no
928
939
  * references.
@@ -993,7 +1004,7 @@ function constantExports(program, options, scopes = analyzeScopes(program)) {
993
1004
  //#endregion
994
1005
  //#region src/jsx.ts
995
1006
  function keptPiece(node) {
996
- const text = node.type === "JSXText" ? node : void 0;
1007
+ const text = node.type === "JSXText" ? node.value : void 0;
997
1008
  return {
998
1009
  node,
999
1010
  text: void 0,
@@ -1008,27 +1019,39 @@ function splicePiece(s, node, children) {
1008
1019
  const first = children.at(0);
1009
1020
  const last = children.at(-1);
1010
1021
  if (!first || !last) return replacedPiece(node, "");
1011
- return {
1012
- node,
1013
- text: s.slice(first.start, last.end),
1014
- startText: first.type === "JSXText" ? first : void 0,
1015
- endText: last.type === "JSXText" ? last : void 0
1016
- };
1022
+ return replacedPiece(node, s.slice(first.start, last.end));
1017
1023
  }
1024
+ /**
1025
+ * A piece that writes `text`, JSX children as source, in place of `node`.
1026
+ *
1027
+ * The texts it starts and ends with are read from `text` itself, not from
1028
+ * the children it came from. A fold inside them in the same round can have
1029
+ * turned a child that was an element into text, such as an inner `<Show>`.
1030
+ * JSX text holds no `<`, `>`, `{`, or `}`, so the first and last of those
1031
+ * mark where the text ends.
1032
+ */
1018
1033
  function replacedPiece(node, text) {
1034
+ const start = text.search(/[<{]/);
1035
+ const end = Math.max(text.lastIndexOf(">"), text.lastIndexOf("}"));
1036
+ const startText = start === -1 ? text : text.slice(0, start);
1037
+ const endText = text.slice(end + 1);
1019
1038
  return {
1020
1039
  node,
1021
1040
  text,
1022
- startText: void 0,
1023
- endText: void 0
1041
+ startText: startText === "" ? void 0 : startText,
1042
+ endText: endText === "" ? void 0 : endText
1024
1043
  };
1025
1044
  }
1045
+ /** Whether JSX drops this text: whitespace that contains a line break. */
1046
+ function isDroppedText(text) {
1047
+ return /^\s*$/.test(text) && /[\r\n]/.test(text);
1048
+ }
1026
1049
  /**
1027
1050
  * Whether two texts render differently as one text node than apart.
1028
1051
  * Two texts that JSX drops, like line breaks and indentation, still drop together.
1029
1052
  */
1030
1053
  function mergeChangesText(before, after) {
1031
- return before !== void 0 && after !== void 0 && !(isFilteredText(before) && isFilteredText(after));
1054
+ return before !== void 0 && after !== void 0 && !(isDroppedText(before) && isDroppedText(after));
1032
1055
  }
1033
1056
  /**
1034
1057
  * Puts `{}` between two pieces that meet as text, on whichever side is replaced.
@@ -1689,16 +1712,10 @@ var Folder = class {
1689
1712
  primary: true
1690
1713
  };
1691
1714
  case "JSXElement":
1692
- case "JSXFragment": return {
1693
- kind: "jsx",
1694
- text: getText(this.context, value)
1695
- };
1715
+ case "JSXFragment": return this.foldedJSX(value);
1696
1716
  default:
1697
1717
  if (value.expression.type === "JSXEmptyExpression") return EMPTY;
1698
- if (value.expression.type === "JSXElement" || value.expression.type === "JSXFragment") return {
1699
- kind: "jsx",
1700
- text: getText(this.context, value.expression)
1701
- };
1718
+ if (value.expression.type === "JSXElement" || value.expression.type === "JSXFragment") return this.foldedJSX(value.expression);
1702
1719
  return {
1703
1720
  kind: "expression",
1704
1721
  text: getText(this.context, value.expression),
@@ -1706,6 +1723,23 @@ var Folder = class {
1706
1723
  };
1707
1724
  }
1708
1725
  }
1726
+ /**
1727
+ * What a JSX value renders, read after the folds of this round. A fold
1728
+ * inside it can have replaced it with an expression already, such as an
1729
+ * inner `<Show>` that became its string `fallback`.
1730
+ */
1731
+ foldedJSX(node) {
1732
+ const text = getText(this.context, node);
1733
+ if (text.startsWith("<")) return {
1734
+ kind: "jsx",
1735
+ text
1736
+ };
1737
+ return {
1738
+ kind: "expression",
1739
+ text,
1740
+ primary: false
1741
+ };
1742
+ }
1709
1743
  foldShow(element) {
1710
1744
  const when = this.attributeTruthiness(element, "when");
1711
1745
  if (when === void 0) return;
@@ -1888,7 +1922,7 @@ var Folder = class {
1888
1922
  const inTemplate = this.joinsParentTemplate(element);
1889
1923
  const loop = new SizeEstimator(this.context.code).jsx(element, inTemplate) + (declaration ? compactLength(this.context.code.slice(declaration.start, declaration.end)) : 0);
1890
1924
  const code = `const __so_rows__ = ${text};`;
1891
- const statement = parse(this.context.filename, code).body.at(0);
1925
+ const statement = parse$1(this.context.filename, code).body.at(0);
1892
1926
  const init = statement?.type === "VariableDeclaration" ? statement.declarations.at(0)?.init : void 0;
1893
1927
  if (init?.type !== "JSXFragment") return false;
1894
1928
  const estimator = new SizeEstimator(code);
@@ -2722,7 +2756,7 @@ function copySize(filename, header, copy, inTemplate, options, called, measured)
2722
2756
  for (let round = 0; round < 4; round += 1) {
2723
2757
  let changed = false;
2724
2758
  for (const pass of calls ? [fold, calls.inline] : [fold]) {
2725
- const program = parse(filename, code);
2759
+ const program = parse$1(filename, code);
2726
2760
  const s = new MagicString(code);
2727
2761
  depth += 1;
2728
2762
  let passChanged;
@@ -2748,7 +2782,7 @@ function copySize(filename, header, copy, inTemplate, options, called, measured)
2748
2782
  if (!changed) break;
2749
2783
  }
2750
2784
  if (measured) measured.code = code;
2751
- const wrapper = parse(filename, code).body.at(-1);
2785
+ const wrapper = parse$1(filename, code).body.at(-1);
2752
2786
  if (wrapper?.type !== "FunctionDeclaration" || !wrapper.body) return Number.POSITIVE_INFINITY;
2753
2787
  const estimator = new SizeEstimator(code);
2754
2788
  let size = 0;
@@ -3795,7 +3829,10 @@ var Inliner = class {
3795
3829
  const statements = [...snapshots];
3796
3830
  const first = component.statements.at(0);
3797
3831
  const last = component.statements.at(-1);
3798
- if (first && last) statements.push(copy.slice(first.start, last.end));
3832
+ if (first && last) {
3833
+ const text = copy.slice(first.start, last.end);
3834
+ statements.push(text.endsWith(";") ? text : `${text};`);
3835
+ }
3799
3836
  return {
3800
3837
  element,
3801
3838
  host,
@@ -3803,19 +3840,22 @@ var Inliner = class {
3803
3840
  root: copy.slice(component.root.start, component.root.end)
3804
3841
  };
3805
3842
  }
3843
+ /** Queues statements for a host. Each `return` gets its own, since their scopes can differ. */
3844
+ addToHost(found, texts) {
3845
+ const key = found.host.kind === "return" ? found.host.statement : found.fn;
3846
+ const entry = this.hosts.get(key) ?? {
3847
+ host: found.host,
3848
+ texts: []
3849
+ };
3850
+ entry.texts.push(...texts);
3851
+ this.hosts.set(key, entry);
3852
+ }
3806
3853
  /**
3807
3854
  * Writes a prepared copy over its call site.
3808
3855
  */
3809
3856
  commit(site) {
3810
3857
  this.context.s.overwrite(site.element.start, site.element.end, site.root);
3811
- if (site.host) {
3812
- const entry = this.hosts.get(site.host.fn) ?? {
3813
- host: site.host.host,
3814
- texts: []
3815
- };
3816
- entry.texts.push(...site.statements);
3817
- this.hosts.set(site.host.fn, entry);
3818
- }
3858
+ if (site.host) this.addToHost(site.host, site.statements);
3819
3859
  }
3820
3860
  /**
3821
3861
  * The context reads in a component's copy at `element` that a closed
@@ -3895,12 +3935,7 @@ var Inliner = class {
3895
3935
  const host = this.findHost(element);
3896
3936
  if (!host) continue;
3897
3937
  const name = this.freshName(`${provider.context.name.charAt(0).toLowerCase()}${provider.context.name.slice(1)}Value`);
3898
- const entry = this.hosts.get(host.fn) ?? {
3899
- host: host.host,
3900
- texts: []
3901
- };
3902
- entry.texts.push(`const ${name} = ${getText(this.context, provider.value)};`);
3903
- this.hosts.set(host.fn, entry);
3938
+ this.addToHost(host, [`const ${name} = ${getText(this.context, provider.value)};`]);
3904
3939
  this.context.s.overwrite(provider.value.start, provider.value.end, name);
3905
3940
  this.transparent.set(element, {
3906
3941
  provider,
@@ -4051,17 +4086,7 @@ var Inliner = class {
4051
4086
  }
4052
4087
  }
4053
4088
  splicedPiece(container, value) {
4054
- if (value.kind === "children") {
4055
- const first = value.children.at(0);
4056
- const last = value.children.at(-1);
4057
- if (!first || !last) return replacedPiece(container, "");
4058
- return {
4059
- node: container,
4060
- text: this.context.s.slice(first.start, last.end),
4061
- startText: first.type === "JSXText" ? first : void 0,
4062
- endText: last.type === "JSXText" ? last : void 0
4063
- };
4064
- }
4089
+ if (value.kind === "children") return splicePiece(this.context.s, container, value.children);
4065
4090
  return replacedPiece(container, value.text);
4066
4091
  }
4067
4092
  /**
@@ -4264,16 +4289,82 @@ var Inliner = class {
4264
4289
  return target && target !== binding && target.scope.parent === void 0 && !target.mutated && isCapitalized(target.name) ? target : void 0;
4265
4290
  }
4266
4291
  /**
4292
+ * The parts of a compound component like Kobalte's
4293
+ * `const Dialog = Object.assign(DialogRoot, { Trigger: DialogTrigger })`,
4294
+ * or `undefined` when the binding is not one. `<Dialog>` is `<DialogRoot>`,
4295
+ * since `Object.assign` returns its first argument, and `<Dialog.Trigger>`
4296
+ * is `<DialogTrigger>` while nothing writes to a member of either.
4297
+ */
4298
+ compoundTarget(binding) {
4299
+ const { declaration } = binding;
4300
+ if (!isCapitalized(binding.name) || !isConstantDeclaration(binding, this.context.options) || declaration.type !== "VariableDeclarator" || declaration.id !== binding.identifier || !declaration.init) return;
4301
+ const init = unwrap(declaration.init);
4302
+ if (init.type !== "CallExpression" || init.optional || init.arguments.length !== 2 || !this.isObjectAssign(init.callee)) return;
4303
+ const [first, second] = init.arguments;
4304
+ if (first.type !== "Identifier" || second.type !== "ObjectExpression") return;
4305
+ const root = this.topLevelComponent(first);
4306
+ if (!root || root === binding || this.hasMemberWrite(binding) || this.hasMemberWrite(root)) return;
4307
+ const parts = /* @__PURE__ */ new Map();
4308
+ for (const property of second.properties) {
4309
+ if (property.type !== "Property" || property.kind !== "init" || property.computed || property.method || property.value.type !== "Identifier") return;
4310
+ const key = propertyKeyName(property.key);
4311
+ if (key === void 0) return;
4312
+ const part = this.topLevelComponent(property.value);
4313
+ if (part) parts.set(key, part);
4314
+ }
4315
+ return {
4316
+ root,
4317
+ parts
4318
+ };
4319
+ }
4320
+ /** Whether `callee` is the global `Object.assign`. */
4321
+ isObjectAssign(callee) {
4322
+ return callee.type === "MemberExpression" && !callee.computed && !callee.optional && callee.object.type === "Identifier" && callee.object.name === "Object" && !this.context.scopes.references.get(callee.object) && callee.property.type === "Identifier" && callee.property.name === "assign";
4323
+ }
4324
+ /** The top-level binding with a capitalized name that `reference` reads, when nothing reassigns it. */
4325
+ topLevelComponent(reference) {
4326
+ const target = this.context.scopes.references.get(reference);
4327
+ return target && target.scope.parent === void 0 && !target.mutated && isCapitalized(target.name) ? target : void 0;
4328
+ }
4329
+ /** Whether anything assigns to, updates, or deletes a member of the binding. */
4330
+ hasMemberWrite(binding) {
4331
+ for (const reference of binding.references) {
4332
+ const member = this.context.parents.get(reference);
4333
+ if (member?.type !== "MemberExpression" || member.object !== reference) continue;
4334
+ const use = this.context.parents.get(member);
4335
+ if (use?.type === "AssignmentExpression" && use.left === member || use?.type === "UpdateExpression" || use?.type === "UnaryExpression" && use.operator === "delete") return true;
4336
+ }
4337
+ return false;
4338
+ }
4339
+ /** Whether the code reads a member of the binding, like `DialogRoot.Trigger`. */
4340
+ hasMemberRead(binding) {
4341
+ for (const reference of binding.references) {
4342
+ const member = this.context.parents.get(reference);
4343
+ if ((member?.type === "MemberExpression" || member?.type === "JSXMemberExpression") && member.object === reference) return true;
4344
+ }
4345
+ return false;
4346
+ }
4347
+ /**
4267
4348
  * The statement of an alias nothing uses that `reference` is the value
4268
4349
  * of, like `const Separator = SeparatorRoot` once its tags are renamed.
4269
- * It does not keep the component, and goes away with it.
4350
+ * It does not keep the component, and goes away with it. A compound
4351
+ * component counts too, when its tags are renamed and nothing reads the
4352
+ * members `Object.assign` gave its root.
4270
4353
  */
4271
4354
  unusedAlias(reference) {
4272
- const declarator = this.context.parents.get(reference);
4355
+ let declarator = this.context.parents.get(reference);
4356
+ if (declarator?.type === "Property") declarator = this.context.parents.get(declarator);
4357
+ if (declarator?.type === "ObjectExpression" || declarator?.type === "CallExpression") {
4358
+ const call = declarator.type === "CallExpression" ? declarator : this.context.parents.get(declarator);
4359
+ declarator = call ? this.context.parents.get(call) : void 0;
4360
+ }
4273
4361
  if (declarator?.type !== "VariableDeclarator" || declarator.id.type !== "Identifier") return;
4274
4362
  const alias = this.context.scopes.root.bindings.get(declarator.id.name);
4363
+ if (alias?.declaration !== declarator || alias.references.length > 0) return;
4364
+ const compound = this.compoundTarget(alias);
4365
+ if (this.aliasTarget(alias) === void 0 && (!compound || this.hasMemberRead(compound.root))) return;
4275
4366
  const statement = this.context.parents.get(declarator);
4276
- 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;
4367
+ return statement?.type === "VariableDeclaration" && statement.declarations.length === 1 && this.context.parents.get(statement)?.type === "Program" ? statement : void 0;
4277
4368
  }
4278
4369
  /**
4279
4370
  * Renames each tag of an alias to the component it names, where that name
@@ -4283,13 +4374,23 @@ var Inliner = class {
4283
4374
  renameAliasTags() {
4284
4375
  let renamed = false;
4285
4376
  for (const binding of this.context.scopes.root.bindings.values()) {
4286
- const target = this.aliasTarget(binding);
4377
+ const compound = this.compoundTarget(binding);
4378
+ const target = this.aliasTarget(binding) ?? compound?.root;
4287
4379
  if (!target) continue;
4288
4380
  for (const reference of binding.references) {
4289
4381
  const parent = this.context.parents.get(reference);
4290
- if (parent?.type !== "JSXOpeningElement" && parent?.type !== "JSXClosingElement" || parent.name !== reference) continue;
4291
- if (lookup(scopeAt(this.context.scopes, this.context.parents, reference), target.name) !== target) continue;
4292
- this.context.s.overwrite(reference.start, reference.end, target.name);
4382
+ let tag = reference;
4383
+ let renamedTo = target;
4384
+ if (parent?.type === "JSXMemberExpression" && parent.object === reference) {
4385
+ const part = compound?.parts.get(parent.property.name);
4386
+ if (!part) continue;
4387
+ tag = parent;
4388
+ renamedTo = part;
4389
+ }
4390
+ const element = this.context.parents.get(tag);
4391
+ if (element?.type !== "JSXOpeningElement" && element?.type !== "JSXClosingElement" || element.name !== tag) continue;
4392
+ if (lookup(scopeAt(this.context.scopes, this.context.parents, reference), renamedTo.name) !== renamedTo) continue;
4393
+ this.context.s.overwrite(tag.start, tag.end, renamedTo.name);
4293
4394
  renamed = true;
4294
4395
  }
4295
4396
  }
@@ -4506,6 +4607,11 @@ function hasChild(children, child) {
4506
4607
  for (const item of children) if (item === child) return true;
4507
4608
  return false;
4508
4609
  }
4610
+ /** The name a non-computed object key spells, like `Trigger` or `'Trigger'`. */
4611
+ function propertyKeyName(key) {
4612
+ if (key.type === "Identifier") return key.name;
4613
+ return key.type === "Literal" && typeof key.value === "string" ? key.value : void 0;
4614
+ }
4509
4615
  //#endregion
4510
4616
  //#region src/memo.ts
4511
4617
  /**
@@ -4518,29 +4624,81 @@ const TRACKED_PROPS = /* @__PURE__ */ new Map([
4518
4624
  ["Repeat", "count"]
4519
4625
  ]);
4520
4626
  /**
4627
+ * Global constructors whose instances are never thenable or async iterable.
4628
+ */
4629
+ const SYNC_CONSTRUCTORS = /* @__PURE__ */ new Set([
4630
+ "Array",
4631
+ "Date",
4632
+ "Error",
4633
+ "Map",
4634
+ "RegExp",
4635
+ "Set",
4636
+ "URL",
4637
+ "URLSearchParams",
4638
+ "WeakMap",
4639
+ "WeakSet"
4640
+ ]);
4641
+ /**
4642
+ * Whether an object literal can have a `then` method or `Symbol.asyncIterator`,
4643
+ * its own or from a `__proto__` it sets.
4644
+ */
4645
+ function mayBeThenable(node) {
4646
+ for (const property of node.properties) {
4647
+ if (property.type === "SpreadElement" || property.computed) return true;
4648
+ const { key } = property;
4649
+ let name;
4650
+ if (key.type === "Identifier") name = key.name;
4651
+ else if ("value" in key) name = key.value;
4652
+ if (name === "then" || name === "__proto__") return true;
4653
+ }
4654
+ return false;
4655
+ }
4656
+ /**
4521
4657
  * Whether evaluating `node` always creates a new value, which reference
4522
- * equality never finds equal to the last one.
4658
+ * equality never finds equal to the last one. The value is never a promise
4659
+ * or an async iterable, which a memo waits for and an inlined read does not.
4660
+ * `isGlobal` tells whether a name is one the module does not declare.
4523
4661
  */
4524
- function isFresh(node) {
4662
+ function isFresh(node, isGlobal) {
4525
4663
  switch (node.type) {
4526
- case "ObjectExpression":
4527
4664
  case "ArrayExpression":
4528
4665
  case "ArrowFunctionExpression":
4529
4666
  case "FunctionExpression":
4530
- case "ClassExpression":
4531
- case "NewExpression":
4532
4667
  case "JSXElement":
4533
4668
  case "JSXFragment": return true;
4534
- case "ParenthesizedExpression": return isFresh(node.expression);
4535
- case "ConditionalExpression": return isFresh(node.consequent) && isFresh(node.alternate);
4669
+ case "ObjectExpression": return !mayBeThenable(node);
4670
+ case "NewExpression": return node.callee.type === "Identifier" && SYNC_CONSTRUCTORS.has(node.callee.name) && isGlobal(node.callee);
4671
+ case "ParenthesizedExpression": return isFresh(node.expression, isGlobal);
4672
+ case "ConditionalExpression": return isFresh(node.consequent, isGlobal) && isFresh(node.alternate, isGlobal);
4536
4673
  case "SequenceExpression": {
4537
4674
  const last = node.expressions.at(-1);
4538
- return last !== void 0 && isFresh(last);
4675
+ return last !== void 0 && isFresh(last, isGlobal);
4539
4676
  }
4540
4677
  default: return false;
4541
4678
  }
4542
4679
  }
4543
4680
  /**
4681
+ * Whether `node` evaluates to a value that is never a promise or an async
4682
+ * iterable. A memo waits for one of those, and an inlined read does not.
4683
+ */
4684
+ function isSync(node, isGlobal) {
4685
+ switch (node.type) {
4686
+ case "Literal":
4687
+ case "TemplateLiteral":
4688
+ case "UnaryExpression":
4689
+ case "UpdateExpression":
4690
+ case "BinaryExpression": return true;
4691
+ case "ParenthesizedExpression": return isSync(node.expression, isGlobal);
4692
+ case "ConditionalExpression": return isSync(node.consequent, isGlobal) && isSync(node.alternate, isGlobal);
4693
+ case "LogicalExpression": return isSync(node.left, isGlobal) && isSync(node.right, isGlobal);
4694
+ case "SequenceExpression": {
4695
+ const last = node.expressions.at(-1);
4696
+ return last !== void 0 && isSync(last, isGlobal);
4697
+ }
4698
+ default: return isFresh(node, isGlobal);
4699
+ }
4700
+ }
4701
+ /**
4544
4702
  * The text of an expression that always gives the same primitive: a literal
4545
4703
  * other than a regular expression, a template literal without expressions,
4546
4704
  * or a negated number.
@@ -4770,7 +4928,12 @@ var MemoInliner = class {
4770
4928
  } else {
4771
4929
  const constant = constantText(this.context, expression);
4772
4930
  if (constant !== void 0) return this.inlineConstant(declarator, binding, constant);
4773
- if (!alwaysNotifies && !isFresh(expression)) return;
4931
+ const isGlobal = (node) => this.context.scopes.references.get(node) === void 0;
4932
+ if (!alwaysNotifies && !isFresh(expression, isGlobal)) return;
4933
+ if (alwaysNotifies && !isSync(expression, isGlobal)) {
4934
+ this.reason = "memo-async";
4935
+ return;
4936
+ }
4774
4937
  }
4775
4938
  if (binding.references.length !== 1) {
4776
4939
  this.reason = "memo-reads";
@@ -4900,6 +5063,233 @@ function inlineMemos(context) {
4900
5063
  return inliner.changed;
4901
5064
  }
4902
5065
  //#endregion
5066
+ //#region src/nesting.ts
5067
+ const VOID_ELEMENTS = /* @__PURE__ */ new Set([
5068
+ "area",
5069
+ "base",
5070
+ "br",
5071
+ "col",
5072
+ "embed",
5073
+ "hr",
5074
+ "img",
5075
+ "input",
5076
+ "keygen",
5077
+ "link",
5078
+ "meta",
5079
+ "param",
5080
+ "source",
5081
+ "track",
5082
+ "wbr"
5083
+ ]);
5084
+ const SVG_ELEMENTS = /* @__PURE__ */ new Set([
5085
+ "altGlyph",
5086
+ "altGlyphDef",
5087
+ "altGlyphItem",
5088
+ "animate",
5089
+ "animateColor",
5090
+ "animateMotion",
5091
+ "animateTransform",
5092
+ "circle",
5093
+ "clipPath",
5094
+ "cursor",
5095
+ "defs",
5096
+ "desc",
5097
+ "ellipse",
5098
+ "feBlend",
5099
+ "feColorMatrix",
5100
+ "feComponentTransfer",
5101
+ "feComposite",
5102
+ "feConvolveMatrix",
5103
+ "feDiffuseLighting",
5104
+ "feDisplacementMap",
5105
+ "feDistantLight",
5106
+ "feDropShadow",
5107
+ "feFlood",
5108
+ "feFuncA",
5109
+ "feFuncB",
5110
+ "feFuncG",
5111
+ "feFuncR",
5112
+ "feGaussianBlur",
5113
+ "feImage",
5114
+ "feMerge",
5115
+ "feMergeNode",
5116
+ "feMorphology",
5117
+ "feOffset",
5118
+ "fePointLight",
5119
+ "feSpecularLighting",
5120
+ "feSpotLight",
5121
+ "feTile",
5122
+ "feTurbulence",
5123
+ "filter",
5124
+ "font",
5125
+ "foreignObject",
5126
+ "g",
5127
+ "glyph",
5128
+ "glyphRef",
5129
+ "hkern",
5130
+ "image",
5131
+ "line",
5132
+ "linearGradient",
5133
+ "marker",
5134
+ "mask",
5135
+ "metadata",
5136
+ "mpath",
5137
+ "path",
5138
+ "pattern",
5139
+ "polygon",
5140
+ "polyline",
5141
+ "radialGradient",
5142
+ "rect",
5143
+ "set",
5144
+ "stop",
5145
+ "switch",
5146
+ "symbol",
5147
+ "text",
5148
+ "textPath",
5149
+ "tref",
5150
+ "tspan",
5151
+ "use",
5152
+ "view",
5153
+ "vkern"
5154
+ ]);
5155
+ function findElement(parent, name) {
5156
+ for (const child of parent.childNodes) if (child.nodeName === name && "childNodes" in child) return child;
5157
+ throw new Error(`[solid-optimizer] no <${name}> in an empty document`);
5158
+ }
5159
+ let body;
5160
+ /** What a browser makes of `html` set as the body's `innerHTML`. */
5161
+ function parseAsBody(html) {
5162
+ body ??= findElement(findElement(parse("<!DOCTYPE html><html><body></body></html>"), "html"), "body");
5163
+ return serialize(parseFragment(body, html, {}));
5164
+ }
5165
+ /** The tag of an intrinsic element, or `undefined` for a component or a namespaced tag. */
5166
+ function readIntrinsicTag(element) {
5167
+ const name = element.openingElement.name;
5168
+ return name.type === "JSXIdentifier" && isIntrinsicTag(name.name) ? name.name : void 0;
5169
+ }
5170
+ /**
5171
+ * The template rooted at `element`. Elements inside fragments join it.
5172
+ * Elements in expression containers or under a component start their own.
5173
+ */
5174
+ function collectTemplate(element, tag) {
5175
+ const node = {
5176
+ element,
5177
+ tag,
5178
+ children: []
5179
+ };
5180
+ addTemplateChildren(node, element.children);
5181
+ return node;
5182
+ }
5183
+ function addTemplateChildren(node, children) {
5184
+ for (const child of children) if (child.type === "JSXFragment") addTemplateChildren(node, child.children);
5185
+ else if (child.type === "JSXElement") {
5186
+ const tag = readIntrinsicTag(child);
5187
+ if (tag !== void 0) node.children.push(collectTemplate(child, tag));
5188
+ }
5189
+ }
5190
+ /**
5191
+ * The tags of a template, without text or attributes. Elements not in
5192
+ * `included` are left out with what they hold.
5193
+ */
5194
+ function writeTags(node, included) {
5195
+ if (VOID_ELEMENTS.has(node.tag)) return `<${node.tag}>`;
5196
+ let inner = "";
5197
+ for (const child of node.children) if (included.has(child)) inner += writeTags(child, included);
5198
+ return `<${node.tag}>${inner}</${node.tag}>`;
5199
+ }
5200
+ /**
5201
+ * Table parts parse only inside a table, and SVG parts only inside an
5202
+ * `<svg>`, so a template rooted at one is checked inside one, as Solid
5203
+ * creates it.
5204
+ */
5205
+ function placeInContext(tag, html) {
5206
+ if (SVG_ELEMENTS.has(tag)) return `<svg>${html}</svg>`;
5207
+ switch (tag) {
5208
+ case "td":
5209
+ case "th": return `<table><tbody><tr>${html}</tr></tbody></table>`;
5210
+ case "tr": return `<table><tbody>${html}</tbody></table>`;
5211
+ case "col": return `<table><colgroup>${html}</colgroup></table>`;
5212
+ case "thead":
5213
+ case "tbody":
5214
+ case "tfoot":
5215
+ case "colgroup":
5216
+ case "caption": return `<table>${html}</table>`;
5217
+ default: return html;
5218
+ }
5219
+ }
5220
+ /** Whether a `<template>` in the template holds an element, which Solid rejects. */
5221
+ function hasTemplateContent(node, included) {
5222
+ for (const child of node.children) if (included.has(child) && (node.tag === "template" || hasTemplateContent(child, included))) return true;
5223
+ return false;
5224
+ }
5225
+ function isValidTemplate(root, included) {
5226
+ if (hasTemplateContent(root, included)) return false;
5227
+ const html = placeInContext(root.tag, writeTags(root, included));
5228
+ return parseAsBody(html).toLowerCase() === html.toLowerCase();
5229
+ }
5230
+ function collectAll(node, into) {
5231
+ into.add(node);
5232
+ for (const child of node.children) collectAll(child, into);
5233
+ return into;
5234
+ }
5235
+ /**
5236
+ * Wraps the elements that make `root`'s template parse differently, and
5237
+ * returns the wrapped elements, each the root of a template of its own.
5238
+ */
5239
+ function wrapInvalidElements(context, root) {
5240
+ if (isValidTemplate(root, collectAll(root, /* @__PURE__ */ new Set()))) return [];
5241
+ const included = /* @__PURE__ */ new Set([root]);
5242
+ if (!isValidTemplate(root, included)) return [];
5243
+ const wrapped = [];
5244
+ const pending = [];
5245
+ pushChildren(pending, root);
5246
+ for (let node = pending.pop(); node; node = pending.pop()) {
5247
+ included.add(node);
5248
+ if (!isValidTemplate(root, included)) {
5249
+ included.delete(node);
5250
+ context.s.prependRight(node.element.start, "{");
5251
+ context.s.appendLeft(node.element.end, "}");
5252
+ wrapped.push(node);
5253
+ continue;
5254
+ }
5255
+ pushChildren(pending, node);
5256
+ }
5257
+ return wrapped;
5258
+ }
5259
+ /** Pushes the children of `node` so that they pop in source order. */
5260
+ function pushChildren(pending, node) {
5261
+ for (let index = node.children.length - 1; index >= 0; index -= 1) pending.push(node.children[index]);
5262
+ }
5263
+ function repairNesting(context) {
5264
+ const roots = [];
5265
+ const visit = (node, inTemplate) => {
5266
+ if (node.type === "JSXElement") {
5267
+ const tag = readIntrinsicTag(node);
5268
+ if (tag !== void 0 && !inTemplate) roots.push(collectTemplate(node, tag));
5269
+ for (const child of node.children) visit(child, tag !== void 0);
5270
+ for (const attribute of node.openingElement.attributes) visit(attribute, false);
5271
+ return;
5272
+ }
5273
+ if (node.type === "JSXFragment") {
5274
+ for (const child of node.children) visit(child, inTemplate);
5275
+ return;
5276
+ }
5277
+ forEachChild(node, (child) => {
5278
+ visit(child, false);
5279
+ });
5280
+ };
5281
+ visit(context.program, false);
5282
+ let changed = false;
5283
+ for (let root = roots.pop(); root; root = roots.pop()) {
5284
+ const wrapped = wrapInvalidElements(context, root);
5285
+ if (wrapped.length > 0) {
5286
+ changed = true;
5287
+ roots.push(...wrapped);
5288
+ }
5289
+ }
5290
+ return changed;
5291
+ }
5292
+ //#endregion
4903
5293
  //#region src/conditional.ts
4904
5294
  /**
4905
5295
  * Rewrites each `<Show>` and `<Switch>` that can be lowered. One inside
@@ -5195,6 +5585,58 @@ function expressionText(context, attribute) {
5195
5585
  }
5196
5586
  }
5197
5587
  //#endregion
5588
+ //#region src/terminate.ts
5589
+ const TERMINATED = /* @__PURE__ */ new Set([
5590
+ "BreakStatement",
5591
+ "ContinueStatement",
5592
+ "DebuggerStatement",
5593
+ "DoWhileStatement",
5594
+ "ExportAllDeclaration",
5595
+ "ExpressionStatement",
5596
+ "ImportDeclaration",
5597
+ "ReturnStatement",
5598
+ "ThrowStatement",
5599
+ "TSTypeAliasDeclaration",
5600
+ "VariableDeclaration"
5601
+ ]);
5602
+ const LOOP_HEADS = /* @__PURE__ */ new Set([
5603
+ "ForStatement",
5604
+ "ForInStatement",
5605
+ "ForOfStatement"
5606
+ ]);
5607
+ function isTerminated(node, context) {
5608
+ if (node.type === "VariableDeclaration") {
5609
+ const parent = context.parents.get(node);
5610
+ return !(parent && LOOP_HEADS.has(parent.type) && Reflect.get(parent, "body") !== node);
5611
+ }
5612
+ if (node.type === "ExportNamedDeclaration") return !node.declaration;
5613
+ if (node.type === "ExportDefaultDeclaration") {
5614
+ const { type } = node.declaration;
5615
+ return type !== "FunctionDeclaration" && type !== "ClassDeclaration";
5616
+ }
5617
+ return TERMINATED.has(node.type);
5618
+ }
5619
+ const TRIVIA = /(?:\s|\/\/[^\n\r\u2028\u2029]*|\/\*[\s\S]*?\*\/)*/y;
5620
+ /** Whether code other than the closing brace of a block follows `position`. */
5621
+ function hasCodeAfter(code, position) {
5622
+ TRIVIA.lastIndex = position;
5623
+ TRIVIA.exec(code);
5624
+ return TRIVIA.lastIndex < code.length && code[TRIVIA.lastIndex] !== "}";
5625
+ }
5626
+ function terminateStatements(context) {
5627
+ const { code, s } = context;
5628
+ let changed = false;
5629
+ const visit = (node) => {
5630
+ if (isTerminated(node, context) && code[node.end - 1] !== ";" && hasCodeAfter(code, node.end)) {
5631
+ s.appendLeft(node.end, ";");
5632
+ changed = true;
5633
+ }
5634
+ forEachChild(node, visit);
5635
+ };
5636
+ visit(context.program);
5637
+ return changed;
5638
+ }
5639
+ //#endregion
5198
5640
  //#region src/compile.ts
5199
5641
  const DEFAULT_BUILT_INS = [
5200
5642
  "For",
@@ -5226,7 +5668,7 @@ function resolveOptions(options) {
5226
5668
  };
5227
5669
  }
5228
5670
  function parseCode(code, filename) {
5229
- const program = parse(filename, code);
5671
+ const program = parse$1(filename, code);
5230
5672
  return {
5231
5673
  code,
5232
5674
  program,
@@ -5286,6 +5728,12 @@ function compile(code, options = {}) {
5286
5728
  if (parsed?.code !== current) parsed = parseCode(current, filename);
5287
5729
  return parsed;
5288
5730
  };
5731
+ const terminated = runPass(parsedCurrent(), filename, resolved, sourceMap, terminateStatements, void 0);
5732
+ if (terminated) {
5733
+ current = terminated.code;
5734
+ if (terminated.map !== void 0) maps.push(terminated.map);
5735
+ }
5736
+ const start = current;
5289
5737
  const maxPasses = options.maxPasses ?? 10;
5290
5738
  let skipped;
5291
5739
  for (let round = 0; round < maxPasses; round += 1) {
@@ -5307,7 +5755,19 @@ function compile(code, options = {}) {
5307
5755
  current = result.code;
5308
5756
  if (result.map !== void 0) maps.push(result.map);
5309
5757
  }
5758
+ if (current !== start) {
5759
+ const result = runPass(parsedCurrent(), filename, resolved, sourceMap, repairNesting, void 0);
5760
+ if (result) {
5761
+ current = result.code;
5762
+ if (result.map !== void 0) maps.push(result.map);
5763
+ }
5764
+ }
5310
5765
  const report = skipped ? { skipped } : {};
5766
+ if (current === start) return {
5767
+ code,
5768
+ map: null,
5769
+ ...report
5770
+ };
5311
5771
  if (maps.length === 0) return {
5312
5772
  code: current,
5313
5773
  map: null,
@@ -5326,7 +5786,7 @@ function compile(code, options = {}) {
5326
5786
  * Only `filename`, `importedConstants`, and `globalConstants` of the options are used.
5327
5787
  */
5328
5788
  function readModuleConstants(code, options = {}) {
5329
- const program = parse(options.filename ?? "input.jsx", code);
5789
+ const program = parse$1(options.filename ?? "input.jsx", code);
5330
5790
  const scopes = analyzeScopes(program);
5331
5791
  return {
5332
5792
  imports: namedImportSources(program, scopes),
@@ -5334,6 +5794,6 @@ function readModuleConstants(code, options = {}) {
5334
5794
  };
5335
5795
  }
5336
5796
  //#endregion
5337
- 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 };
5797
+ export { analyzeScopes as a, collectParents as c, parse$1 as d, unwrap as f, runtimeImportSources as i, forEachChild as l, readModuleConstants as n, lookup as o, CONTEXT_SAFE_PRIMITIVES as r, scopeAt as s, compile as t, isIntrinsicTag as u };
5338
5798
 
5339
- //# sourceMappingURL=compile-DnfP-Quf.mjs.map
5799
+ //# sourceMappingURL=compile-O1Z60VsW.mjs.map