solid-optimizer 1.0.0-next.9 → 1.1.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.
@@ -1,6 +1,6 @@
1
1
  import remapping from "@jridgewell/remapping";
2
- import MagicString from "magic-string";
3
2
  import { parseSync, rawTransferSupported, visitorKeys } from "oxc-parser";
3
+ import MagicString from "magic-string";
4
4
  import { parse, parseFragment, serialize } from "parse5";
5
5
  //#region src/ast.ts
6
6
  /**
@@ -1055,6 +1055,238 @@ function constantExports(program, options, scopes = analyzeScopes(program)) {
1055
1055
  return result;
1056
1056
  }
1057
1057
  //#endregion
1058
+ //#region src/text.ts
1059
+ const WRITTEN = 2147483648;
1060
+ const LOOSE = 4294967295;
1061
+ const LOOSE_UNITS = "￿￿";
1062
+ function encodeOrigin(value) {
1063
+ return String.fromCharCode(value >>> 16, value & 65535);
1064
+ }
1065
+ function decodeOrigin(origins, index) {
1066
+ return (origins.charCodeAt(index * 2) << 16 | origins.charCodeAt(index * 2 + 1)) >>> 0;
1067
+ }
1068
+ function repeatOrigin(value, length) {
1069
+ return encodeOrigin(value).repeat(length);
1070
+ }
1071
+ /** The line of the original that holds an offset. */
1072
+ function findLine(lineStarts, offset) {
1073
+ let low = 0;
1074
+ let high = lineStarts.length - 1;
1075
+ while (low < high) {
1076
+ const middle = low + high + 1 >> 1;
1077
+ if ((lineStarts[middle] ?? 0) <= offset) low = middle;
1078
+ else high = middle - 1;
1079
+ }
1080
+ return low;
1081
+ }
1082
+ let identityCode;
1083
+ let identity = "";
1084
+ /** The origins of unedited code: each character its own offset. */
1085
+ function createIdentity(code) {
1086
+ if (identityCode === code) return identity;
1087
+ const chunks = [];
1088
+ const units = new Uint16Array(Math.min(code.length, 4096) * 2);
1089
+ for (let start = 0; start < code.length; start += 4096) {
1090
+ const end = Math.min(code.length, start + 4096);
1091
+ for (let index = start; index < end; index += 1) {
1092
+ units[(index - start) * 2] = index >>> 16;
1093
+ units[(index - start) * 2 + 1] = index & 65535;
1094
+ }
1095
+ chunks.push(String.fromCharCode(...units.subarray(0, (end - start) * 2)));
1096
+ }
1097
+ identityCode = code;
1098
+ identity = chunks.join("");
1099
+ return identity;
1100
+ }
1101
+ /**
1102
+ * Code with the origin of each of its characters, so that the source map
1103
+ * can point a copied character back at the one it copies.
1104
+ *
1105
+ * `origins` is `undefined` when the compile writes no source map.
1106
+ */
1107
+ var Text = class {
1108
+ constructor(code, origins) {
1109
+ this.code = code;
1110
+ this.origins = origins;
1111
+ }
1112
+ toString() {
1113
+ return this.code;
1114
+ }
1115
+ };
1116
+ /** The code of a content. */
1117
+ function getCode(content) {
1118
+ return typeof content === "string" ? content : content.code;
1119
+ }
1120
+ /**
1121
+ * Joins contents into one text. The characters of a string take the offset
1122
+ * of the edit that writes the text.
1123
+ */
1124
+ function join(parts, separator = "") {
1125
+ let code = "";
1126
+ let origins = "";
1127
+ for (let index = 0; index < parts.length; index += 1) {
1128
+ const part = parts[index] ?? "";
1129
+ if (index > 0 && separator) {
1130
+ code += separator;
1131
+ if (origins !== void 0) origins += repeatOrigin(LOOSE, separator.length);
1132
+ }
1133
+ if (typeof part === "string") {
1134
+ code += part;
1135
+ if (origins !== void 0) origins += repeatOrigin(LOOSE, part.length);
1136
+ } else {
1137
+ code += part.code;
1138
+ origins = part.origins === void 0 ? void 0 : origins + part.origins;
1139
+ }
1140
+ }
1141
+ return new Text(code, origins);
1142
+ }
1143
+ /** Builds a text from a template, keeping the origins of the texts it holds. */
1144
+ function joinText(strings, ...values) {
1145
+ const parts = [];
1146
+ for (let index = 0; index < strings.length; index += 1) {
1147
+ parts.push(strings[index] ?? "");
1148
+ if (index < values.length) parts.push(values[index] ?? "");
1149
+ }
1150
+ return join(parts);
1151
+ }
1152
+ /** The origins of a content written at an offset. */
1153
+ function resolveOrigins(content, at) {
1154
+ if (typeof content === "string") return repeatOrigin(WRITTEN | at, content.length);
1155
+ const { origins } = content;
1156
+ if (origins === void 0) return repeatOrigin(WRITTEN | at, content.code.length);
1157
+ let result = "";
1158
+ let from = 0;
1159
+ const written = encodeOrigin(WRITTEN | at);
1160
+ let found = origins.indexOf(LOOSE_UNITS);
1161
+ while (found !== -1) {
1162
+ if (found % 2 === 1) {
1163
+ found = origins.indexOf(LOOSE_UNITS, found + 1);
1164
+ continue;
1165
+ }
1166
+ result += origins.slice(from, found) + written;
1167
+ from = found + 2;
1168
+ found = origins.indexOf(LOOSE_UNITS, from);
1169
+ }
1170
+ return from === 0 ? origins : result + origins.slice(from);
1171
+ }
1172
+ /**
1173
+ * Edits code like `MagicString`, and keeps the origin of each character of
1174
+ * the result.
1175
+ *
1176
+ * A second `MagicString` holds the origins, two code units per character,
1177
+ * and takes every edit the first one takes.
1178
+ */
1179
+ var Editor = class Editor {
1180
+ constructor(original, tracksOrigins) {
1181
+ this.original = original;
1182
+ this.tracksOrigins = tracksOrigins;
1183
+ this.s = new MagicString(original);
1184
+ }
1185
+ /** A new editor on the same original code, which keeps origins when this one does. */
1186
+ fresh() {
1187
+ return new Editor(this.original, this.tracksOrigins);
1188
+ }
1189
+ /** The origins to edit, or `undefined` when this editor keeps none. */
1190
+ editOrigins() {
1191
+ if (this.tracksOrigins && !this.o) this.o = new MagicString(createIdentity(this.original));
1192
+ return this.o;
1193
+ }
1194
+ /** Code that a pass writes in place of what is at `at`, mapped there. */
1195
+ written(code, at) {
1196
+ return new Text(code, this.tracksOrigins ? repeatOrigin(WRITTEN | at, code.length) : void 0);
1197
+ }
1198
+ overwrite(start, end, content) {
1199
+ this.s.overwrite(start, end, getCode(content));
1200
+ this.editOrigins()?.overwrite(start * 2, end * 2, resolveOrigins(content, start));
1201
+ return this;
1202
+ }
1203
+ remove(start, end) {
1204
+ this.s.remove(start, end);
1205
+ this.editOrigins()?.remove(start * 2, end * 2);
1206
+ return this;
1207
+ }
1208
+ prependLeft(index, content) {
1209
+ this.s.prependLeft(index, getCode(content));
1210
+ this.editOrigins()?.prependLeft(index * 2, resolveOrigins(content, index));
1211
+ return this;
1212
+ }
1213
+ prependRight(index, content) {
1214
+ this.s.prependRight(index, getCode(content));
1215
+ this.editOrigins()?.prependRight(index * 2, resolveOrigins(content, index));
1216
+ return this;
1217
+ }
1218
+ appendLeft(index, content) {
1219
+ this.s.appendLeft(index, getCode(content));
1220
+ this.editOrigins()?.appendLeft(index * 2, resolveOrigins(content, index));
1221
+ return this;
1222
+ }
1223
+ /** The edited code of characters `start` to `end` of the original, with origins. */
1224
+ slice(start, end) {
1225
+ let origins;
1226
+ if (this.o) origins = this.o.slice(start * 2, end * 2);
1227
+ else if (this.tracksOrigins) origins = createIdentity(this.original).slice(start * 2, end * 2);
1228
+ return new Text(this.s.slice(start, end), origins);
1229
+ }
1230
+ toString() {
1231
+ return this.s.toString();
1232
+ }
1233
+ /**
1234
+ * A map from the edited code to the original. A copied character maps to
1235
+ * the one it copies, and a written run maps to where it was written.
1236
+ */
1237
+ generateMap(source) {
1238
+ const code = this.s.toString();
1239
+ const origins = this.o?.toString() ?? createIdentity(this.original);
1240
+ const lineStarts = [0];
1241
+ for (let index = 0; index < this.original.length; index += 1) if (this.original.charCodeAt(index) === 10) lineStarts.push(index + 1);
1242
+ const mappings = [[]];
1243
+ let line = mappings[0] ?? [];
1244
+ let column = 0;
1245
+ let previous = LOOSE;
1246
+ let sourceLine = 0;
1247
+ let sourceColumn = 0;
1248
+ for (let index = 0; index < code.length; index += 1) {
1249
+ const origin = decodeOrigin(origins, index);
1250
+ if (origin < WRITTEN) {
1251
+ if (origin === previous + 1 && this.original.charCodeAt(previous) !== 10) sourceColumn += 1;
1252
+ else {
1253
+ sourceLine = findLine(lineStarts, origin);
1254
+ sourceColumn = origin - (lineStarts[sourceLine] ?? 0);
1255
+ }
1256
+ line.push([
1257
+ column,
1258
+ 0,
1259
+ sourceLine,
1260
+ sourceColumn
1261
+ ]);
1262
+ } else if (origin !== previous || column === 0) {
1263
+ const offset = origin - WRITTEN;
1264
+ const written = findLine(lineStarts, offset);
1265
+ line.push([
1266
+ column,
1267
+ 0,
1268
+ written,
1269
+ offset - (lineStarts[written] ?? 0)
1270
+ ]);
1271
+ }
1272
+ previous = origin;
1273
+ if (code.charCodeAt(index) === 10) {
1274
+ line = [];
1275
+ mappings.push(line);
1276
+ column = 0;
1277
+ } else column += 1;
1278
+ }
1279
+ return {
1280
+ version: 3,
1281
+ file: null,
1282
+ names: [],
1283
+ sources: [source],
1284
+ sourcesContent: [this.original],
1285
+ mappings
1286
+ };
1287
+ }
1288
+ };
1289
+ //#endregion
1058
1290
  //#region src/jsx.ts
1059
1291
  function keptPiece(node) {
1060
1292
  const text = node.type === "JSXText" ? node.value : void 0;
@@ -1084,10 +1316,11 @@ function splicePiece(s, node, children) {
1084
1316
  * mark where the text ends.
1085
1317
  */
1086
1318
  function replacedPiece(node, text) {
1087
- const start = text.search(/[<{]/);
1088
- const end = Math.max(text.lastIndexOf(">"), text.lastIndexOf("}"));
1089
- const startText = start === -1 ? text : text.slice(0, start);
1090
- const endText = text.slice(end + 1);
1319
+ const code = getCode(text);
1320
+ const start = code.search(/[<{]/);
1321
+ const end = Math.max(code.lastIndexOf(">"), code.lastIndexOf("}"));
1322
+ const startText = start === -1 ? code : code.slice(0, start);
1323
+ const endText = code.slice(end + 1);
1091
1324
  return {
1092
1325
  node,
1093
1326
  text,
@@ -1111,12 +1344,12 @@ function mergeChangesText(before, after) {
1111
1344
  */
1112
1345
  function separate(previous, next, emptiesBetween) {
1113
1346
  if (next.text !== void 0) {
1114
- next.text = `{}${next.text}`;
1347
+ next.text = joinText`{}${next.text}`;
1115
1348
  next.startText = void 0;
1116
1349
  return;
1117
1350
  }
1118
1351
  if (previous.text !== void 0) {
1119
- previous.text = `${previous.text}{}`;
1352
+ previous.text = joinText`${previous.text}{}`;
1120
1353
  previous.endText = void 0;
1121
1354
  return;
1122
1355
  }
@@ -1132,7 +1365,7 @@ function writePieces(s, pieces) {
1132
1365
  let previous;
1133
1366
  let emptiesSincePrevious = [];
1134
1367
  for (const piece of pieces) {
1135
- if (piece.text === "") {
1368
+ if (piece.text !== void 0 && getCode(piece.text) === "") {
1136
1369
  emptiesSincePrevious.push(piece);
1137
1370
  continue;
1138
1371
  }
@@ -1143,7 +1376,7 @@ function writePieces(s, pieces) {
1143
1376
  for (const piece of pieces) {
1144
1377
  if (piece.text === void 0) continue;
1145
1378
  changed = true;
1146
- if (piece.text === "") s.remove(piece.node.start, piece.node.end);
1379
+ if (getCode(piece.text) === "") s.remove(piece.node.start, piece.node.end);
1147
1380
  else s.overwrite(piece.node.start, piece.node.end, piece.text);
1148
1381
  }
1149
1382
  return changed;
@@ -1218,7 +1451,7 @@ function isStaticText(node) {
1218
1451
  if (inner.type === "TemplateLiteral") return inner.expressions.length === 0;
1219
1452
  return inner.type === "UnaryExpression" && inner.operator === "-" && inner.argument.type === "Literal" && typeof inner.argument.value === "number";
1220
1453
  }
1221
- function isIntrinsic(element) {
1454
+ function isIntrinsic$1(element) {
1222
1455
  const { name } = element.openingElement;
1223
1456
  return name.type === "JSXIdentifier" && isIntrinsicTag(name.name);
1224
1457
  }
@@ -1259,7 +1492,7 @@ var SizeEstimator = class {
1259
1492
  */
1260
1493
  jsx(node, inTemplate) {
1261
1494
  if (node.type === "JSXFragment") return this.children(node.children) + 2;
1262
- if (!isIntrinsic(node)) return (inTemplate ? 24 : 0) + this.component(node);
1495
+ if (!isIntrinsic$1(node)) return (inTemplate ? 24 : 0) + this.component(node);
1263
1496
  const tag = nameLength(node.openingElement.name);
1264
1497
  let size = (inTemplate ? 0 : TEMPLATE) + tag * 2 + 5;
1265
1498
  let dynamic = false;
@@ -1576,7 +1809,7 @@ var Folder = class {
1576
1809
  return isJSXChild(node, this.context.parents) || this.context.parents.get(node)?.type === "JSXAttribute";
1577
1810
  }
1578
1811
  replace(node, text) {
1579
- if (getText(this.context, node) === text) return;
1812
+ if (getText(this.context, node).code === getCode(text)) return;
1580
1813
  this.context.s.overwrite(node.start, node.end, text);
1581
1814
  this.changed = true;
1582
1815
  }
@@ -1642,11 +1875,11 @@ var Folder = class {
1642
1875
  const parts = discarded ? effectfulParts(discarded) : [];
1643
1876
  if (parts.length === 0) {
1644
1877
  const text = getText(this.context, value);
1645
- return needsParensAt(target, value, this.context.parents) ? `(${text})` : text;
1878
+ return needsParensAt(target, value, this.context.parents) ? joinText`(${text})` : text;
1646
1879
  }
1647
1880
  const texts = getTexts(this.context, parts);
1648
1881
  texts.push(getText(this.context, value));
1649
- return `(${texts.join(", ")})`;
1882
+ return joinText`(${join(texts, ", ")})`;
1650
1883
  }
1651
1884
  foldLogical(node) {
1652
1885
  const left = truthiness(node.left, this.lookup);
@@ -1763,7 +1996,7 @@ var Folder = class {
1763
1996
  if (value.value.includes("&")) return;
1764
1997
  return {
1765
1998
  kind: "expression",
1766
- text: JSON.stringify(value.value),
1999
+ text: this.context.s.written(JSON.stringify(value.value), value.start),
1767
2000
  primary: true
1768
2001
  };
1769
2002
  case "JSXElement":
@@ -1785,7 +2018,7 @@ var Folder = class {
1785
2018
  */
1786
2019
  foldedJSX(node) {
1787
2020
  const text = getText(this.context, node);
1788
- if (text.startsWith("<")) return {
2021
+ if (text.code.startsWith("<")) return {
1789
2022
  kind: "jsx",
1790
2023
  text
1791
2024
  };
@@ -1839,7 +2072,7 @@ var Folder = class {
1839
2072
  let body = row.body;
1840
2073
  while (body.type === "ParenthesizedExpression") body = body.expression;
1841
2074
  if (body.type !== "JSXElement" && body.type !== "JSXFragment" || hasRefOrSpread(body)) return;
1842
- if (this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)) return;
2075
+ if (this.context.s.slice(body.start, body.end).code !== this.context.code.slice(body.start, body.end)) return;
1843
2076
  const scope = this.context.scopes.scopes.get(row);
1844
2077
  if (!scope) return;
1845
2078
  const params = [];
@@ -1852,11 +2085,11 @@ var Folder = class {
1852
2085
  const indexParam = params.at(1);
1853
2086
  const rows = [];
1854
2087
  for (const [index, item] of list.items.entries()) {
1855
- const copy = new MagicString(this.context.code);
2088
+ const copy = this.context.s.fresh();
1856
2089
  if (itemParam && !this.substituteItem(copy, itemParam, item, byIndex) || indexParam && !this.substituteIndex(copy, indexParam, index, !byIndex)) return;
1857
2090
  rows.push(copy.slice(body.start, body.end));
1858
2091
  }
1859
- const text = `<>${rows.join("")}</>`;
2092
+ const text = joinText`<>${join(rows)}</>`;
1860
2093
  if (!this.unrollingPays(element, text, list.declaration)) return;
1861
2094
  return {
1862
2095
  kind: "jsx",
@@ -1954,7 +2187,7 @@ var Folder = class {
1954
2187
  }
1955
2188
  /** A value's text in place of `node`, with parentheses unless it fills a JSX container. */
1956
2189
  valueAt(node, text) {
1957
- return this.context.parents.get(node)?.type === "JSXExpressionContainer" ? text : `(${text})`;
2190
+ return this.context.parents.get(node)?.type === "JSXExpressionContainer" ? text : joinText`(${text})`;
1958
2191
  }
1959
2192
  /** Writes an item's index over each read of the row's index parameter. */
1960
2193
  substituteIndex(copy, param, index, accessor) {
@@ -1976,7 +2209,7 @@ var Folder = class {
1976
2209
  unrollingPays(element, text, declaration) {
1977
2210
  const inTemplate = this.joinsParentTemplate(element);
1978
2211
  const loop = new SizeEstimator(this.context.code).jsx(element, inTemplate) + (declaration ? compactLength(this.context.code.slice(declaration.start, declaration.end)) : 0);
1979
- const code = `const __so_rows__ = ${text};`;
2212
+ const code = `const __so_rows__ = ${text.code};`;
1980
2213
  const statement = parse$1(this.context.filename, code).body.at(0);
1981
2214
  const init = statement?.type === "VariableDeclaration" ? statement.declarations.at(0)?.init : void 0;
1982
2215
  if (init?.type !== "JSXFragment") return false;
@@ -2061,12 +2294,12 @@ var Folder = class {
2061
2294
  }
2062
2295
  }
2063
2296
  if (tag === void 0) return;
2064
- const attributes = [];
2297
+ const attributes = [tag];
2065
2298
  for (const attribute of element.openingElement.attributes) if (attribute !== component) attributes.push(getText(this.context, attribute));
2066
- const opening = [tag, ...attributes].join(" ");
2299
+ const opening = join(attributes, " ");
2067
2300
  return {
2068
2301
  kind: "jsx",
2069
- text: element.closingElement ? `<${opening}>${innerText(this.context.s, element)}</${tag}>` : `<${opening} />`
2302
+ text: element.closingElement ? joinText`<${opening}>${innerText(this.context.s, element)}</${tag}>` : joinText`<${opening} />`
2070
2303
  };
2071
2304
  }
2072
2305
  /**
@@ -2081,7 +2314,7 @@ var Folder = class {
2081
2314
  switch (resolved.kind) {
2082
2315
  case "empty": return "null";
2083
2316
  case "jsx": return resolved.text;
2084
- case "expression": return resolved.primary ? resolved.text : `(${resolved.text})`;
2317
+ case "expression": return resolved.primary ? resolved.text : joinText`(${resolved.text})`;
2085
2318
  default: {
2086
2319
  const significant = getSignificant(resolved.children);
2087
2320
  const only = significant.at(0);
@@ -2090,7 +2323,7 @@ var Folder = class {
2090
2323
  const first = resolved.children.at(0);
2091
2324
  const last = resolved.children.at(-1);
2092
2325
  if (!first || !last) return "null";
2093
- return `<>${this.context.s.slice(first.start, last.end)}</>`;
2326
+ return joinText`<>${this.context.s.slice(first.start, last.end)}</>`;
2094
2327
  }
2095
2328
  }
2096
2329
  }
@@ -2126,7 +2359,7 @@ var Folder = class {
2126
2359
  pieces.push(replacedPiece(child, resolved.text));
2127
2360
  break;
2128
2361
  case "expression":
2129
- pieces.push(replacedPiece(child, `{${resolved.text}}`));
2362
+ pieces.push(replacedPiece(child, joinText`{${resolved.text}}`));
2130
2363
  break;
2131
2364
  default: pieces.push(replacedPiece(child, ""));
2132
2365
  }
@@ -2157,10 +2390,10 @@ var Folder = class {
2157
2390
  const { params } = callee;
2158
2391
  const args = expression.arguments;
2159
2392
  if (params.length !== args.length || hasRefOrSpread(body)) return;
2160
- if (this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)) return;
2393
+ if (this.context.s.slice(body.start, body.end).code !== this.context.code.slice(body.start, body.end)) return;
2161
2394
  const scope = this.context.scopes.scopes.get(callee);
2162
2395
  if (!scope) return;
2163
- const copy = new MagicString(this.context.code);
2396
+ const copy = this.context.s.fresh();
2164
2397
  for (const [index, param] of params.entries()) {
2165
2398
  const arg = args.at(index);
2166
2399
  if (param.type !== "Identifier" || !arg || arg.type === "SpreadElement") return;
@@ -2171,7 +2404,7 @@ var Folder = class {
2171
2404
  if (arg.type === "Identifier" && lookup(scopeAt(this.context.scopes, this.context.parents, reference), arg.name) !== this.context.scopes.references.get(arg)) return;
2172
2405
  const parent = this.context.parents.get(reference);
2173
2406
  const shorthand = parent?.type === "Property" && parent.shorthand && parent.value === reference;
2174
- copy.overwrite(reference.start, reference.end, shorthand ? `${param.name}: ${text}` : text);
2407
+ copy.overwrite(reference.start, reference.end, shorthand ? joinText`${param.name}: ${text}` : text);
2175
2408
  }
2176
2409
  }
2177
2410
  return copy.slice(body.start, body.end);
@@ -2183,7 +2416,7 @@ var Folder = class {
2183
2416
  switch (node.type) {
2184
2417
  case "Literal": return "regex" in node ? void 0 : getText(this.context, node);
2185
2418
  case "TemplateLiteral": return node.expressions.length === 0 ? getText(this.context, node) : void 0;
2186
- case "UnaryExpression": return node.operator === "-" && node.argument.type === "Literal" ? `(${getText(this.context, node)})` : void 0;
2419
+ case "UnaryExpression": return node.operator === "-" && node.argument.type === "Literal" ? joinText`(${getText(this.context, node)})` : void 0;
2187
2420
  case "Identifier": {
2188
2421
  const binding = this.context.scopes.references.get(node);
2189
2422
  return binding && !binding.mutated ? node.name : void 0;
@@ -2266,12 +2499,12 @@ var Folder = class {
2266
2499
  return true;
2267
2500
  }
2268
2501
  replaceStatement(statement, text) {
2269
- if (text === "") {
2502
+ if (getCode(text) === "") {
2270
2503
  this.context.s.remove(statement.start, statement.end);
2271
2504
  this.changed = true;
2272
2505
  return;
2273
2506
  }
2274
- this.replace(statement, continuesPreviousStatement(text) ? `;${text}` : text);
2507
+ this.replace(statement, continuesPreviousStatement(getCode(text)) ? joinText`;${text}` : text);
2275
2508
  }
2276
2509
  /**
2277
2510
  * A statement that keeps a discarded test's side effects, or `undefined`
@@ -2281,8 +2514,8 @@ var Folder = class {
2281
2514
  const parts = effectfulParts(test);
2282
2515
  const first = parts.at(0);
2283
2516
  if (first === void 0) return;
2284
- const text = getTexts(this.context, parts).join(", ");
2285
- return startsLikeStatement(first) ? `(${text});` : `${text};`;
2517
+ const text = join(getTexts(this.context, parts), ", ");
2518
+ return startsLikeStatement(first) ? joinText`(${text});` : joinText`${text};`;
2286
2519
  }
2287
2520
  /**
2288
2521
  * Resolves an `if` with a constant test. Returns the kept branch, `null`
@@ -2299,7 +2532,7 @@ var Folder = class {
2299
2532
  const effect = this.discardedTest(statement.test);
2300
2533
  if (effect !== void 0) parts.push(effect);
2301
2534
  if (kept) parts.push(getText(this.context, kept));
2302
- this.replaceStatement(statement, parts.join(" "));
2535
+ this.replaceStatement(statement, join(parts, " "));
2303
2536
  return kept;
2304
2537
  }
2305
2538
  resolveWhile(statement) {
@@ -2833,11 +3066,6 @@ function removeProviders(context) {
2833
3066
  //#endregion
2834
3067
  //#region src/copy-size.ts
2835
3068
  /**
2836
- * Measures a component's copy at a call site: folds it, and inlines the
2837
- * components it calls, as the passes after inlining would. Then it estimates
2838
- * its size with `SizeEstimator`.
2839
- */
2840
- /**
2841
3069
  * The name of the function a copy is wrapped in to be folded and measured.
2842
3070
  * It is capitalized, so the inline pass can move statements into it.
2843
3071
  */
@@ -2858,12 +3086,12 @@ const MAX_DEPTH = 3;
2858
3086
  */
2859
3087
  function copySize(filename, header, copy, inTemplate, options, called, measured) {
2860
3088
  const calls = depth < MAX_DEPTH ? called : void 0;
2861
- let code = `${header}\n${calls?.declarations ?? ""}\nfunction ${WRAPPER}() {\n${copy.statements.join("\n")}\nreturn (${copy.root});\n}\n`;
3089
+ let code = `${header}\n${calls?.declarations ?? ""}\nfunction ${WRAPPER}() {\n${join(copy.statements, "\n").code}\nreturn (${getCode(copy.root)});\n}\n`;
2862
3090
  for (let round = 0; round < 4; round += 1) {
2863
3091
  let changed = false;
2864
3092
  for (const pass of calls ? [fold, calls.inline] : [fold]) {
2865
3093
  const program = parse$1(filename, code);
2866
- const s = new MagicString(code);
3094
+ const s = new Editor(code, false);
2867
3095
  depth += 1;
2868
3096
  let passChanged;
2869
3097
  try {
@@ -2903,79 +3131,6 @@ function copySize(filename, header, copy, inTemplate, options, called, measured)
2903
3131
  }
2904
3132
  //#endregion
2905
3133
  //#region src/inline.ts
2906
- /**
2907
- * The inline pass: replaces a component call with the component's body.
2908
- *
2909
- * `<Card title="Hi" />` with `function Card(props) { return <div>{props.title}</div>; }`
2910
- * becomes `<div>{"Hi"}</div>`. The JSX transform then sees one tree instead of
2911
- * two, so it emits one template, one clone, and fewer hydration markers.
2912
- *
2913
- * A component inlines when its shape keeps the result equivalent:
2914
- *
2915
- * - It is declared once at the top level of the module, with a capitalized
2916
- * name, as a function declaration or a `const` bound to a function. A
2917
- * tag of an alias, like `const Separator = SeparatorRoot`, is renamed to
2918
- * the component first. See `renameAliasTags`.
2919
- * - It takes no parameter, or one identifier that is only read as `props.name`,
2920
- * or spread onto an element as `{...props}`.
2921
- * - Its body is statements followed by one final `return` of JSX, or an arrow
2922
- * function whose body is JSX.
2923
- * - It does not use `this`, `arguments`, `new.target`, or `super`.
2924
- *
2925
- * A call site inlines when it passes plain attributes: no spread and no
2926
- * namespaced attribute. A `ref` moves to the element the component forwards
2927
- * `props.ref` to. See `refValue`.
2928
- *
2929
- * # How props keep their meaning
2930
- *
2931
- * Solid passes a dynamic prop as a getter, so every read of `props.name`
2932
- * evaluates the attribute's expression again. Inlining replaces each read
2933
- * with the expression itself, which does the same.
2934
- *
2935
- * A static prop, such as an identifier or a function, is evaluated once when
2936
- * the component is created. Its expression is substituted directly when that
2937
- * gives the same value, such as a literal or a binding nothing reassigns, or
2938
- * when the prop is read exactly once. Otherwise its value is stored in a
2939
- * `const` before the component body runs.
2940
- *
2941
- * # Where a component body can go
2942
- *
2943
- * A component whose body is only JSX inlines anywhere JSX can go.
2944
- *
2945
- * Statements, and stored props, have to run where the component would have
2946
- * been created. Solid runs a component untracked, so the statements move into
2947
- * the function whose returned JSX holds the call, when that function also
2948
- * runs untracked:
2949
- *
2950
- * - a component;
2951
- * - the child callback of `<For>` or `<Repeat>`, which runs once per item
2952
- * under its own owner;
2953
- * - the child callback of `<Show>` or `<Match>` that takes the value, which
2954
- * runs once each time the condition turns true;
2955
- * - the callback given to `render`, which runs once under its root.
2956
- *
2957
- * The call has to be in that returned JSX with only intrinsic elements and
2958
- * fragments around it, so it is created exactly once each time that function
2959
- * runs.
2960
- *
2961
- * A context provider is a component, so statements do not move out of it,
2962
- * and `useContext` still runs under it. The exception is a provider whose
2963
- * subtree only runs visible code. Statements move out through it, and each
2964
- * `useContext` of its context in a copy becomes its value. See `provider.ts`.
2965
- *
2966
- * The props can also be read through `merge()` and `omit()` views declared
2967
- * in the component. Each call site knows which props it passes, so a read
2968
- * of a view resolves to a prop, a literal default, or `undefined`, and a
2969
- * spread of a view becomes the attributes it holds.
2970
- *
2971
- * # Accepted differences
2972
- *
2973
- * - A prop that is a function and is called as `props.name()` runs with
2974
- * `this` set to its own receiver instead of the props object.
2975
- * - Statements moved into the host run before the host's JSX is created,
2976
- * instead of while it is created. The order of `onSettled` and effect
2977
- * registration across siblings can change.
2978
- */
2979
3134
  function isWithin(node, container) {
2980
3135
  return node.start >= container.start && node.end <= container.end;
2981
3136
  }
@@ -3620,7 +3775,7 @@ var Inliner = class {
3620
3775
  const value = evaluate(property.value, () => void 0);
3621
3776
  const text = value ? literalText(value.value) : void 0;
3622
3777
  if (text === void 0 || isReservedPropName(key)) return;
3623
- defaults.set(key, text);
3778
+ defaults.set(key, this.context.s.written(text, property.value.start));
3624
3779
  }
3625
3780
  sources.push({
3626
3781
  defaults,
@@ -3730,11 +3885,11 @@ var Inliner = class {
3730
3885
  };
3731
3886
  let text;
3732
3887
  let primary = true;
3733
- if (significant.length > 1 || only.type === "JSXText") text = `<>${this.context.s.slice(element.openingElement.end, element.closingElement?.start ?? element.end)}</>`;
3888
+ if (significant.length > 1 || only.type === "JSXText") text = joinText`<>${this.context.s.slice(element.openingElement.end, element.closingElement?.start ?? element.end)}</>`;
3734
3889
  else if (only.type === "JSXExpressionContainer") {
3735
3890
  if (only.expression.type === "JSXEmptyExpression") return;
3736
3891
  const value = this.expressionValue(only.expression, "children", reads, fresh, snapshots);
3737
- if (value.kind !== "expression" || value.text !== getText(this.context, only.expression)) return value;
3892
+ if (value.kind !== "expression" || getCode(value.text) !== getText(this.context, only.expression).code) return value;
3738
3893
  text = value.text;
3739
3894
  primary = value.primary;
3740
3895
  } else text = getText(this.context, only);
@@ -3785,7 +3940,7 @@ var Inliner = class {
3785
3940
  if (value.value.includes("&")) return;
3786
3941
  return {
3787
3942
  kind: "expression",
3788
- text: JSON.stringify(value.value),
3943
+ text: this.context.s.written(JSON.stringify(value.value), value.start),
3789
3944
  primary: true
3790
3945
  };
3791
3946
  case "JSXElement":
@@ -3824,7 +3979,7 @@ var Inliner = class {
3824
3979
  primary
3825
3980
  };
3826
3981
  const local = fresh(name);
3827
- snapshots.push(`const ${local} = ${text};`);
3982
+ snapshots.push(joinText`const ${local} = ${text};`);
3828
3983
  return {
3829
3984
  kind: "expression",
3830
3985
  text: local,
@@ -3927,7 +4082,7 @@ var Inliner = class {
3927
4082
  this.reason = "context-value";
3928
4083
  return;
3929
4084
  }
3930
- const copy = new MagicString(this.context.code);
4085
+ const copy = this.context.s.fresh();
3931
4086
  this.renameLocals(copy, component, fresh);
3932
4087
  this.substituteProps(copy, views.propReads, values);
3933
4088
  this.substituteViews(copy, component, element, views, values);
@@ -3937,7 +4092,7 @@ var Inliner = class {
3937
4092
  const last = component.statements.at(-1);
3938
4093
  if (first && last) {
3939
4094
  const text = copy.slice(first.start, last.end);
3940
- statements.push(text.endsWith(";") ? text : `${text};`);
4095
+ statements.push(text.code.endsWith(";") ? text : joinText`${text};`);
3941
4096
  }
3942
4097
  return {
3943
4098
  element,
@@ -4041,7 +4196,7 @@ var Inliner = class {
4041
4196
  const host = this.findHost(element);
4042
4197
  if (!host) continue;
4043
4198
  const name = this.freshName(`${provider.context.name.charAt(0).toLowerCase()}${provider.context.name.slice(1)}Value`);
4044
- this.addToHost(host, [`const ${name} = ${getText(this.context, provider.value)};`]);
4199
+ this.addToHost(host, [joinText`const ${name} = ${getText(this.context, provider.value)};`]);
4045
4200
  this.context.s.overwrite(provider.value.start, provider.value.end, name);
4046
4201
  this.transparent.set(element, {
4047
4202
  provider,
@@ -4096,7 +4251,7 @@ var Inliner = class {
4096
4251
  let names = taken.get(spread.element);
4097
4252
  if (!names) {
4098
4253
  names = /* @__PURE__ */ new Set();
4099
- for (const attribute of spread.element.openingElement.attributes) if (attribute.type === "JSXAttribute") names.add(attribute.name.type === "JSXIdentifier" ? attribute.name.name : getText(this.context, attribute.name));
4254
+ for (const attribute of spread.element.openingElement.attributes) if (attribute.type === "JSXAttribute") names.add(attribute.name.type === "JSXIdentifier" ? attribute.name.name : getText(this.context, attribute.name).code);
4100
4255
  taken.set(spread.element, names);
4101
4256
  }
4102
4257
  const keys = /* @__PURE__ */ new Map();
@@ -4122,8 +4277,8 @@ var Inliner = class {
4122
4277
  */
4123
4278
  substituteViews(copy, component, element, views, values) {
4124
4279
  for (const [member, text] of views.texts) {
4125
- const bare = text !== "void 0" || acceptsAnyExpression(this.context, member);
4126
- copy.overwrite(member.start, member.end, bare ? text : `(${text})`);
4280
+ const bare = getCode(text) !== "void 0" || acceptsAnyExpression(this.context, member);
4281
+ copy.overwrite(member.start, member.end, bare ? text : joinText`(${text})`);
4127
4282
  }
4128
4283
  for (const { spread, keys } of views.spreads) {
4129
4284
  const parts = [];
@@ -4131,16 +4286,16 @@ var Inliner = class {
4131
4286
  for (const [key, text] of keys) {
4132
4287
  const value = values.get(key);
4133
4288
  if (key === "children") children = this.spreadChildren(element, text, value);
4134
- else parts.push(`${key}={${text ?? value?.text ?? "void 0"}}`);
4289
+ else parts.push(joinText`${key}={${text ?? value?.text ?? "void 0"}}`);
4135
4290
  }
4136
4291
  const { attribute } = spread;
4137
4292
  if (parts.length === 0) copy.remove(attribute.start, attribute.end);
4138
- else copy.overwrite(attribute.start, attribute.end, parts.join(" "));
4293
+ else copy.overwrite(attribute.start, attribute.end, join(parts, " "));
4139
4294
  if (children !== void 0) {
4140
4295
  const opening = spread.element.openingElement;
4141
4296
  const tag = copy.slice(opening.name.start, opening.name.end);
4142
4297
  const close = this.context.code.lastIndexOf("/>", opening.end);
4143
- copy.overwrite(close, opening.end, `>${children}</${tag}>`);
4298
+ copy.overwrite(close, opening.end, joinText`>${children}</${tag}>`);
4144
4299
  }
4145
4300
  }
4146
4301
  for (const declaration of component.viewDeclarations) copy.remove(declaration.start, declaration.end);
@@ -4150,10 +4305,10 @@ var Inliner = class {
4150
4305
  * children, or the value of a single expression or default.
4151
4306
  */
4152
4307
  spreadChildren(element, text, value) {
4153
- if (text !== void 0) return text === "void 0" ? void 0 : `{${text}}`;
4308
+ if (text !== void 0) return getCode(text) === "void 0" ? void 0 : joinText`{${text}}`;
4154
4309
  if (!value) return;
4155
4310
  if (value.kind === "children" && element.closingElement) return this.context.s.slice(element.openingElement.end, element.closingElement.start);
4156
- return `{${value.text}}`;
4311
+ return joinText`{${value.text}}`;
4157
4312
  }
4158
4313
  renameLocals(copy, component, fresh) {
4159
4314
  for (const local of component.locals) {
@@ -4183,7 +4338,7 @@ var Inliner = class {
4183
4338
  continue;
4184
4339
  }
4185
4340
  const bare = value.primary || acceptsAnyExpression(this.context, read.member);
4186
- copy.overwrite(read.member.start, read.member.end, bare ? value.text : `(${value.text})`);
4341
+ copy.overwrite(read.member.start, read.member.end, bare ? value.text : joinText`(${value.text})`);
4187
4342
  }
4188
4343
  for (const [parent, pieces] of spliced) {
4189
4344
  const children = [];
@@ -4334,7 +4489,7 @@ var Inliner = class {
4334
4489
  const texts = [];
4335
4490
  for (const component of components) {
4336
4491
  const statement = this.topLevelStatement(component.binding.declaration);
4337
- if (statement) texts.push(getText(this.context, statement));
4492
+ if (statement) texts.push(getText(this.context, statement).code);
4338
4493
  }
4339
4494
  return texts.join("\n");
4340
4495
  }
@@ -4606,7 +4761,7 @@ var Inliner = class {
4606
4761
  const tag = element.openingElement.name;
4607
4762
  if (tag.type === "JSXMemberExpression") return {
4608
4763
  reason: "member-tag",
4609
- name: getText(this.context, tag)
4764
+ name: getText(this.context, tag).code
4610
4765
  };
4611
4766
  if (tag.type !== "JSXIdentifier" || !isCapitalized(tag.name)) return;
4612
4767
  const { name } = tag;
@@ -4642,11 +4797,11 @@ var Inliner = class {
4642
4797
  writeHosts() {
4643
4798
  for (const { host, texts } of this.hosts.values()) if (host.kind === "return") {
4644
4799
  const indent = this.indentationAt(host.statement.start);
4645
- let written = "";
4646
- for (const text of texts) written += `${text}\n${indent}`;
4647
- this.context.s.prependRight(host.statement.start, written);
4800
+ const written = [];
4801
+ for (const text of texts) written.push(text, `\n${indent}`);
4802
+ this.context.s.prependRight(host.statement.start, join(written));
4648
4803
  } else {
4649
- this.context.s.prependRight(host.body.start, `{ ${texts.join(" ")} return `);
4804
+ this.context.s.prependRight(host.body.start, joinText`{ ${join(texts, " ")} return `);
4650
4805
  this.context.s.appendLeft(host.body.end, "; }");
4651
4806
  }
4652
4807
  }
@@ -4911,7 +5066,7 @@ var MemoInliner = class {
4911
5066
  for (const call of calls) {
4912
5067
  const parent = this.context.parents.get(call);
4913
5068
  const bare = parent?.type === "JSXExpressionContainer" || parent?.type === "VariableDeclarator" || parent?.type === "ReturnStatement" || parent?.type === "ArrayExpression" || parent?.type === "Property" || parent?.type === "CallExpression" && parent.callee !== call;
4914
- this.context.s.overwrite(call.start, call.end, bare ? text : `(${text})`);
5069
+ this.context.s.overwrite(call.start, call.end, bare ? text : joinText`(${text})`);
4915
5070
  this.edited.push([call.start, call.end]);
4916
5071
  }
4917
5072
  this.context.s.remove(statement.start, statement.end);
@@ -5134,14 +5289,14 @@ var MemoInliner = class {
5134
5289
  if (calls.length === 0) return;
5135
5290
  for (const [start, end] of this.edited) if (start < statement.end && end > statement.start) return;
5136
5291
  const text = getText(this.context, body);
5137
- const length = compactLength(text);
5292
+ const length = compactLength(text.code);
5138
5293
  if ((calls.length - 1) * length > calls.length * 3 + 13) return;
5139
5294
  if (usesFunctionContext(this.context, fn)) return;
5140
5295
  for (const call of calls) if (!this.resolvesSameAt(body, call, binding)) return;
5141
5296
  const bare = isPrimary(body);
5142
5297
  for (const call of calls) {
5143
5298
  const inContainer = this.context.parents.get(call)?.type === "JSXExpressionContainer" && body.type !== "SequenceExpression";
5144
- this.context.s.overwrite(call.start, call.end, bare || inContainer ? text : `(${text})`);
5299
+ this.context.s.overwrite(call.start, call.end, bare || inContainer ? text : joinText`(${text})`);
5145
5300
  this.edited.push([call.start, call.end]);
5146
5301
  }
5147
5302
  this.context.s.remove(statement.start, statement.end);
@@ -5411,7 +5566,7 @@ function lowerConditionals(context) {
5411
5566
  const ternary = ternaryOf(context, node);
5412
5567
  const form = ternary === void 0 ? void 0 : formAt(context, node);
5413
5568
  if (ternary !== void 0 && form !== void 0) {
5414
- context.s.overwrite(node.start, node.end, form === "container" ? `{${ternary}}` : `<>{${ternary}}</>`);
5569
+ context.s.overwrite(node.start, node.end, form === "container" ? joinText`{${ternary}}` : joinText`<>{${ternary}}</>`);
5415
5570
  changed = true;
5416
5571
  return;
5417
5572
  }
@@ -5440,7 +5595,7 @@ function ternaryOf(context, element) {
5440
5595
  case "Show": {
5441
5596
  const branch = branchOf(context, element, ["when", "fallback"]);
5442
5597
  if (branch === void 0) return;
5443
- return `${branch.when} ? ${branch.children} : ${branch.fallback ?? "undefined"}`;
5598
+ return joinText`${branch.when} ? ${branch.children} : ${branch.fallback ?? "undefined"}`;
5444
5599
  }
5445
5600
  case "Switch": return switchTernary(context, element);
5446
5601
  default: return;
@@ -5452,17 +5607,17 @@ function ternaryOf(context, element) {
5452
5607
  function switchTernary(context, element) {
5453
5608
  const props = propsOf(context, element, ["fallback"]);
5454
5609
  if (props === void 0) return;
5455
- let chain = "";
5610
+ const chain = [];
5456
5611
  let count = 0;
5457
5612
  for (const child of significantChildren(element.children)) {
5458
5613
  if (child.type !== "JSXElement" || builtInOf(context, child) !== "Match") return;
5459
5614
  const branch = branchOf(context, child, ["when"]);
5460
5615
  if (branch === void 0) return;
5461
- chain += `${branch.when} ? ${branch.children} : `;
5616
+ chain.push(branch.when, " ? ", branch.children, " : ");
5462
5617
  count += 1;
5463
5618
  }
5464
5619
  if (count === 0) return;
5465
- return `${chain}${props.get("fallback") ?? "undefined"}`;
5620
+ return join([...chain, props.get("fallback") ?? "undefined"]);
5466
5621
  }
5467
5622
  /**
5468
5623
  * How a `<Show>` or `<Switch>` at this position is written once lowered, or `undefined`
@@ -5539,7 +5694,7 @@ function branchOf(context, element, names) {
5539
5694
  const inner = closingElement ? context.s.slice(element.openingElement.end, closingElement.start) : "";
5540
5695
  return {
5541
5696
  when,
5542
- children: significant.length > 0 ? `<>${inner}</>` : "undefined",
5697
+ children: significant.length > 0 ? joinText`<>${inner}</>` : "undefined",
5543
5698
  fallback: props.get("fallback")
5544
5699
  };
5545
5700
  }
@@ -5555,7 +5710,7 @@ function callbackBody(context, element, callback) {
5555
5710
  const value = findAttribute(element, "when")?.value;
5556
5711
  if (value?.type !== "JSXExpressionContainer" || value.expression.type === "JSXEmptyExpression" || !isPlainRead(context, value.expression)) return;
5557
5712
  const when = value.expression;
5558
- const whenText = `(${context.s.slice(when.start, when.end)})`;
5713
+ const whenText = joinText`(${context.s.slice(when.start, when.end)})`;
5559
5714
  const names = [];
5560
5715
  collectReferences(context, when, names);
5561
5716
  const binding = lookup(scopeAt(context.scopes, context.parents, param), param.name);
@@ -5575,17 +5730,18 @@ function callbackBody(context, element, callback) {
5575
5730
  else edits.push({
5576
5731
  start: reference.start,
5577
5732
  end: reference.end,
5578
- text: `(() => ${whenText})`
5733
+ text: joinText`(() => ${whenText})`
5579
5734
  });
5580
5735
  }
5581
5736
  edits.sort((a, b) => a.start - b.start);
5582
- let text = "";
5737
+ const parts = [];
5583
5738
  let at = body.start;
5584
5739
  for (const edit of edits) {
5585
- text += context.s.slice(at, edit.start) + edit.text;
5740
+ parts.push(context.s.slice(at, edit.start), edit.text);
5586
5741
  at = edit.end;
5587
5742
  }
5588
- return text + context.s.slice(at, body.end);
5743
+ parts.push(context.s.slice(at, body.end));
5744
+ return join(parts);
5589
5745
  }
5590
5746
  /**
5591
5747
  * Whether reading an expression again gives the same value, with nothing run
@@ -5684,7 +5840,7 @@ function expressionText(context, attribute) {
5684
5840
  switch (value.type) {
5685
5841
  case "JSXExpressionContainer":
5686
5842
  if (value.expression.type === "JSXEmptyExpression") return;
5687
- return `(${context.s.slice(value.expression.start, value.expression.end)})`;
5843
+ return joinText`(${context.s.slice(value.expression.start, value.expression.end)})`;
5688
5844
  case "JSXElement":
5689
5845
  case "JSXFragment": return context.s.slice(value.start, value.end);
5690
5846
  default: return;
@@ -5743,6 +5899,236 @@ function terminateStatements(context) {
5743
5899
  return changed;
5744
5900
  }
5745
5901
  //#endregion
5902
+ //#region src/tidy.ts
5903
+ /**
5904
+ * The text Solid's JSX transform makes of a raw text child: when the text
5905
+ * has a line break, each line after the first loses its leading spaces, lines
5906
+ * of only spaces drop out and the rest join with a space; then every run of
5907
+ * spaces becomes one space. This differs from React's rule, which keeps runs
5908
+ * of spaces on one line.
5909
+ */
5910
+ function cleanText(raw) {
5911
+ let text = raw.replaceAll("\r", "");
5912
+ if (text.includes("\n")) {
5913
+ const kept = [];
5914
+ for (const [index, line] of text.split("\n").entries()) {
5915
+ const trimmed = index === 0 ? line : line.replace(/^[ \t]+/, "");
5916
+ if (/[^ \t]/.test(trimmed)) kept.push(trimmed);
5917
+ }
5918
+ text = kept.join(" ");
5919
+ }
5920
+ return text.replaceAll(/[ \t\n]+/g, " ");
5921
+ }
5922
+ /**
5923
+ * Whether a text holds whitespace or format characters other than space,
5924
+ * tab and line breaks, such as U+0085 or a byte order mark. Solid's JSX
5925
+ * transform and JavaScript disagree on some of them, so such text stays as it is.
5926
+ */
5927
+ function hasUnusualSpace(text) {
5928
+ return /(?![ \t\n\r])[\s\p{White_Space}\p{Cf}]/u.test(text);
5929
+ }
5930
+ /**
5931
+ * The string a container holds when it is a plain string written without
5932
+ * escapes, such as `{'a'}` or `{`a`}`. The characters between the quotes are
5933
+ * then the string itself, so tidying keeps them, and their source map
5934
+ * positions, and only drops what is around them.
5935
+ */
5936
+ function readString(container, code) {
5937
+ const { expression } = container;
5938
+ let value;
5939
+ if (expression.type === "Literal" && typeof expression.value === "string") value = expression.value;
5940
+ else if (expression.type === "TemplateLiteral" && expression.expressions.length === 0 && expression.quasis.length === 1) value = expression.quasis[0].value.cooked ?? void 0;
5941
+ if (value === void 0 || code.slice(expression.start + 1, expression.end - 1) !== value) return;
5942
+ if ((code.slice(container.start + 1, expression.start) + code.slice(expression.end, container.end - 1)).trim() !== "") return;
5943
+ return value;
5944
+ }
5945
+ /**
5946
+ * Replaces the braces and quotes around a string with `before` and `after`,
5947
+ * keeping the string's own characters where they are.
5948
+ */
5949
+ function unwrapString(container, before, after, context) {
5950
+ const { expression } = container;
5951
+ const { code, s } = context;
5952
+ s.remove(container.start, expression.start);
5953
+ s.remove(expression.end, container.end);
5954
+ const open = code[expression.start];
5955
+ const close = code[expression.end - 1];
5956
+ if (before === open) {} else if (before === "") s.remove(expression.start, expression.start + 1);
5957
+ else s.overwrite(expression.start, expression.start + 1, s.written(before, expression.start));
5958
+ if (after === close) {} else if (after === "") s.remove(expression.end - 1, expression.end);
5959
+ else s.overwrite(expression.end - 1, expression.end, s.written(after, expression.end - 1));
5960
+ }
5961
+ /** Whether a container holds nothing, not even a comment. */
5962
+ function isEmpty(container, code) {
5963
+ return container.expression.type === "JSXEmptyExpression" && code.slice(container.start + 1, container.end - 1).trim() === "";
5964
+ }
5965
+ /**
5966
+ * The pieces a list of children renders: each text that is not empty, and a
5967
+ * mark for each child that is not text.
5968
+ */
5969
+ function renderPieces(parts) {
5970
+ const pieces = [];
5971
+ let raw;
5972
+ const flush = () => {
5973
+ if (raw !== void 0) {
5974
+ const text = cleanText(raw);
5975
+ if (text !== "") pieces.push(text);
5976
+ raw = void 0;
5977
+ }
5978
+ };
5979
+ for (const part of parts) {
5980
+ if (!part) continue;
5981
+ if ("raw" in part) raw = (raw ?? "") + part.raw;
5982
+ else if ("literal" in part) {
5983
+ flush();
5984
+ if (part.literal !== "") pieces.push(part.literal);
5985
+ } else {
5986
+ flush();
5987
+ pieces.push(`\0${String(part.other)}`);
5988
+ }
5989
+ }
5990
+ flush();
5991
+ return pieces;
5992
+ }
5993
+ /**
5994
+ * What a list of children renders. In an element, Solid's JSX transform
5995
+ * writes the texts next to each other into the template as one text, so
5996
+ * only the joined text counts. Anywhere else, such as a fragment, each text
5997
+ * stays its own string, so the pieces must stay apart too.
5998
+ */
5999
+ function render(parts, inElement) {
6000
+ const pieces = renderPieces(parts);
6001
+ if (!inElement) return JSON.stringify(pieces);
6002
+ let joined = "";
6003
+ for (const piece of pieces) joined += piece.startsWith("\0") ? `${piece}\0` : piece;
6004
+ return joined;
6005
+ }
6006
+ /** Whether an element is an HTML or SVG element, which Solid lowers into a template. */
6007
+ function isIntrinsic(element) {
6008
+ const { name } = element.openingElement;
6009
+ if (name.type === "JSXNamespacedName") return true;
6010
+ return name.type === "JSXIdentifier" && /^[a-z]/.test(name.name);
6011
+ }
6012
+ /** A string that can be written as JSX text: no syntax, no entities, no line breaks. */
6013
+ function isPlainText(value) {
6014
+ return value !== "" && !/[{}<>&\r\n\t]/.test(value) && !hasUnusualSpace(value) && value.trim() === value;
6015
+ }
6016
+ /** A string that can be written as a JSX attribute in double quotes. */
6017
+ function isPlainAttribute(value) {
6018
+ return !/["&\r\n]/.test(value) && !hasUnusualSpace(value);
6019
+ }
6020
+ /**
6021
+ * Attributes whose string Solid's JSX transform treats differently once it
6022
+ * is written as a plain value: it moves a static `style` last, and `ref`,
6023
+ * `classList`, event handlers (`on` in any case) and namespaced attributes do
6024
+ * not take a string.
6025
+ */
6026
+ function isTidyAttribute(attribute) {
6027
+ const { name } = attribute;
6028
+ return name.type === "JSXIdentifier" && name.name !== "style" && name.name !== "ref" && name.name !== "classList" && !name.name.startsWith("on");
6029
+ }
6030
+ /**
6031
+ * Whether an element can get children from an attribute: a `children`
6032
+ * attribute or a spread. Its own children then decide whether those show, so
6033
+ * even an empty `{}` among them counts, and they stay as they are.
6034
+ */
6035
+ function hasChildrenAttribute(element) {
6036
+ for (const attribute of element.openingElement.attributes) if (attribute.type === "JSXSpreadAttribute" || attribute.name.type === "JSXIdentifier" && attribute.name.name === "children") return true;
6037
+ return false;
6038
+ }
6039
+ /**
6040
+ * Removes empty braces and writes plain strings as text, one at a time. Each
6041
+ * edit is kept only when the children still render the same with every edit
6042
+ * kept so far.
6043
+ */
6044
+ function tidyChildren(children, inElement, context) {
6045
+ const { code, s } = context;
6046
+ for (const child of children) if (child.type === "JSXText" && hasUnusualSpace(code.slice(child.start, child.end))) return false;
6047
+ const parts = [];
6048
+ for (const [index, child] of children.entries()) if (child.type === "JSXText") parts.push({ raw: code.slice(child.start, child.end) });
6049
+ else if (child.type === "JSXExpressionContainer" && isEmpty(child, code)) parts.push({ literal: "" });
6050
+ else if (child.type === "JSXExpressionContainer" && readString(child, code) !== void 0) parts.push({ literal: readString(child, code) ?? "" });
6051
+ else parts.push({ other: index });
6052
+ const expected = render(parts, inElement);
6053
+ let changed = false;
6054
+ for (const [index, child] of children.entries()) {
6055
+ if (child.type !== "JSXExpressionContainer") continue;
6056
+ const empty = isEmpty(child, code);
6057
+ const value = empty ? void 0 : readString(child, code);
6058
+ if (!empty && (value === void 0 || !isPlainText(value))) continue;
6059
+ const before = parts[index];
6060
+ parts[index] = empty ? void 0 : { raw: value ?? "" };
6061
+ if (render(parts, inElement) === expected) {
6062
+ if (empty) s.remove(child.start, child.end);
6063
+ else unwrapString(child, "", "", context);
6064
+ changed = true;
6065
+ } else parts[index] = before;
6066
+ }
6067
+ return changed;
6068
+ }
6069
+ /** The one element a fragment holds, when everything else in it is line breaks or empty braces. */
6070
+ function findOnlyElement(fragment, code) {
6071
+ let only;
6072
+ for (const child of fragment.children) if (child.type === "JSXElement") {
6073
+ if (only) return;
6074
+ only = child;
6075
+ } else if (child.type === "JSXText") {
6076
+ if (!/^[ \t\r\n]*$/.test(child.value) || cleanText(child.value) !== "") return;
6077
+ } else if (!(child.type === "JSXExpressionContainer" && isEmpty(child, code))) return;
6078
+ return only;
6079
+ }
6080
+ function tidyAttribute(attribute, context) {
6081
+ const { value } = attribute;
6082
+ if (value?.type !== "JSXExpressionContainer" || !isTidyAttribute(attribute)) return false;
6083
+ const text = readString(value, context.code);
6084
+ if (text === void 0 || !isPlainAttribute(text)) return false;
6085
+ unwrapString(value, "\"", "\"", context);
6086
+ return true;
6087
+ }
6088
+ /**
6089
+ * Whether a fragment is a branch of `? :`, or the right side of `&&`, `||`
6090
+ * or `??`, where the lowering of `<Show>` and `<Switch>` leaves them. There a
6091
+ * fragment around one element lowers the same as the element. Elsewhere,
6092
+ * such as a function's return, Solid's JSX transform writes different code.
6093
+ */
6094
+ function isBranch(fragment, context) {
6095
+ let node = fragment;
6096
+ let parent = context.parents.get(node);
6097
+ while (parent?.type === "ParenthesizedExpression") {
6098
+ node = parent;
6099
+ parent = context.parents.get(node);
6100
+ }
6101
+ if (parent?.type === "ConditionalExpression") return parent.consequent === node || parent.alternate === node;
6102
+ return parent?.type === "LogicalExpression" && parent.right === node;
6103
+ }
6104
+ function tidyJSX(context) {
6105
+ let changed = false;
6106
+ const visit = (node) => {
6107
+ if (node.type === "JSXFragment" && isBranch(node, context)) {
6108
+ const only = findOnlyElement(node, context.code);
6109
+ if (only) {
6110
+ context.s.remove(node.start, only.start);
6111
+ context.s.remove(only.end, node.end);
6112
+ changed = true;
6113
+ visit(only);
6114
+ return;
6115
+ }
6116
+ }
6117
+ const childrenFixed = node.type === "JSXElement" && hasChildrenAttribute(node);
6118
+ if ((node.type === "JSXElement" || node.type === "JSXFragment") && !childrenFixed) {
6119
+ const inElement = node.type === "JSXElement" && isIntrinsic(node);
6120
+ if (tidyChildren(node.children, inElement, context)) changed = true;
6121
+ }
6122
+ if (node.type === "JSXAttribute" && tidyAttribute(node, context)) {
6123
+ changed = true;
6124
+ return;
6125
+ }
6126
+ forEachChild(node, visit);
6127
+ };
6128
+ visit(context.program);
6129
+ return changed;
6130
+ }
6131
+ //#endregion
5746
6132
  //#region src/compile.ts
5747
6133
  const DEFAULT_BUILT_INS = [
5748
6134
  "For",
@@ -5787,7 +6173,7 @@ function runPass(parsed, filename, options, sourceMap, pass, skips) {
5787
6173
  const context = {
5788
6174
  code,
5789
6175
  filename,
5790
- s: new MagicString(code),
6176
+ s: new Editor(code, sourceMap),
5791
6177
  program: parsed.program,
5792
6178
  parents: parsed.parents,
5793
6179
  scopes: {
@@ -5800,11 +6186,7 @@ function runPass(parsed, filename, options, sourceMap, pass, skips) {
5800
6186
  if (!pass(context)) return;
5801
6187
  return {
5802
6188
  code: context.s.toString(),
5803
- map: sourceMap ? context.s.generateMap({
5804
- source: filename,
5805
- hires: true,
5806
- includeContent: true
5807
- }).toString() : void 0
6189
+ map: sourceMap ? context.s.generateMap(filename) : void 0
5808
6190
  };
5809
6191
  }
5810
6192
  /**
@@ -5867,6 +6249,11 @@ function compile(code, options = {}) {
5867
6249
  current = result.code;
5868
6250
  if (result.map !== void 0) maps.push(result.map);
5869
6251
  }
6252
+ const tidied = options.tidy ?? true ? runPass(parsedCurrent(), filename, resolved, sourceMap, tidyJSX, void 0) : void 0;
6253
+ if (tidied) {
6254
+ current = tidied.code;
6255
+ if (tidied.map !== void 0) maps.push(tidied.map);
6256
+ }
5870
6257
  }
5871
6258
  const report = skipped ? { skipped } : {};
5872
6259
  if (current === start) return {
@@ -5902,4 +6289,4 @@ function readModuleConstants(code, options = {}) {
5902
6289
  //#endregion
5903
6290
  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 };
5904
6291
 
5905
- //# sourceMappingURL=compile-DptOANJi.mjs.map
6292
+ //# sourceMappingURL=compile-D2f8eXFk.mjs.map