brumate 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +43 -72
  2. package/dist/boot-DN1ZU8Hg.d.ts +37 -0
  3. package/dist/cli.js +2 -2
  4. package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
  5. package/dist/client-routes-DakuM32C.js +94 -0
  6. package/dist/client-routes-DakuM32C.js.map +1 -0
  7. package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
  8. package/dist/cookies-Av5WFmcf.js.map +1 -0
  9. package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
  10. package/dist/devtools-BKjnHrnv.js.map +1 -0
  11. package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
  12. package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
  13. package/dist/{files-D_JUcSU5.js → files-DdT84mPy.js} +22 -3
  14. package/dist/{files-D_JUcSU5.js.map → files-DdT84mPy.js.map} +1 -1
  15. package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
  16. package/dist/html-DEeoepg3.js.map +1 -0
  17. package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
  18. package/dist/index.d.ts +65 -6
  19. package/dist/index.js +20 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/{inspect-CGCWfaEx.js → inspect-BPchdWbU.js} +887 -172
  22. package/dist/inspect-BPchdWbU.js.map +1 -0
  23. package/dist/loader-Dc9OwY5I.js +101 -0
  24. package/dist/loader-Dc9OwY5I.js.map +1 -0
  25. package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
  26. package/dist/navigate-CzLjnoPH.js.map +1 -0
  27. package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
  28. package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
  29. package/dist/rpc-9fSqL_YK.js.map +1 -0
  30. package/dist/runtime/client.d.ts +4 -4
  31. package/dist/runtime/client.js +599 -306
  32. package/dist/runtime/client.js.map +1 -1
  33. package/dist/runtime/devtools.d.ts +3 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/hot.js +9 -5
  37. package/dist/runtime/hot.js.map +1 -1
  38. package/dist/runtime/html.d.ts +2 -2
  39. package/dist/runtime/html.js +1 -1
  40. package/dist/runtime/loader.d.ts +12 -2
  41. package/dist/runtime/loader.js +3 -1
  42. package/dist/runtime/server.d.ts +4 -4
  43. package/dist/runtime/server.js +5 -5
  44. package/dist/runtime/signals.d.ts +2 -2
  45. package/dist/runtime/signals.js +5 -5
  46. package/dist/runtime/signals.js.map +1 -1
  47. package/dist/runtime/static-loader.d.ts +3 -0
  48. package/dist/runtime/static-loader.js +1 -0
  49. package/dist/runtime/testing.d.ts +21 -2
  50. package/dist/runtime/testing.js +83 -7
  51. package/dist/runtime/testing.js.map +1 -1
  52. package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
  53. package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
  54. package/dist/server-DZsgnPKS.js.map +1 -0
  55. package/dist/shared-CWYOd0H3.js +40 -0
  56. package/dist/shared-CWYOd0H3.js.map +1 -0
  57. package/dist/static-loader-BcFh4ebX.d.ts +11 -0
  58. package/dist/static-loader-ClNkHZGn.js +185 -0
  59. package/dist/static-loader-ClNkHZGn.js.map +1 -0
  60. package/dist/stream-bgNCMcaA.js +280 -0
  61. package/dist/stream-bgNCMcaA.js.map +1 -0
  62. package/dist/vite.d.ts +30 -5
  63. package/dist/vite.js +501 -62
  64. package/dist/vite.js.map +1 -1
  65. package/package.json +7 -2
  66. package/types.d.ts +5 -0
  67. package/dist/cookies-rgIAc8IE.js.map +0 -1
  68. package/dist/devtools-Bm8cS7hX.js.map +0 -1
  69. package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
  70. package/dist/html-CxWpXngy.js.map +0 -1
  71. package/dist/inspect-CGCWfaEx.js.map +0 -1
  72. package/dist/loader-BUhNqDHw.d.ts +0 -30
  73. package/dist/loader-py4qu6tQ.js +0 -215
  74. package/dist/loader-py4qu6tQ.js.map +0 -1
  75. package/dist/navigate-C5dP89YL.js.map +0 -1
  76. package/dist/rpc-B86KKjzx.js.map +0 -1
  77. package/dist/server-CX3JnPCs.js.map +0 -1
  78. package/dist/shared-BE_oBSDM.js +0 -176
  79. package/dist/shared-BE_oBSDM.js.map +0 -1
  80. package/dist/stream-cvhqOzfs.js +0 -145
  81. package/dist/stream-cvhqOzfs.js.map +0 -1
@@ -1,3 +1,4 @@
1
+ import { u as insertValue } from "./html-DEeoepg3.js";
1
2
  import { parseSync } from "oxc-parser";
2
3
  import { parse } from "postcss";
3
4
  import selectorParser from "postcss-selector-parser";
@@ -15,12 +16,14 @@ const MACROS = /* @__PURE__ */ new Set([
15
16
  "$untrack",
16
17
  "$produce",
17
18
  "$isPending",
18
- "$provide",
19
- "$context",
19
+ "$setContext",
20
+ "$getContext",
20
21
  "$id",
21
22
  "$title",
22
23
  "$action"
23
24
  ]);
25
+ /** Compile-time functions that have a new name, by old name. */
26
+ const RENAMED_MACROS = /* @__PURE__ */ new Map([["$provide", "$setContext"], ["$context", "$getContext"]]);
24
27
  /** True for `import … from 'brumate/signals'`, which the compiler removes. */
25
28
  function isMacroImport(statement) {
26
29
  return statement.type === "ImportDeclaration" && statement.source.value === "brumate/signals";
@@ -40,15 +43,26 @@ function walk(value, visit, seen = /* @__PURE__ */ new Set()) {
40
43
  * Reads the imports of `brumate/signals` in the file. A call of a renamed
41
44
  * import, such as `signal(0)` after `import { $signal as signal }`, gets the
42
45
  * name of the compile-time function, so the compiler sees `$signal(0)`.
43
- * Returns the compile-time functions that the file imports.
46
+ * Returns the compile-time functions that the file imports, and errors for
47
+ * imports of compile-time functions that have a new name.
44
48
  */
45
49
  function resolveMacros(file) {
46
50
  const aliases = /* @__PURE__ */ new Map();
51
+ const diagnostics = [];
47
52
  walk(file, (node) => {
48
53
  if (!isMacroImport(node)) return;
49
54
  for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") {
50
55
  const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
51
56
  aliases.set(specifier.local.name, imported);
57
+ const renamed = RENAMED_MACROS.get(imported);
58
+ if (renamed) diagnostics.push({
59
+ severity: "error",
60
+ message: `${imported} was renamed to ${renamed}. Import ${renamed} from '${SIGNALS_MODULE}'`,
61
+ range: {
62
+ start: specifier.start,
63
+ end: specifier.end
64
+ }
65
+ });
52
66
  }
53
67
  });
54
68
  if ([...aliases].some(([local, imported]) => local !== imported)) walk(file, (node) => {
@@ -57,22 +71,28 @@ function resolveMacros(file) {
57
71
  if (imported) node.callee.name = imported;
58
72
  }
59
73
  });
60
- return new Set(aliases.values());
74
+ return {
75
+ imported: new Set(aliases.values()),
76
+ diagnostics
77
+ };
61
78
  }
62
79
  /** Reports calls of compile-time functions that the file does not import. */
63
80
  function checkMacroImports(file, imported) {
64
81
  const missing = /* @__PURE__ */ new Map();
65
82
  walk(file, (node) => {
66
- if (node.type === "CallExpression" && node.callee.type === "Identifier" && MACROS.has(node.callee.name) && !imported.has(node.callee.name) && !missing.has(node.callee.name)) missing.set(node.callee.name, {
83
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && (MACROS.has(node.callee.name) || RENAMED_MACROS.has(node.callee.name)) && !imported.has(node.callee.name) && !missing.has(node.callee.name)) missing.set(node.callee.name, {
67
84
  start: node.start,
68
85
  end: node.end
69
86
  });
70
87
  });
71
- return [...missing].map(([name, range]) => ({
72
- severity: "error",
73
- message: `Import ${name} from '${SIGNALS_MODULE}'`,
74
- range
75
- }));
88
+ return [...missing].map(([name, range]) => {
89
+ const renamed = RENAMED_MACROS.get(name);
90
+ return {
91
+ severity: "error",
92
+ message: renamed ? `${name} was renamed to ${renamed}. Import ${renamed} from '${SIGNALS_MODULE}'` : `Import ${name} from '${SIGNALS_MODULE}'`,
93
+ range
94
+ };
95
+ });
76
96
  }
77
97
  //#endregion
78
98
  //#region src/model.ts
@@ -225,10 +245,10 @@ const REACTIVE = /* @__PURE__ */ new Set([
225
245
  ]);
226
246
  const COMPILE_TIME_FUNCTIONS = MACROS;
227
247
  const MISPLACED = {
228
- $provide: "Call $provide at the top level of a script",
248
+ $setContext: "Call $setContext at the top level of a script",
229
249
  $title: "Call $title at the top level of a script",
230
250
  $id: "Create an ID with \"const name = $id()\" at the top level of a script",
231
- $context: "Read a context with \"const name = $context(Context)\" at the top level of a script",
251
+ $getContext: "Read a context with \"const name = $getContext(Context)\" at the top level of a script",
232
252
  $props: "Call $props() as the value of a const in the component script",
233
253
  $signal: "Declare a signal with \"let name = $signal(value)\" at the top level of a script",
234
254
  $memo: "Declare a memo with \"const name = $memo(value)\" at the top level of a script",
@@ -318,8 +338,8 @@ var Analyzer = class {
318
338
  this.component = this.createScope("component", this.module);
319
339
  }
320
340
  run() {
321
- const imported = resolveMacros(this.file);
322
- this.diagnostics.push(...checkMacroImports(this.file, imported));
341
+ const { imported, diagnostics } = resolveMacros(this.file);
342
+ this.diagnostics.push(...diagnostics, ...checkMacroImports(this.file, imported));
323
343
  if (this.file.moduleScript) this.declareModuleScript(this.file.moduleScript.program);
324
344
  if (this.file.instanceScript) this.declareScript(this.file.instanceScript.program, this.component, true);
325
345
  for (const template of this.file.templates) this.declareTemplate(template, this.component);
@@ -502,7 +522,7 @@ var Analyzer = class {
502
522
  const call = statement.expression;
503
523
  if (call.arguments.length !== 1) this.report("error", "$title takes one argument, the title", call);
504
524
  else this.createSite("title", scope, call.arguments[0], "title");
505
- } else if (name === "$provide") this.declareProvide(statement.expression, scope);
525
+ } else if (name === "$setContext") this.declareProvide(statement.expression, scope);
506
526
  else if (name === "$effect" || name === "$client") this.declareEffect(statement.expression, name, scope);
507
527
  else this.createSite("setup", scope, statement, "setup");
508
528
  break;
@@ -548,12 +568,12 @@ var Analyzer = class {
548
568
  declaration.idIndex = [...scope.declarations.values()].filter((item) => item.idIndex !== void 0).length;
549
569
  return;
550
570
  }
551
- if (name === "$context") {
571
+ if (name === "$getContext") {
552
572
  if (kind !== "const" || id.type !== "Identifier") {
553
- this.report("error", "Read a context with \"const name = $context(Context)\"", declarator);
573
+ this.report("error", "Read a context with \"const name = $getContext(Context)\"", declarator);
554
574
  return;
555
575
  }
556
- if (call.arguments.length !== 1) this.report("error", "$context takes one argument, the context", call);
576
+ if (call.arguments.length !== 1) this.report("error", "$getContext takes one argument, the context", call);
557
577
  this.addDeclaration(scope, id.name, "context", id);
558
578
  const argument = call.arguments[0];
559
579
  if (argument) this.createSite("setup", scope, argument, `context ${id.name}`);
@@ -583,8 +603,11 @@ var Analyzer = class {
583
603
  if (call.arguments.length > 1) this.report("error", `${name} takes one argument`, call);
584
604
  const argument = call.arguments[0];
585
605
  if (name === "$signal") {
586
- this.addDeclaration(scope, id.name, "signal", id);
587
- if (argument) this.createSite("setup", scope, argument, `signal ${id.name}`);
606
+ const declaration = this.addDeclaration(scope, id.name, "signal", id);
607
+ if (argument) {
608
+ declaration.init = argument;
609
+ this.createSite("setup", scope, argument, `signal ${id.name}`);
610
+ }
588
611
  return;
589
612
  }
590
613
  const declaration = this.addDeclaration(scope, id.name, "memo", id);
@@ -635,7 +658,7 @@ var Analyzer = class {
635
658
  * Functions in a provided value run in the browser, where a component that
636
659
  * reads the context calls them. Each one is a client root, as a function
637
660
  * prop is: the value itself, or the value of a key of an object, such as
638
- * `toggle` in `$provide(Theme, { theme, toggle })`.
661
+ * `toggle` in `$setContext(Theme, { theme, toggle })`.
639
662
  */
640
663
  addProvidedFunctions() {
641
664
  for (const site of this.sites.filter((item) => item.kind === "provide")) {
@@ -647,7 +670,7 @@ var Analyzer = class {
647
670
  declareProvide(call, scope) {
648
671
  const [context, value] = call.arguments;
649
672
  if (!context || !value || call.arguments.length !== 2) {
650
- this.report("error", "$provide takes two arguments, the context and the value", call);
673
+ this.report("error", "$setContext takes two arguments, the context and the value", call);
651
674
  return;
652
675
  }
653
676
  this.createSite("provide", scope, value, "provide", { extra: [context] });
@@ -733,31 +756,34 @@ var Analyzer = class {
733
756
  visitAttributes(node, scope) {
734
757
  const isComponent = node.kind === "component";
735
758
  const tag = node.kind === "element" ? node.tag : node.kind === "component" ? node.name : "dynamic";
736
- for (const attribute of node.attributes) switch (attribute.kind) {
737
- case "static":
738
- case "prefetch": break;
739
- case "value":
740
- this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.value, `${isComponent ? "prop" : "attribute"} ${tag}.${attribute.name}`, { owner: node });
741
- break;
742
- case "event":
743
- this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
744
- owner: node,
745
- event: isComponent ? void 0 : attribute
746
- });
747
- break;
748
- case "ref":
749
- if (node.kind === "element") this.refs.push({
750
- attribute,
751
- element: node,
752
- scope
753
- });
754
- break;
755
- case "spread":
756
- this.createExpressionSite("spread", scope, attribute.value, `spread ${tag}`, { owner: node });
757
- break;
758
- case "computed":
759
- this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.name, `computed ${tag}`, { owner: node });
760
- if (attribute.value !== true) this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.value, `computed ${tag}`, { owner: node });
759
+ for (const attribute of node.attributes) {
760
+ if (!isComponent && (attribute.kind === "static" || attribute.kind === "value") && attribute.name.startsWith("b-")) this.report("error", `"${attribute.name}" is reserved. Brumate writes the attributes that start with "b-"`, attribute);
761
+ switch (attribute.kind) {
762
+ case "static":
763
+ case "prefetch": break;
764
+ case "value":
765
+ this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.value, `${isComponent ? "prop" : "attribute"} ${tag}.${attribute.name}`, { owner: node });
766
+ break;
767
+ case "event":
768
+ this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
769
+ owner: node,
770
+ event: isComponent ? void 0 : attribute
771
+ });
772
+ break;
773
+ case "ref":
774
+ if (node.kind === "element") this.refs.push({
775
+ attribute,
776
+ element: node,
777
+ scope
778
+ });
779
+ break;
780
+ case "spread":
781
+ this.createExpressionSite("spread", scope, attribute.value, `spread ${tag}`, { owner: node });
782
+ break;
783
+ case "computed":
784
+ this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.name, `computed ${tag}`, { owner: node });
785
+ if (attribute.value !== true) this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.value, `computed ${tag}`, { owner: node });
786
+ }
761
787
  }
762
788
  }
763
789
  header(block, scope, expression, label) {
@@ -820,7 +846,12 @@ var Analyzer = class {
820
846
  if (block.target) this.header(block, scope, block.target, "portal");
821
847
  this.visitBody(block.body, scope, block);
822
848
  break;
823
- case "client": this.visitBody(block.body, scope, block);
849
+ case "client":
850
+ this.visitBody(block.body, scope, block);
851
+ break;
852
+ case "offscreen":
853
+ this.header(block, scope, block.visible, "offscreen");
854
+ this.visitBody(block.body, scope, block);
824
855
  }
825
856
  }
826
857
  declareLoopVariables(block, body) {
@@ -1606,6 +1637,8 @@ const BLOCK_KEYWORDS = /* @__PURE__ */ new Set([
1606
1637
  "portal",
1607
1638
  "head",
1608
1639
  "client",
1640
+ "offscreen",
1641
+ "defer",
1609
1642
  "template"
1610
1643
  ]);
1611
1644
  const BRANCH_KEYWORDS = /* @__PURE__ */ new Set([
@@ -2335,6 +2368,19 @@ var Parser = class {
2335
2368
  body: this.parseBody("client")
2336
2369
  };
2337
2370
  }
2371
+ case "offscreen": {
2372
+ const header = this.parseHeader("offscreen", true);
2373
+ const visible = this.expression(header.start, header.end);
2374
+ const body = this.parseBody("offscreen");
2375
+ return {
2376
+ kind: "offscreen",
2377
+ start,
2378
+ end: this.pos,
2379
+ visible,
2380
+ body
2381
+ };
2382
+ }
2383
+ case "defer": return this.fail("#defer is reserved for a future block", start);
2338
2384
  default: return this.fail(`Unknown block #${keyword}`, start);
2339
2385
  }
2340
2386
  }
@@ -2460,7 +2506,8 @@ function childrenOf(node) {
2460
2506
  case "key":
2461
2507
  case "portal":
2462
2508
  case "head":
2463
- case "client": return node.body.children;
2509
+ case "client":
2510
+ case "offscreen": return node.body.children;
2464
2511
  default: return [];
2465
2512
  }
2466
2513
  }
@@ -3499,8 +3546,9 @@ function promiseName(name) {
3499
3546
  * `$signal(x)` and `$memo(x)` become `(x)`, `$props()` becomes `$$props`
3500
3547
  * and `$untrack(x)` becomes `(x)`. On the server, a memo is renamed to
3501
3548
  * `$$p_<name>`, because it can hold a promise that is awaited where it is read.
3549
+ * The memos in `inline` are plain values on the server too.
3502
3550
  */
3503
- function addValueEdits(patch, file, sites, mode = "server") {
3551
+ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE__ */ new Set()) {
3504
3552
  const sitesByNode = /* @__PURE__ */ new Map();
3505
3553
  for (const site of sites) sitesByNode.set(site.node, site);
3506
3554
  const visit = (node) => {
@@ -3531,10 +3579,10 @@ function addValueEdits(patch, file, sites, mode = "server") {
3531
3579
  return;
3532
3580
  }
3533
3581
  const site = name === "$memo" || name === "$optimistic" ? sitesByNode.get(argument) : void 0;
3534
- const declaration = site?.declaration;
3582
+ const declaration = site?.declaration && !inline.has(site.declaration) ? site.declaration : void 0;
3535
3583
  if (declaration && mode === "server") patch.replace(declaration.range.start, declaration.range.end, promiseName(declaration.name));
3536
3584
  if (declaration && mode === "server") {
3537
- for (const read of site.reads) if (read.range.start !== read.range.end && read.declaration !== declaration && (read.declaration.kind === "memo" || read.declaration.kind === "async-memo")) patch.replace(read.range.start, read.range.end, `$$b.read(${promiseName(read.declaration.name)})`);
3585
+ for (const read of site.reads) if (read.range.start !== read.range.end && read.declaration !== declaration && !inline.has(read.declaration) && (read.declaration.kind === "memo" || read.declaration.kind === "async-memo")) patch.replace(read.range.start, read.range.end, `$$b.read(${promiseName(read.declaration.name)})`);
3538
3586
  patch.replace(node.start, argument.start, site.awaits ? "$$b.memo(async () => (" : "$$b.memo(() => (");
3539
3587
  patch.replace(argument.end, node.end, "), $$ctx)");
3540
3588
  } else if (site?.awaits) {
@@ -3593,8 +3641,8 @@ const SHARED_QUERY = "?brumate-shared";
3593
3641
  const UNSHARED = /* @__PURE__ */ new Set([
3594
3642
  "$isPending",
3595
3643
  "$id",
3596
- "$context",
3597
- "$provide",
3644
+ "$getContext",
3645
+ "$setContext",
3598
3646
  "$title",
3599
3647
  "$action",
3600
3648
  "$props"
@@ -3746,8 +3794,28 @@ function generateShared(module) {
3746
3794
  }
3747
3795
  //#endregion
3748
3796
  //#region src/css.ts
3749
- /** Adds the scope attribute to every compound selector, except inside `:global(…)`. */
3750
- const scopeSelector = (attribute) => selectorParser((selectors) => {
3797
+ /**
3798
+ * True if a scoped selector could match an element, so the element needs the
3799
+ * scope attribute. `tag` is undefined when it is not known at compile time,
3800
+ * and `classes` is undefined when the element can have classes that are not
3801
+ * known.
3802
+ */
3803
+ function needsScope(targets, tag, classes) {
3804
+ const lower = tag?.toLowerCase();
3805
+ return targets.some((target) => (target.tag === void 0 || lower === void 0 || target.tag === lower) && (classes === void 0 || target.classes.every((name) => classes.includes(name))));
3806
+ }
3807
+ /** What an element needs to match a compound. Selectors inside pseudo-classes are not read. */
3808
+ function scopeTarget(compound) {
3809
+ const target = { classes: [] };
3810
+ for (const node of compound) if (node.type === "tag") target.tag = node.value.toLowerCase();
3811
+ else if (node.type === "class") target.classes.push(node.value);
3812
+ return target;
3813
+ }
3814
+ /**
3815
+ * Adds the scope attribute to every compound selector, except inside
3816
+ * `:global(…)`. Each scoped compound goes into `targets`.
3817
+ */
3818
+ const scopeSelector = (attribute, targets) => selectorParser((selectors) => {
3751
3819
  selectors.each((selector) => {
3752
3820
  const compounds = [[]];
3753
3821
  selector.each((node) => {
@@ -3762,6 +3830,7 @@ const scopeSelector = (attribute) => selectorParser((selectors) => {
3762
3830
  continue;
3763
3831
  }
3764
3832
  if (compound.length === 0) continue;
3833
+ targets.push(scopeTarget(compound));
3765
3834
  const last = compound.findLast((node) => !(node.type === "pseudo" && node.value.startsWith("::")));
3766
3835
  const scope = selectorParser.attribute({
3767
3836
  attribute,
@@ -3773,13 +3842,56 @@ const scopeSelector = (attribute) => selectorParser((selectors) => {
3773
3842
  }
3774
3843
  });
3775
3844
  });
3776
- function scopeRules(root, attribute) {
3777
- const processor = scopeSelector(attribute);
3845
+ function scopeRules(root, attribute, targets) {
3846
+ const processor = scopeSelector(attribute, targets);
3778
3847
  root.walkRules((rule) => {
3779
3848
  if (rule.parent?.type === "atrule" && /keyframes$/i.test(rule.parent.name)) return;
3780
3849
  rule.selector = processor.processSync(rule.selector);
3781
3850
  });
3782
3851
  }
3852
+ /** Line breaks in a selector, value or at-rule are whitespace, because strings cannot hold them. */
3853
+ function collapse(text) {
3854
+ return text.replace(/\s*\n\s*/g, " ").trim();
3855
+ }
3856
+ /**
3857
+ * Removes the comments and the whitespace that CSS does not need, for a
3858
+ * build. Comments that start with `/*!`, such as licenses, stay.
3859
+ */
3860
+ function minifyCSS(css) {
3861
+ if (!css) return css;
3862
+ const root = parse(css);
3863
+ root.raws.after = "";
3864
+ root.raws.semicolon = false;
3865
+ root.walk((node) => {
3866
+ node.raws.before = "";
3867
+ switch (node.type) {
3868
+ case "comment":
3869
+ if (!node.text.startsWith("!")) node.remove();
3870
+ break;
3871
+ case "decl":
3872
+ node.raws.between = ":";
3873
+ delete node.raws.value;
3874
+ node.value = collapse(node.value);
3875
+ if (node.important) node.raws.important = "!important";
3876
+ break;
3877
+ case "rule":
3878
+ delete node.raws.selector;
3879
+ node.selector = collapse(node.selector);
3880
+ node.raws.between = "";
3881
+ node.raws.after = "";
3882
+ node.raws.semicolon = false;
3883
+ break;
3884
+ case "atrule":
3885
+ delete node.raws.params;
3886
+ node.params = collapse(node.params);
3887
+ node.raws.afterName = node.params ? " " : "";
3888
+ node.raws.between = "";
3889
+ node.raws.after = "";
3890
+ node.raws.semicolon = false;
3891
+ }
3892
+ });
3893
+ return root.toString();
3894
+ }
3783
3895
  /**
3784
3896
  * Loads a style preprocessor from the project, or from beside this package.
3785
3897
  * Returns undefined when it is not installed.
@@ -3831,6 +3943,7 @@ function compileStyles(file, scope, filePath) {
3831
3943
  const variables = [];
3832
3944
  const dependencies = [];
3833
3945
  const parts = [];
3946
+ const targets = [];
3834
3947
  for (const style of file.styles) {
3835
3948
  const contentStart = file.source.indexOf(style.content, style.start);
3836
3949
  let content = "";
@@ -3857,7 +3970,7 @@ function compileStyles(file, scope, filePath) {
3857
3970
  content += style.content.slice(position);
3858
3971
  try {
3859
3972
  const root = parse(style.lang === "css" ? content : preprocess(style.lang, content, filePath, dependencies));
3860
- scopeRules(root, attribute);
3973
+ scopeRules(root, attribute, targets);
3861
3974
  parts.push(root.toString().trim());
3862
3975
  } catch (error) {
3863
3976
  diagnostics.push({
@@ -3875,11 +3988,57 @@ function compileStyles(file, scope, filePath) {
3875
3988
  attribute,
3876
3989
  variables,
3877
3990
  diagnostics,
3878
- dependencies
3991
+ dependencies,
3992
+ targets
3879
3993
  };
3880
3994
  }
3881
3995
  //#endregion
3882
3996
  //#region src/plan.ts
3997
+ /**
3998
+ * Elements that the HTML parser can end before their end tag, or whose
3999
+ * content it moves out, when they hold some other elements: a `<p>` ends at
4000
+ * a `<div>`, and a `<table>` moves out content that is not part of a table.
4001
+ */
4002
+ const UNSTABLE = /* @__PURE__ */ new Set([
4003
+ "p",
4004
+ "h1",
4005
+ "h2",
4006
+ "h3",
4007
+ "h4",
4008
+ "h5",
4009
+ "h6",
4010
+ "dt",
4011
+ "dd",
4012
+ "option",
4013
+ "optgroup",
4014
+ "select",
4015
+ "rb",
4016
+ "rp",
4017
+ "rt",
4018
+ "rtc",
4019
+ "table",
4020
+ "caption",
4021
+ "colgroup",
4022
+ "thead",
4023
+ "tbody",
4024
+ "tfoot",
4025
+ "template"
4026
+ ]);
4027
+ /**
4028
+ * True if the browser keeps the element's content inside it, whatever that
4029
+ * content renders. Then an element inside it can find it with `closest`, and
4030
+ * it can stand for a list item. A `<tr>` is one when it holds only cells.
4031
+ */
4032
+ function isStable(node) {
4033
+ const tag = node.tag.toLowerCase();
4034
+ if (tag === "tr") return node.children.every((child) => child.kind === "text" ? cleanText(child.value).trim() === "" : child.kind === "element" && ["td", "th"].includes(child.tag.toLowerCase()));
4035
+ return !UNSTABLE.has(tag);
4036
+ }
4037
+ /**
4038
+ * Elements whose content is text, where a comment would be text too. The
4039
+ * parser reads `<script>` and `<style>` itself, so only these reach markup.
4040
+ */
4041
+ const RAW_TEXT = /* @__PURE__ */ new Set(["textarea", "title"]);
3883
4042
  const NO_SLOT = /* @__PURE__ */ new Set([
3884
4043
  "import",
3885
4044
  "module",
@@ -3984,15 +4143,20 @@ function createPlan(file, graph, path, hideNames = false) {
3984
4143
  for (const declaration of model.declarations) for (const ref of declaration.refs) refTargets.set(ref.attribute, declaration);
3985
4144
  const slotted = /* @__PURE__ */ new Set();
3986
4145
  for (const plan of scopes.values()) for (const declaration of plan.slots) slotted.add(declaration);
3987
- const visitBody = (body) => {
4146
+ const contents = /* @__PURE__ */ new Set();
4147
+ const textContents = /* @__PURE__ */ new Set();
4148
+ const diagnostics = [];
4149
+ const elementItems = /* @__PURE__ */ new Set();
4150
+ const itemRoots = /* @__PURE__ */ new Set();
4151
+ const visitBody = (body, outer) => {
3988
4152
  const scope = bodyScopes.get(body);
3989
4153
  for (const template of body.templates) visitBody(template.body);
3990
- visitNodes(body.children, scope);
4154
+ visitNodes(body.children, scope, outer);
3991
4155
  };
3992
- const visitNodes = (nodes, scope) => {
3993
- for (const node of nodes) visitNode(node, scope);
4156
+ const visitNodes = (nodes, scope, outer) => {
4157
+ for (const node of nodes) visitNode(node, scope, outer);
3994
4158
  };
3995
- const visitNode = (node, scope) => {
4159
+ const visitNode = (node, scope, outer) => {
3996
4160
  switch (node.kind) {
3997
4161
  case "text": return;
3998
4162
  case "insert": {
@@ -4003,11 +4167,25 @@ function createPlan(file, graph, path, hideNames = false) {
4003
4167
  case "element":
4004
4168
  case "dynamic": {
4005
4169
  const sites = sitesByNode.get(node) ?? [];
4006
- if (node.kind === "element" && node.attributes.some((attribute) => {
4170
+ const hasRef = node.kind === "element" && node.attributes.some((attribute) => {
4007
4171
  const target = attribute.kind === "ref" ? refTargets.get(attribute) : void 0;
4008
4172
  return target !== void 0 && slotted.has(target);
4009
- }) || sites.some((site) => site.kind === "event" || isLiveSite(site))) anchor(scope, node);
4010
- visitNodes(node.children, scope);
4173
+ });
4174
+ const content = node.kind === "element" ? liveContent(node) : void 0;
4175
+ const events = sites.some((site) => site.kind === "event");
4176
+ const implied = node.kind === "element" && outer === scope;
4177
+ if (hasRef || content || itemRoots.has(node) || sites.some((site) => isLiveSite(site)) || events && !implied) anchor(scope, node);
4178
+ if (content) {
4179
+ anchors.set(content, anchors.get(node));
4180
+ contents.add(content);
4181
+ if (node.kind === "element" && RAW_TEXT.has(node.tag.toLowerCase())) textContents.add(content);
4182
+ return;
4183
+ }
4184
+ let inner = outer;
4185
+ if (node.kind === "dynamic") inner = void 0;
4186
+ else if (anchors.has(node)) inner = isStable(node) ? scope : void 0;
4187
+ visitNodes(node.children, scope, inner);
4188
+ if (node.kind === "element" && RAW_TEXT.has(node.tag.toLowerCase())) checkText(node);
4011
4189
  return;
4012
4190
  }
4013
4191
  case "component":
@@ -4015,24 +4193,65 @@ function createPlan(file, graph, path, hideNames = false) {
4015
4193
  visitNodes(node.children, scope);
4016
4194
  return;
4017
4195
  case "fragment":
4018
- visitNodes(node.children, scope);
4196
+ visitNodes(node.children, scope, outer);
4019
4197
  return;
4020
4198
  case "listener":
4021
4199
  anchor(scope, node);
4022
4200
  return;
4023
- default: visitBlock(node, scope);
4201
+ default: visitBlock(node, scope, outer);
4024
4202
  }
4025
4203
  };
4026
- const visitBlock = (block, scope) => {
4204
+ /**
4205
+ * Reports live markup inside an element whose content is text. Its markers
4206
+ * would be text, so the client can only update a value that is the whole content.
4207
+ */
4208
+ const checkText = (element) => {
4209
+ const found = firstAnchored(element.children, anchors);
4210
+ if (found) {
4211
+ const tag = element.tag.toLowerCase();
4212
+ diagnostics.push({
4213
+ severity: "error",
4214
+ message: `A value that changes in <${tag}> must be its whole content, such as <${tag}>{\`Count \${count}\`}</${tag}>`,
4215
+ range: {
4216
+ start: found.start,
4217
+ end: found.end
4218
+ }
4219
+ });
4220
+ }
4221
+ };
4222
+ /** The live insert that is the whole content of an element, if any. */
4223
+ const liveContent = (node) => {
4224
+ const [only, ...rest] = node.children.filter((child) => child.kind !== "text" || cleanText(child.value) !== "");
4225
+ if (rest.length > 0 || only?.kind !== "insert") return;
4226
+ const site = insertSites.get(only.expression.ast);
4227
+ return site && isLiveSite(site) ? only : void 0;
4228
+ };
4229
+ const visitBlock = (block, scope, outer) => {
4027
4230
  const portalTarget = block.kind === "portal" && block.target !== void 0;
4028
4231
  const live = block.kind === "client" || portalTarget || block.kind === "try" && resetUsed(model, block, graph.reached) || (headerSites.get(block) ?? []).some((site) => isLiveSite(site));
4029
4232
  if (live) anchor(scope, block);
4233
+ if (live && block.kind === "offscreen") scopes.get(bodyScopes.get(block.body)).needsId = true;
4030
4234
  if (block.kind === "portal" || block.kind === "head") scopes.get(bodyScopes.get(block.body)).needsId = true;
4235
+ const inner = block.kind === "portal" || block.kind === "head" ? void 0 : outer;
4031
4236
  for (const body of blockBodies(block)) {
4032
- if (live && (block.kind === "for" || block.kind === "repeat") && body === block.body) scopes.get(bodyScopes.get(body)).needsId = true;
4033
- visitBody(body);
4237
+ if (live && (block.kind === "for" || block.kind === "repeat") && body === block.body) {
4238
+ scopes.get(bodyScopes.get(body)).needsId = true;
4239
+ const root = singleRoot(body);
4240
+ if (root) {
4241
+ itemRoots.add(root);
4242
+ elementItems.add(block);
4243
+ }
4244
+ }
4245
+ visitBody(body, inner);
4034
4246
  }
4035
4247
  };
4248
+ /** The element that is the whole markup of a body, when nothing else renders next to it. */
4249
+ const singleRoot = (body) => {
4250
+ const scope = bodyScopes.get(body);
4251
+ if (body.templates.length > 0 || model.sites.some((site) => site.kind === "client" && site.scope === scope)) return;
4252
+ const [only, ...rest] = body.children.filter((child) => child.kind !== "text" || cleanText(child.value) !== "");
4253
+ return rest.length === 0 && only?.kind === "element" && isStable(only) ? only : void 0;
4254
+ };
4036
4255
  for (const template of file.templates) visitBody(template.body);
4037
4256
  visitNodes(file.children, model.component);
4038
4257
  for (const plan of scopes.values()) {
@@ -4051,10 +4270,34 @@ function createPlan(file, graph, path, hideNames = false) {
4051
4270
  scopes,
4052
4271
  bodyScopes,
4053
4272
  anchors,
4273
+ contents,
4274
+ textContents,
4275
+ elementItems,
4054
4276
  symbols,
4055
- clientSites
4277
+ clientSites,
4278
+ diagnostics
4056
4279
  };
4057
4280
  }
4281
+ /** The first node in the markup that has an anchor, at any depth. */
4282
+ function firstAnchored(nodes, anchors) {
4283
+ for (const node of nodes) {
4284
+ const found = anchors.has(node) ? node : firstAnchored(childNodes(node), anchors);
4285
+ if (found) return found;
4286
+ }
4287
+ }
4288
+ /** Returns the markup inside a node, with the bodies of a block. */
4289
+ function childNodes(node) {
4290
+ switch (node.kind) {
4291
+ case "text":
4292
+ case "insert":
4293
+ case "listener": return [];
4294
+ case "element":
4295
+ case "component":
4296
+ case "dynamic":
4297
+ case "fragment": return node.children;
4298
+ default: return blockBodies(node).flatMap((body) => body.children);
4299
+ }
4300
+ }
4058
4301
  /** Returns the bodies of a block, in source order. */
4059
4302
  function blockBodies(block) {
4060
4303
  switch (block.kind) {
@@ -4144,6 +4387,117 @@ function awaitedMemos(plan, body, blocking) {
4144
4387
  }
4145
4388
  return [...result];
4146
4389
  }
4390
+ /** Expressions that run code the compiler cannot see, or that a memo should not hold. */
4391
+ const UNSAFE_NODES = /* @__PURE__ */ new Set([
4392
+ "CallExpression",
4393
+ "NewExpression",
4394
+ "TaggedTemplateExpression",
4395
+ "AwaitExpression",
4396
+ "YieldExpression",
4397
+ "ImportExpression",
4398
+ "AssignmentExpression",
4399
+ "UpdateExpression",
4400
+ "FunctionExpression",
4401
+ "ArrowFunctionExpression",
4402
+ "ClassExpression"
4403
+ ]);
4404
+ /**
4405
+ * True if an expression always gives a primitive, so it is never a promise
4406
+ * or an async iterable. A name is a primitive when `plain` says that it reads
4407
+ * a declaration that holds one.
4408
+ */
4409
+ function isPrimitive(node, plain = () => false) {
4410
+ switch (node.type) {
4411
+ case "Identifier": return plain(node);
4412
+ case "Literal": return !("regex" in node && node.regex);
4413
+ case "TemplateLiteral":
4414
+ case "BinaryExpression":
4415
+ case "UnaryExpression": return true;
4416
+ case "LogicalExpression": return isPrimitive(node.left, plain) && isPrimitive(node.right, plain);
4417
+ case "ConditionalExpression": return isPrimitive(node.consequent, plain) && isPrimitive(node.alternate, plain);
4418
+ case "TSAsExpression":
4419
+ case "TSSatisfiesExpression":
4420
+ case "TSNonNullExpression": return isPrimitive(node.expression, plain);
4421
+ default: return false;
4422
+ }
4423
+ }
4424
+ /** True if an expression calls no code and, unless `members`, reads no property. */
4425
+ function isSafe(node, members) {
4426
+ if (UNSAFE_NODES.has(node.type)) return false;
4427
+ if (!members && (node.type === "MemberExpression" || node.type === "ChainExpression")) return false;
4428
+ for (const [, child] of children(node)) if (!isSafe(child, members)) return false;
4429
+ return true;
4430
+ }
4431
+ /** True if a name in the code of a site reads a declaration that `plain` accepts. */
4432
+ function readsPlain(site, name, plain) {
4433
+ return site?.reads.some((read) => read.range.start === name.start && read.range.end === name.end && plain(read.declaration)) ?? false;
4434
+ }
4435
+ const ARITHMETIC_ASSIGNMENTS = /* @__PURE__ */ new Set([
4436
+ "+=",
4437
+ "-=",
4438
+ "*=",
4439
+ "/=",
4440
+ "%=",
4441
+ "**=",
4442
+ "<<=",
4443
+ ">>=",
4444
+ ">>>=",
4445
+ "&=",
4446
+ "|=",
4447
+ "^="
4448
+ ]);
4449
+ /** Returns the assignment or update of a site whose target is at `at`. */
4450
+ function writeAt(node, at) {
4451
+ if (node.type === "AssignmentExpression" && node.left.type === "Identifier" && node.left.start === at || node.type === "UpdateExpression" && node.argument.type === "Identifier" && node.argument.start === at) return node;
4452
+ for (const [, child] of children(node)) {
4453
+ const found = writeAt(child, at);
4454
+ if (found) return found;
4455
+ }
4456
+ }
4457
+ /**
4458
+ * Returns the memos and signals that always hold a primitive on the server,
4459
+ * so the server reads them as plain values.
4460
+ *
4461
+ * - A memo gives a primitive and calls nothing, so it is never a promise and
4462
+ * needs no render context. Each memo that it reads is one too, so no read
4463
+ * waits for a load. A memo that the server would not compute where it is
4464
+ * declared reads no property, because computing it early must not throw.
4465
+ * - A signal starts with a primitive, and each write gives a primitive, such
4466
+ * as `count++`. A signal that an element ref sets is left out.
4467
+ */
4468
+ function plainValues(plan, blocking) {
4469
+ const result = /* @__PURE__ */ new Set();
4470
+ const visiting = /* @__PURE__ */ new Set();
4471
+ const check = (declaration) => {
4472
+ if (result.has(declaration)) return true;
4473
+ if (visiting.has(declaration)) return false;
4474
+ visiting.add(declaration);
4475
+ const plain = declaration.kind === "signal" ? isPlainSignal(declaration) : isPlainMemo(declaration);
4476
+ visiting.delete(declaration);
4477
+ if (plain) result.add(declaration);
4478
+ return plain;
4479
+ };
4480
+ const isPlainMemo = (declaration) => {
4481
+ const site = declaration.site;
4482
+ return declaration.kind === "memo" && !declaration.writable && !declaration.optimistic && site !== void 0 && isPrimitive(site.node, (name) => readsPlain(site, name, check)) && isSafe(site.node, blocking.has(declaration)) && site.reads.every((read) => !isMemo(read.declaration) || check(read.declaration));
4483
+ };
4484
+ const isPlainSignal = (declaration) => {
4485
+ if (declaration.refs.length > 0) return false;
4486
+ const init = declaration.init;
4487
+ if (init) {
4488
+ const site = plan.graph.model.sites.find((item) => item.node === init);
4489
+ if (!isPrimitive(init, (name) => readsPlain(site, name, check))) return false;
4490
+ }
4491
+ return declaration.writes.every((write) => {
4492
+ const node = writeAt(write.site.node, write.range.start);
4493
+ if (node?.type === "UpdateExpression") return true;
4494
+ if (node?.type !== "AssignmentExpression") return false;
4495
+ return ARITHMETIC_ASSIGNMENTS.has(node.operator) || isPrimitive(node.right, (name) => readsPlain(write.site, name, check));
4496
+ });
4497
+ };
4498
+ for (const declaration of plan.graph.model.declarations) check(declaration);
4499
+ return result;
4500
+ }
4147
4501
  //#endregion
4148
4502
  //#region src/codegen/markup.ts
4149
4503
  const VOID_ELEMENTS = /* @__PURE__ */ new Set([
@@ -4167,14 +4521,36 @@ const TYPE_DECLARATIONS = /* @__PURE__ */ new Set([
4167
4521
  "TSDeclareFunction",
4168
4522
  "TSModuleDeclaration"
4169
4523
  ]);
4170
- /** The name of the compile-time function that a declarator calls, for `$context` and `$id`. */
4524
+ /** The name of the compile-time function that a declarator calls, for `$getContext` and `$id`. */
4171
4525
  function specialCall(declarator) {
4172
4526
  const init = declarator.init;
4173
4527
  if (init?.type !== "CallExpression" || init.callee.type !== "Identifier") return;
4174
4528
  const name = init.callee.name;
4175
- return name === "$context" || name === "$id" ? name : void 0;
4529
+ return name === "$getContext" || name === "$id" ? name : void 0;
4176
4530
  }
4177
4531
  /** Writes code that renders markup to an HTML string, on the server or on the client. */
4532
+ /** The exports of the core that do on the client what the server's render context does. */
4533
+ const CLIENT_HELPERS = {
4534
+ scope: "createScope",
4535
+ slots: "setSlots",
4536
+ item: "setItem",
4537
+ element: "elementAt",
4538
+ id: "makeId",
4539
+ own: "setOwner",
4540
+ provide: "provideValue",
4541
+ consume: "consumeContext",
4542
+ head: "addHead",
4543
+ portal: "addPortal",
4544
+ style: "addStyle",
4545
+ fn: "handlerProp",
4546
+ after: "afterInsert",
4547
+ title: "title"
4548
+ };
4549
+ /** The markup of an inserted literal, such as `{'<b>'}`, or undefined for other code. */
4550
+ function literalText(node) {
4551
+ if (node.type === "Literal") return "regex" in node && node.regex ? void 0 : insertValue(node.value);
4552
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return insertValue(node.quasis[0].value.cooked);
4553
+ }
4178
4554
  var Emitter = class {
4179
4555
  lines = [];
4180
4556
  file;
@@ -4185,8 +4561,12 @@ var Emitter = class {
4185
4561
  refTargets = /* @__PURE__ */ new Map();
4186
4562
  wait;
4187
4563
  async;
4564
+ /** The render context as an argument, which the client's helpers do not take. */
4565
+ ctxArgument;
4188
4566
  /** Async memos that the server awaits where they are declared. */
4189
4567
  blocking;
4568
+ /** Memos and signals that hold a primitive on the server, so it awaits none of them. */
4569
+ inline;
4190
4570
  parts = [];
4191
4571
  depth = 0;
4192
4572
  /** How many of this component's elements contain the current node. */
@@ -4199,7 +4579,9 @@ var Emitter = class {
4199
4579
  this.options = options;
4200
4580
  this.wait = options.mode === "server" ? "await " : "";
4201
4581
  this.async = options.mode === "server" ? "async " : "";
4582
+ this.ctxArgument = options.mode === "server" ? "$$ctx" : "undefined";
4202
4583
  this.blocking = blockingMemos(plan);
4584
+ this.inline = options.mode === "server" ? plainValues(plan, this.blocking) : /* @__PURE__ */ new Set();
4203
4585
  for (const site of plan.graph.model.sites) this.sitesByNode.set(site.node, site);
4204
4586
  for (const declaration of plan.graph.model.declarations) for (const ref of declaration.refs) this.refTargets.set(ref.attribute, declaration);
4205
4587
  }
@@ -4239,6 +4621,19 @@ var Emitter = class {
4239
4621
  const value = parts.map((part) => "static" in part ? JSON.stringify(part.static) : part.code).join(" + ");
4240
4622
  this.lines.push(`${" ".repeat(this.depth)}$$html += ${value};`);
4241
4623
  }
4624
+ /**
4625
+ * The value of a runtime call that returns a string, or a promise when it
4626
+ * is not ready. The server awaits only a promise, because most values are
4627
+ * ready and each await pauses the render. `$$t` is a variable of the
4628
+ * module. Nothing runs between its write and its read.
4629
+ */
4630
+ ready(call) {
4631
+ return this.options.mode === "server" ? `(typeof ($$t = ${call}) === 'string' ? $$t : await $$t)` : call;
4632
+ }
4633
+ /** The value of a memo, which the server awaits only when it is still loading. */
4634
+ memoValue(name) {
4635
+ return `(($$t = $$b.ready(${promiseName(name)})) instanceof Promise ? await $$t : $$t)`;
4636
+ }
4242
4637
  unique(prefix) {
4243
4638
  return `$$${prefix}${this.counter++}`;
4244
4639
  }
@@ -4266,19 +4661,25 @@ var Emitter = class {
4266
4661
  /** Creates the instance of a body scope. */
4267
4662
  createScope(scope) {
4268
4663
  const parent = instanceScope(this.plan, scope.parent);
4269
- this.line(`const ${this.scopeVar(scope)} = $$ctx.scope(${scope.id}, ${this.scopeVar(parent)});`);
4664
+ this.line(`const ${this.scopeVar(scope)} = ${this.helper("scope")}(${scope.id}, ${this.scopeVar(parent)});`);
4270
4665
  }
4271
4666
  emitSlots(scope) {
4272
4667
  const slots = this.plan.scopes.get(scope)?.slots ?? [];
4273
4668
  if (slots.length > 0) {
4274
4669
  const values = slots.map((slot) => this.isPromise(slot) ? `$$b.wait(${promiseName(slot.name)})` : slot.name);
4275
4670
  const names = this.options.mode === "server" ? `, ${JSON.stringify(slots.map((slot) => slot.name))}` : "";
4276
- this.line(`$$ctx.slots(${this.scopeVar(scope)}, [${values.join(", ")}]${names});`);
4671
+ this.line(`${this.helper("slots")}(${this.scopeVar(scope)}, [${values.join(", ")}]${names});`);
4277
4672
  }
4278
4673
  }
4674
+ /** True if the server inserts a primitive, such as a memo that it computes as a plain value. */
4675
+ isPrimitiveInsert(expression) {
4676
+ if (this.options.mode !== "server") return false;
4677
+ const site = this.sitesByNode.get(expression.ast);
4678
+ return isPrimitive(expression.ast, (name) => readsPlain(site, name, (declaration) => this.inline.has(declaration)));
4679
+ }
4279
4680
  /** True for an async memo that is a promise where its scope ends, on the server. */
4280
4681
  isPromise(declaration) {
4281
- return this.options.mode === "server" && isMemo(declaration) && !this.blocking.has(declaration);
4682
+ return this.options.mode === "server" && isMemo(declaration) && !this.blocking.has(declaration) && !this.inline.has(declaration);
4282
4683
  }
4283
4684
  /** Awaits the async memos of a statement that markup outside `#loading` reads. */
4284
4685
  awaitMemos(statement) {
@@ -4287,7 +4688,7 @@ var Emitter = class {
4287
4688
  const init = declarator.init;
4288
4689
  const argument = init?.type === "CallExpression" ? init.arguments[0] : void 0;
4289
4690
  const declaration = argument && this.sitesByNode.get(argument)?.declaration;
4290
- if (declaration && isMemo(declaration) && this.blocking.has(declaration)) this.line(`const ${declaration.name} = await $$b.wait(${promiseName(declaration.name)});`);
4691
+ if (declaration && isMemo(declaration) && this.blocking.has(declaration) && !this.inline.has(declaration)) this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
4291
4692
  }
4292
4693
  }
4293
4694
  emitStatements(statements, scope) {
@@ -4297,14 +4698,14 @@ var Emitter = class {
4297
4698
  const name = expression.type === "CallExpression" && expression.callee.type === "Identifier" ? expression.callee.name : void 0;
4298
4699
  if (name === "$effect" || name === "$client") continue;
4299
4700
  if (name === "$title" && expression.type === "CallExpression" && expression.arguments[0]) {
4300
- this.line(`$$ctx.title(${this.source(expression.arguments[0])});`);
4701
+ this.line(`${this.helper("title")}(${this.source(expression.arguments[0])});`);
4301
4702
  continue;
4302
4703
  }
4303
- if (name === "$provide" && expression.type === "CallExpression") {
4704
+ if (name === "$setContext" && expression.type === "CallExpression") {
4304
4705
  const [context, value] = expression.arguments;
4305
4706
  if (context && value) {
4306
4707
  const target = this.scopeVar(instanceScope(this.plan, scope));
4307
- this.line(`$$ctx.provide(${this.source(context)}, ${this.providedValue(value, scope)}, ${target});`);
4708
+ this.line(`${this.helper("provide")}(${this.source(context)}, ${this.providedValue(value, scope)}, ${target});`);
4308
4709
  }
4309
4710
  continue;
4310
4711
  }
@@ -4334,16 +4735,16 @@ var Emitter = class {
4334
4735
  const call = specialCall(declarator);
4335
4736
  const declaration = declarator.id.type === "Identifier" ? scope.declarations.get(declarator.id.name) : void 0;
4336
4737
  if (call === "$id" && declaration?.idIndex !== void 0) {
4337
- this.line(`const ${declaration.name} = $$ctx.id(${target}, ${declaration.idIndex});`);
4738
+ this.line(`const ${declaration.name} = ${this.helper("id")}(${target}, ${declaration.idIndex});`);
4338
4739
  continue;
4339
4740
  }
4340
- if (call !== "$context" || declarator.id.type !== "Identifier" || !init.arguments[0]) {
4741
+ if (call !== "$getContext" || declarator.id.type !== "Identifier" || !init.arguments[0]) {
4341
4742
  this.line(`${statement.kind} ${this.source(declarator)};`);
4342
4743
  continue;
4343
4744
  }
4344
4745
  const slot = declaration ? slotIndex(this.plan, declaration) : -1;
4345
4746
  const record = slot === -1 ? "" : `, ${slot}`;
4346
- this.line(`const ${declarator.id.name} = $$ctx.consume(${this.source(init.arguments[0])}, ${target}${record});`);
4747
+ this.line(`const ${declarator.id.name} = ${this.helper("consume")}(${this.source(init.arguments[0])}, ${target}${record});`);
4347
4748
  }
4348
4749
  return true;
4349
4750
  }
@@ -4363,15 +4764,15 @@ var Emitter = class {
4363
4764
  for (const site of this.plan.graph.model.sites) {
4364
4765
  if (site.kind !== "client" || site.scope !== scope) continue;
4365
4766
  const anchor = this.anchor(scope, site);
4366
- this.html("<template data-b=\"");
4767
+ this.html("<template b-b=\"");
4367
4768
  this.code(anchor.scope);
4368
- this.html(`:${anchor.index}" data-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"></template>`);
4769
+ this.html(`:${anchor.index}" b-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"></template>`);
4369
4770
  }
4370
4771
  }
4371
4772
  /** Emits the content of the component, without creating its scope. */
4372
4773
  emitComponentContent(setup) {
4373
4774
  const component = this.plan.graph.model.component;
4374
- if (this.plan.styles.css) this.code(`$$ctx.style(${JSON.stringify(this.plan.id)}, $$css)`);
4775
+ if (this.plan.styles.css) this.code(`${this.helper("style")}(${JSON.stringify(this.plan.id)}, $$css)`);
4375
4776
  this.emitStatements(setup, component);
4376
4777
  for (const template of this.file.templates) this.emitTemplate(template);
4377
4778
  this.emitClientAnchors(component);
@@ -4389,10 +4790,36 @@ var Emitter = class {
4389
4790
  this.emitNodes(body.children, scope);
4390
4791
  this.emitSlots(scope);
4391
4792
  }
4392
- /** Emits one item of `#for` or `#repeat`, given expressions for the item and its index. */
4393
- emitItem(block, item, index) {
4793
+ /**
4794
+ * On the server, the scope and slot of the list of a `#for` whose list is
4795
+ * a signal, memo or prop of an enclosing scope that the client gets, as an
4796
+ * expression. The client then takes each item from that list, and the
4797
+ * server does not write it. The server checks that each item is the value
4798
+ * of the list at its position before it leaves one out.
4799
+ */
4800
+ itemSource(block) {
4801
+ if (this.options.mode !== "server" || block.kind !== "for" || block.list.ast.type !== "Identifier" || block.item.type !== "Identifier" || !this.plan.anchors.has(block)) return;
4802
+ const scope = this.plan.bodyScopes.get(block.body).parent;
4803
+ const declaration = lookup(scope, block.list.ast.name);
4804
+ if (!declaration || ![
4805
+ "signal",
4806
+ "memo",
4807
+ "prop"
4808
+ ].includes(declaration.kind)) return;
4809
+ for (let current = scope; current; current = current.parent) {
4810
+ if (current.kind === "template") return;
4811
+ if (current === declaration.scope) break;
4812
+ }
4813
+ const slot = this.plan.scopes.get(declaration.scope)?.slots.indexOf(declaration) ?? -1;
4814
+ return slot === -1 ? void 0 : `[${this.scopeVar(declaration.scope)}, ${slot}]`;
4815
+ }
4816
+ /**
4817
+ * Emits one item of `#for` or `#repeat`, given expressions for the item and
4818
+ * its index, and on the server the scope and slot of its list.
4819
+ */
4820
+ emitItem(block, item, index, source) {
4394
4821
  const scope = this.plan.bodyScopes.get(block.body);
4395
- const anchored = this.plan.anchors.has(block);
4822
+ const anchored = this.plan.anchors.has(block) && !this.plan.elementItems.has(block);
4396
4823
  if (block.kind === "for") this.line(`const ${copy(this.file.source, block.item.start, block.item.end)} = ${item};`);
4397
4824
  if (block.index) this.line(`const ${block.index.name} = ${index};`);
4398
4825
  if (this.plan.scopes.get(scope).needsId) this.createScope(scope);
@@ -4402,10 +4829,11 @@ var Emitter = class {
4402
4829
  this.html("-->");
4403
4830
  }
4404
4831
  this.emitBody(block.body, false);
4405
- if (anchored) {
4406
- this.line(`$$ctx.item(${this.scopeVar(scope)}, ${item});`);
4407
- this.html("<!--/i-->");
4832
+ if (this.plan.anchors.has(block)) {
4833
+ const from = source ? `, ${source}` : "";
4834
+ this.line(`${this.helper("item")}(${this.scopeVar(scope)}, ${item}${from});`);
4408
4835
  }
4836
+ if (anchored) this.html("<!--/i-->");
4409
4837
  }
4410
4838
  emitTemplate(template) {
4411
4839
  const first = template.params[0];
@@ -4422,6 +4850,14 @@ var Emitter = class {
4422
4850
  emitNodes(nodes, scope) {
4423
4851
  for (const node of nodes) this.emitNode(node, scope);
4424
4852
  }
4853
+ /**
4854
+ * A render helper: a method of the render context on the server, and an
4855
+ * export of the core on the client, where a build keeps only the helpers
4856
+ * that its components call.
4857
+ */
4858
+ helper(name) {
4859
+ return this.options.mode === "server" ? `$$ctx.${name}` : `$$b.${CLIENT_HELPERS[name]}`;
4860
+ }
4425
4861
  emitNode(node, scope) {
4426
4862
  switch (node.kind) {
4427
4863
  case "text":
@@ -4430,14 +4866,16 @@ var Emitter = class {
4430
4866
  case "insert": {
4431
4867
  const anchor = this.anchor(scope, node);
4432
4868
  const at = this.options.mode === "server" ? `, $$ctx, ${this.scopeVar(instanceScope(this.plan, scope))}` : "";
4433
- const value = `${this.wait}$$b.insert(${this.expression(node.expression)}${at})`;
4434
- if (anchor) {
4869
+ const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${this.expression(node.expression)})` : this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
4870
+ const text = literalText(node.expression.ast);
4871
+ const emitValue = () => text === void 0 ? this.code(value) : this.html(text);
4872
+ if (anchor && !this.plan.contents.has(node)) {
4435
4873
  this.html("<!--t");
4436
4874
  this.code(anchor.scope);
4437
4875
  this.html(`:${anchor.index}-->`);
4438
- this.code(value);
4876
+ emitValue();
4439
4877
  this.html("<!--/t-->");
4440
- } else this.code(value);
4878
+ } else emitValue();
4441
4879
  return;
4442
4880
  }
4443
4881
  case "element":
@@ -4455,9 +4893,9 @@ var Emitter = class {
4455
4893
  case "listener": {
4456
4894
  const anchor = this.anchor(scope, node);
4457
4895
  const events = node.attributes.map((attribute) => this.eventEntry(attribute.event, attribute.modifiers, attribute.handler));
4458
- this.html("<template data-b=\"");
4896
+ this.html("<template b-b=\"");
4459
4897
  this.code(anchor.scope);
4460
- this.html(`:${anchor.index}" data-listen="${node.target}" data-on="${events.join(" ")}"></template>`);
4898
+ this.html(`:${anchor.index}" b-listen="${node.target}" b-on="${events.join(" ")}"></template>`);
4461
4899
  return;
4462
4900
  }
4463
4901
  default: this.emitBlock(node, scope);
@@ -4469,11 +4907,11 @@ var Emitter = class {
4469
4907
  }
4470
4908
  emitRef(target, attribute, anchor) {
4471
4909
  const declaration = this.refTargets.get(attribute);
4472
- const element = `$$ctx.element(${anchor.scope}, ${anchor.index})`;
4910
+ const element = `${this.helper("element")}(${anchor.scope}, ${anchor.index})`;
4473
4911
  const outer = this.options.outer;
4474
4912
  if (declaration && outer && !this.isInside(declaration.scope)) {
4475
4913
  const path = scopePath(this.plan, outer.baseVar, outer.base, declaration.scope);
4476
- this.line(`$$ctx.after(() => $$b.set(${path}, ${slotIndex(this.plan, declaration)}, ${element}));`);
4914
+ this.line(`${this.helper("after")}.push(() => $$b.set(${path}, ${slotIndex(this.plan, declaration)}, ${element}));`);
4477
4915
  } else this.line(`${target} = ${element};`);
4478
4916
  }
4479
4917
  /**
@@ -4490,7 +4928,7 @@ var Emitter = class {
4490
4928
  else if (own?.kind === "value") existing = this.expression(own.value);
4491
4929
  this.code(`$$b.attribute("style", $$b.vars({ ${values.join(", ")} }, ${existing}))`);
4492
4930
  if (this.plan.liveStyles) {
4493
- this.html(" data-v=\"");
4931
+ this.html(" b-v=\"");
4494
4932
  this.code(this.scopeVar(this.plan.graph.model.component));
4495
4933
  this.html("\"");
4496
4934
  }
@@ -4522,7 +4960,7 @@ var Emitter = class {
4522
4960
  }
4523
4961
  emitElement(node, scope) {
4524
4962
  this.html(`<${node.tag}`);
4525
- if (this.plan.styles.css) this.html(` ${this.plan.styles.attribute}`);
4963
+ if (this.hasScope(node.tag, staticClasses(node.attributes))) this.html(` ${this.plan.styles.attribute}`);
4526
4964
  const ownStyle = this.emitVariables(node);
4527
4965
  const events = [];
4528
4966
  let prefetch;
@@ -4539,6 +4977,11 @@ var Emitter = class {
4539
4977
  this.code(action);
4540
4978
  break;
4541
4979
  }
4980
+ const classes = attribute.name === "class" ? literalClasses(attribute.value.ast, (start, end) => this.patch.slice(start, end)) : void 0;
4981
+ if (classes) {
4982
+ this.emitClasses(classes);
4983
+ break;
4984
+ }
4542
4985
  this.code(`$$b.attribute(${JSON.stringify(attribute.name)}, ${this.expression(attribute.value)})`);
4543
4986
  break;
4544
4987
  }
@@ -4558,12 +5001,12 @@ var Emitter = class {
4558
5001
  }
4559
5002
  }
4560
5003
  if (anchor) {
4561
- this.html(" data-b=\"");
5004
+ this.html(" b-b=\"");
4562
5005
  this.code(anchor.scope);
4563
5006
  this.html(`:${anchor.index}"`);
4564
5007
  }
4565
5008
  if (events.length > 0) {
4566
- this.html(` data-on="${events.join(" ")}"`);
5009
+ this.html(` b-on="${events.join(" ")}"`);
4567
5010
  if (prefetch) this.html(` data-prefetch="${prefetch}"`);
4568
5011
  }
4569
5012
  this.html(">");
@@ -4573,6 +5016,39 @@ var Emitter = class {
4573
5016
  this.nesting--;
4574
5017
  this.html(`</${node.tag}>`);
4575
5018
  }
5019
+ /**
5020
+ * Renders a literal `class` value as the runtime renders it, without
5021
+ * building the value. A class with a condition is added when the condition
5022
+ * is truthy. No class leaves the attribute out.
5023
+ */
5024
+ emitClasses(classes) {
5025
+ const [first, ...rest] = classes;
5026
+ if (!first) return;
5027
+ const piece = (part) => {
5028
+ const text = JSON.stringify(` ${escapeClass(part.name)}`);
5029
+ return part.condition === void 0 ? text : `((${part.condition}) ? ${text} : "")`;
5030
+ };
5031
+ if (first.condition === void 0) {
5032
+ this.html(` class="${escapeClass(first.name)}`);
5033
+ for (const part of rest) if (part.condition === void 0) this.html(` ${escapeClass(part.name)}`);
5034
+ else this.code(piece(part));
5035
+ this.html("\"");
5036
+ } else if (rest.length === 0) {
5037
+ const text = JSON.stringify(` class="${escapeClass(first.name)}"`);
5038
+ this.code(`((${first.condition}) ? ${text} : "")`);
5039
+ } else this.code(`$$b.classAttribute(${classes.map(piece).join(" + ")})`);
5040
+ }
5041
+ /**
5042
+ * True if an element gets the scope attribute. In a build, only elements
5043
+ * that a scoped selector could match get it. In development, every
5044
+ * element of a component with styles gets it, so a change to the styles
5045
+ * applies without rendering the page again.
5046
+ */
5047
+ hasScope(tag, classes) {
5048
+ const { css, targets } = this.plan.styles;
5049
+ if (!css) return false;
5050
+ return !this.plan.hideNames || needsScope(targets, tag, classes);
5051
+ }
4576
5052
  /** Runs a callback for markup that renders outside this component's elements, such as children. */
4577
5053
  atTopLevel(callback) {
4578
5054
  const nesting = this.nesting;
@@ -4621,7 +5097,7 @@ var Emitter = class {
4621
5097
  const site = this.sitesByNode.get(part);
4622
5098
  const symbol = site?.kind === "prop" ? this.plan.symbols.get(site) : void 0;
4623
5099
  const code = `${method ? "function " : ""}${this.source(part)}`;
4624
- return symbol ? `$$ctx.fn(${code}, ${JSON.stringify(`${this.plan.id}#${symbol}`)}, ${instance})` : void 0;
5100
+ return symbol ? `${this.helper("fn")}(${code}, ${JSON.stringify(`${this.plan.id}#${symbol}`)}, ${instance})` : void 0;
4625
5101
  };
4626
5102
  if (value.type !== "ObjectExpression") return mark(value) ?? this.source(value);
4627
5103
  let code = "";
@@ -4644,7 +5120,7 @@ var Emitter = class {
4644
5120
  const symbol = site && this.plan.symbols.get(site);
4645
5121
  if (symbol) {
4646
5122
  const instance = this.scopeVar(instanceScope(this.plan, scope));
4647
- return `$$ctx.fn(${code}, ${JSON.stringify(`${this.plan.id}#${symbol}`)}, ${instance})`;
5123
+ return `${this.helper("fn")}(${code}, ${JSON.stringify(`${this.plan.id}#${symbol}`)}, ${instance})`;
4648
5124
  }
4649
5125
  return code;
4650
5126
  }
@@ -4654,16 +5130,16 @@ var Emitter = class {
4654
5130
  const anchor = this.anchor(scope, node);
4655
5131
  const owner = this.scopeVar(instanceScope(this.plan, scope));
4656
5132
  const link = anchor ? `, ${anchor.index}` : "";
4657
- this.code(`${this.wait}$$b.component(${node.name}, ${props}, $$ctx, ${owner}${link})`);
5133
+ this.code(`${this.wait}$$b.component(${node.name}, ${props}, ${this.ctxArgument}, ${owner}${link})`);
4658
5134
  }
4659
5135
  emitDynamic(node, scope) {
4660
5136
  const childrenName = this.emitChildren(node.children, scope);
4661
5137
  const extra = [];
4662
- if (this.plan.styles.css) extra.push(`${JSON.stringify(this.plan.styles.attribute)}: true`);
5138
+ if (this.hasScope(void 0, staticClasses(node.attributes))) extra.push(`${JSON.stringify(this.plan.styles.attribute)}: true`);
4663
5139
  const anchor = this.anchor(scope, node);
4664
- if (anchor) extra.push(`"data-b": \`\${${anchor.scope}}:${anchor.index}\``);
5140
+ if (anchor) extra.push(`"b-b": \`\${${anchor.scope}}:${anchor.index}\``);
4665
5141
  const events = node.attributes.flatMap((attribute) => attribute.kind === "event" ? [this.eventEntry(attribute.event, attribute.modifiers, attribute.handler)] : []);
4666
- if (events.length > 0) extra.push(`"data-on": ${JSON.stringify(events.join(" "))}`);
5142
+ if (events.length > 0) extra.push(`"b-on": ${JSON.stringify(events.join(" "))}`);
4667
5143
  let attributes = node.attributes.filter((attribute) => attribute.kind !== "event");
4668
5144
  const { variables } = this.plan.styles;
4669
5145
  if (variables.length > 0 && this.nesting === 0) {
@@ -4674,9 +5150,9 @@ var Emitter = class {
4674
5150
  attributes = attributes.filter((attribute) => attribute !== own);
4675
5151
  const values = variables.map((variable) => `${JSON.stringify(variable.name)}: ${variableValue(variable, this.expression(variable.expression))}`);
4676
5152
  extra.push(`"style": $$b.vars({ ${values.join(", ")} }, ${existing})`);
4677
- if (this.plan.liveStyles) extra.push(`"data-v": ${this.scopeVar(this.plan.graph.model.component)}`);
5153
+ if (this.plan.liveStyles) extra.push(`"b-v": ${this.scopeVar(this.plan.graph.model.component)}`);
4678
5154
  }
4679
- this.code(`${this.wait}$$b.dynamic(${this.expression(node.tag)}, ${this.props(attributes, scope, extra)}, ${childrenName ?? "undefined"}, $$ctx, ${this.scopeVar(instanceScope(this.plan, scope))})`);
5155
+ this.code(this.ready(`$$b.dynamic(${this.expression(node.tag)}, ${this.props(attributes, scope, extra)}, ${childrenName ?? "undefined"}, ${this.ctxArgument}, ${this.scopeVar(instanceScope(this.plan, scope))})`));
4680
5156
  }
4681
5157
  /**
4682
5158
  * Renders a portal. Without a target, the body goes to the end of the page,
@@ -4687,9 +5163,9 @@ var Emitter = class {
4687
5163
  const body = this.plan.bodyScopes.get(block.body);
4688
5164
  if (block.kind === "portal" && block.target) {
4689
5165
  const anchor = this.anchor(scope, block);
4690
- this.html("<template data-b=\"");
5166
+ this.html("<template b-b=\"");
4691
5167
  this.code(anchor.scope);
4692
- this.html(`:${anchor.index}" data-client="load=${this.plan.id}#k${body.id}"></template>`);
5168
+ this.html(`:${anchor.index}" b-client="load=${this.plan.id}#k${body.id}"></template>`);
4693
5169
  return;
4694
5170
  }
4695
5171
  const name = this.unique("portal");
@@ -4704,7 +5180,7 @@ var Emitter = class {
4704
5180
  this.flush();
4705
5181
  this.line("return $$html;");
4706
5182
  this.close("})();");
4707
- this.line(`$$ctx.${block.kind === "head" ? "head" : "portal"}(${name});`);
5183
+ this.line(`${this.helper(block.kind === "head" ? "head" : "portal")}(${name});`);
4708
5184
  }
4709
5185
  /**
4710
5186
  * Writes the fallback of `#loading` and renders its body after the rest of
@@ -4727,7 +5203,10 @@ var Emitter = class {
4727
5203
  this.end(block);
4728
5204
  this.line(`$$ctx.defer(${boundary}, async ($$ctx) => {`);
4729
5205
  this.line(`let $$html = '';`);
4730
- for (const declaration of awaitedMemos(this.plan, body, this.blocking)) this.line(`const ${declaration.name} = await $$b.wait(${promiseName(declaration.name)});`);
5206
+ for (const declaration of awaitedMemos(this.plan, body, this.blocking)) {
5207
+ if (this.inline.has(declaration)) continue;
5208
+ this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5209
+ }
4731
5210
  this.emitBody(block.body);
4732
5211
  this.flush();
4733
5212
  this.line("return $$html;");
@@ -4770,11 +5249,18 @@ var Emitter = class {
4770
5249
  const item = this.unique("item");
4771
5250
  const index = this.unique("index");
4772
5251
  this.line("{");
4773
- if (block.kind === "for") this.line(`const ${list} = Array.from(${this.expression(block.list)});`);
4774
- else this.line(`const ${list} = Array.from({ length: ${this.expression(block.count)} }, (_, index) => index);`);
5252
+ if (block.kind === "for") {
5253
+ const value = `${list}v`;
5254
+ this.line(`const ${value} = ${this.expression(block.list)};`);
5255
+ this.line(`const ${list} = Array.isArray(${value}) ? ${value} : Array.from(${value});`);
5256
+ } else this.line(`const ${list} = Array.from({ length: ${this.expression(block.count)} }, (_, index) => index);`);
4775
5257
  this.open(scope, block);
4776
- this.line(`for (const [${index}, ${item}] of ${list}.entries()) {`);
4777
- this.emitItem(block, item, index);
5258
+ const from = this.itemSource(block);
5259
+ const source = from && this.unique("source");
5260
+ if (source) this.line(`const ${source} = ${from};`);
5261
+ this.line(`for (let ${index} = 0; ${index} < ${list}.length; ${index}++) {`);
5262
+ this.line(`const ${item} = ${list}[${index}];`);
5263
+ this.emitItem(block, item, index, source);
4778
5264
  this.close();
4779
5265
  if (block.fallback) {
4780
5266
  this.line(`if (${list}.length === 0) {`);
@@ -4788,13 +5274,16 @@ var Emitter = class {
4788
5274
  case "try": {
4789
5275
  const before = this.unique("before");
4790
5276
  const error = this.unique("error");
5277
+ const mark = this.options.mode === "server" ? this.unique("mark") : void 0;
4791
5278
  this.open(scope, block);
4792
5279
  this.flush();
4793
5280
  this.line(`const ${before} = $$html;`);
5281
+ if (mark) this.line(`const ${mark} = $$ctx.mark();`);
4794
5282
  this.line("try {");
4795
5283
  this.emitBody(block.body);
4796
5284
  this.close(`} catch (${error}) {`);
4797
5285
  this.line(`$$html = ${before};`);
5286
+ if (mark) this.line(`$$ctx.restore(${mark});`);
4798
5287
  if (block.error) this.line(`const ${block.error.name} = ${error};`);
4799
5288
  if (block.reset) this.line(`const ${block.reset.name} = undefined;`);
4800
5289
  this.emitBody(block.fallback);
@@ -4805,9 +5294,9 @@ var Emitter = class {
4805
5294
  case "client": {
4806
5295
  const anchor = this.anchor(scope, block);
4807
5296
  const body = this.plan.bodyScopes.get(block.body);
4808
- this.html("<template data-b=\"");
5297
+ this.html("<template b-b=\"");
4809
5298
  this.code(anchor.scope);
4810
- this.html(`:${anchor.index}" data-client="${block.trigger}=${this.plan.id}#k${body.id}"></template>`);
5299
+ this.html(`:${anchor.index}" b-client="${block.trigger}=${this.plan.id}#k${body.id}"></template>`);
4811
5300
  this.open(scope, block);
4812
5301
  this.end(block);
4813
5302
  return;
@@ -4827,6 +5316,16 @@ var Emitter = class {
4827
5316
  case "head":
4828
5317
  this.emitPortal(block, scope);
4829
5318
  return;
5319
+ case "offscreen":
5320
+ this.line(`if ${this.expression(block.visible)} {`);
5321
+ this.open(scope, block, "1");
5322
+ this.emitBody(block.body);
5323
+ this.end(block);
5324
+ this.close("} else {");
5325
+ this.open(scope, block, "-1");
5326
+ this.end(block);
5327
+ this.close();
5328
+ return;
4830
5329
  default:
4831
5330
  this.open(scope, block);
4832
5331
  this.line("{");
@@ -4836,6 +5335,88 @@ var Emitter = class {
4836
5335
  }
4837
5336
  }
4838
5337
  };
5338
+ /**
5339
+ * The classes of an element, or undefined when it can have classes that are
5340
+ * not known. Code can add classes to an element that it has a ref to or that
5341
+ * it handles events of, such as `event.currentTarget.classList`.
5342
+ */
5343
+ function staticClasses(attributes) {
5344
+ const classes = [];
5345
+ for (const attribute of attributes) {
5346
+ if (attribute.kind === "spread" || attribute.kind === "computed" || attribute.kind === "ref" || attribute.kind === "event") return;
5347
+ if ((attribute.kind === "static" || attribute.kind === "value") && attribute.name.toLowerCase() === "class") {
5348
+ if (attribute.kind === "value") return;
5349
+ if (attribute.value !== true) classes.push(...attribute.value.split(/\s+/).filter(Boolean));
5350
+ }
5351
+ }
5352
+ return classes;
5353
+ }
5354
+ /** Escapes a class for an attribute, as the runtime does. */
5355
+ function escapeClass(name) {
5356
+ return name.replace(/[&<"]/g, (char) => char === "&" ? "&amp;" : char === "<" ? "&lt;" : "&quot;");
5357
+ }
5358
+ /**
5359
+ * The classes of a literal `class` value, such as `{ done: todo.done }` or
5360
+ * `['todo', { done: todo.done }]`, in the order that the runtime joins them.
5361
+ * `slice` returns the compiled code of a range of the source. Returns
5362
+ * undefined for a value that only the runtime can read, such as one with a
5363
+ * spread or a computed key.
5364
+ */
5365
+ function literalClasses(value, slice) {
5366
+ if (value.type !== "ObjectExpression" && value.type !== "ArrayExpression") return;
5367
+ const parts = [];
5368
+ const visit = (node) => {
5369
+ if (node === null) return true;
5370
+ if (node.type === "Literal" && typeof node.value === "string") {
5371
+ if (node.value !== "") parts.push({ name: node.value });
5372
+ return true;
5373
+ }
5374
+ if (node.type === "ArrayExpression") return node.elements.every(visit);
5375
+ if (node.type !== "ObjectExpression") return false;
5376
+ const names = /* @__PURE__ */ new Set();
5377
+ for (const property of node.properties) {
5378
+ if (property.type !== "Property" || property.kind !== "init" || property.method || property.computed) return false;
5379
+ const { key } = property;
5380
+ const name = key.type === "Identifier" ? key.name : key.type === "Literal" && typeof key.value === "string" ? key.value : void 0;
5381
+ if (!name || /^\d+$/.test(name) || name === "__proto__" || names.has(name)) return false;
5382
+ names.add(name);
5383
+ const constant = property.value;
5384
+ if (constant.type === "Literal" && (constant.value === null || [
5385
+ "boolean",
5386
+ "number",
5387
+ "string"
5388
+ ].includes(typeof constant.value))) {
5389
+ if (constant.value) parts.push({ name });
5390
+ continue;
5391
+ }
5392
+ let condition = slice(property.value.start, property.value.end);
5393
+ if (property.shorthand) {
5394
+ const whole = slice(property.start, property.end);
5395
+ if (whole.startsWith(`${name}: `)) condition = whole.slice(name.length + 2);
5396
+ else if (unmarked(whole) !== name) return false;
5397
+ }
5398
+ parts.push({
5399
+ name,
5400
+ condition
5401
+ });
5402
+ }
5403
+ return true;
5404
+ };
5405
+ return visit(value) ? parts : void 0;
5406
+ }
5407
+ /**
5408
+ * The code of the text that the runtime makes of a literal class value,
5409
+ * for the client to set. An empty text removes the attribute.
5410
+ */
5411
+ function classText(classes) {
5412
+ if (classes.every((part) => part.condition === void 0)) return JSON.stringify(classes.map((part) => part.name).join(" "));
5413
+ const [first] = classes;
5414
+ if (classes.length === 1 && first) return `((${first.condition}) ? ${JSON.stringify(first.name)} : "")`;
5415
+ return `(${classes.map((part) => {
5416
+ const text = JSON.stringify(` ${part.name}`);
5417
+ return part.condition === void 0 ? text : `((${part.condition}) ? ${text} : "")`;
5418
+ }).join(" + ")}).slice(1)`;
5419
+ }
4839
5420
  /** The value of a style variable, with the text around its interpolation, such as a unit. */
4840
5421
  function variableValue(variable, expression) {
4841
5422
  return variable.prefix || variable.suffix ? `$$b.affix(${JSON.stringify(variable.prefix)}, ${expression}, ${JSON.stringify(variable.suffix)})` : expression;
@@ -4869,7 +5450,7 @@ function serverFunctions(plan) {
4869
5450
  function generateServer(file, plan) {
4870
5451
  const model = plan.graph.model;
4871
5452
  const patch = new Patch(file.source);
4872
- addValueEdits(patch, file, model.sites);
5453
+ addValueEdits(patch, file, model.sites, "server", plainValues(plan, blockingMemos(plan)));
4873
5454
  addEventEdits(patch, model);
4874
5455
  const source = (node) => patch.slice(node.start, node.end);
4875
5456
  const header = ["import * as $$b from 'brumate/server';"];
@@ -4895,7 +5476,11 @@ function generateServer(file, plan) {
4895
5476
  const exported = serverFunctions(plan).map((declaration) => `${JSON.stringify(serverFunctionId(plan, declaration.name))}: ${declaration.name}`);
4896
5477
  moduleBody.push(`export const rpc = { ${exported.join(", ")} };`);
4897
5478
  for (const declaration of serverFunctions(plan)) moduleBody.push(`${declaration.name} = $$b.dedupe(${declaration.name}, ${JSON.stringify(serverFunctionId(plan, declaration.name))});`);
4898
- if (plan.styles.css) moduleBody.push(`const $$css = ${JSON.stringify(plan.styles.css)};`);
5479
+ if (plan.styles.css) {
5480
+ const css = plan.hideNames ? minifyCSS(plan.styles.css) : plan.styles.css;
5481
+ moduleBody.push(`const $$css = ${JSON.stringify(css)};`);
5482
+ }
5483
+ moduleBody.push("let $$t: any;");
4899
5484
  const emitter = new Emitter(file, plan, patch, { mode: "server" });
4900
5485
  const generics = file.generics ? `<${file.generics}>` : "";
4901
5486
  emitter.line(`export default async function ${plan.name}${generics}($$props: ${propsType(file)}, $$ctx: $$b.Context): Promise<string> {`);
@@ -4955,7 +5540,8 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
4955
5540
  case "key":
4956
5541
  case "portal":
4957
5542
  case "head":
4958
- case "client": componentNames(node.body.children, names);
5543
+ case "client":
5544
+ case "offscreen": componentNames(node.body.children, names);
4959
5545
  }
4960
5546
  return names;
4961
5547
  }
@@ -5030,7 +5616,10 @@ function generateRender(file, plan) {
5030
5616
  moduleBody.push(`const ${declaration.name} = (...$$a) => $$b.rpc(${JSON.stringify(ref)}, $$a);`);
5031
5617
  }
5032
5618
  const setup = (file.instanceScript?.program.body ?? []).filter((statement) => statement.type !== "ImportDeclaration" && !TYPE_DECLARATIONS.has(statement.type));
5033
- if (plan.styles.css) moduleBody.push(`const $$css = ${JSON.stringify(plan.styles.css)};`);
5619
+ if (plan.styles.css) {
5620
+ const css = plan.hideNames ? minifyCSS(plan.styles.css) : plan.styles.css;
5621
+ moduleBody.push(`const $$css = ${JSON.stringify(css)};`);
5622
+ }
5034
5623
  const emitter = new Emitter(file, plan, patch, {
5035
5624
  mode: "client",
5036
5625
  functions: true
@@ -5038,7 +5627,7 @@ function generateRender(file, plan) {
5038
5627
  const generics = file.generics ? `<${file.generics}>` : "";
5039
5628
  emitter.line(`export default function ${plan.name}${generics}($$props: ${propsType(file)}): string {`);
5040
5629
  emitter.line(`let $$html = '';`);
5041
- emitter.line(`const ${emitter.scopeVar(model.component)} = $$ctx.scope(${model.component.id}, undefined, ${JSON.stringify(plan.id)});`);
5630
+ emitter.line(`const ${emitter.scopeVar(model.component)} = $$b.createScope(${model.component.id}, undefined, ${JSON.stringify(plan.id)});`);
5042
5631
  emitter.emitComponentContent(setup);
5043
5632
  emitter.line("return $$html;");
5044
5633
  emitter.close();
@@ -5046,8 +5635,6 @@ function generateRender(file, plan) {
5046
5635
  ...header,
5047
5636
  ...moduleBody,
5048
5637
  "",
5049
- "const $$ctx = $$b.context;",
5050
- "",
5051
5638
  ...emitter.lines,
5052
5639
  ""
5053
5640
  ].join("\n");
@@ -5168,6 +5755,22 @@ var Rewriter = class {
5168
5755
  const shared = this.sharedCall(site, scopeVar, base);
5169
5756
  if (shared) return shared.kind === "function" ? `((...$$a) => ${shared.fn}(${scopeVar}, ${shared.refs}, ...$$a))` : `${shared.fn}(${scopeVar}, ${shared.refs})`;
5170
5757
  }
5758
+ const patch = this.edits(site, scopeVar, base, options);
5759
+ const range = options.range ?? site.node;
5760
+ return patch.slice(range.start, range.end);
5761
+ }
5762
+ /**
5763
+ * Rewrites the code of a site, and passes `read` a function that returns
5764
+ * the rewritten code of a range in it. Returns undefined for a site that
5765
+ * calls the shared module, because its code is not in the component.
5766
+ */
5767
+ rewriteRanges(site, scopeVar, base, read) {
5768
+ if (this.sharedCall(site, scopeVar, base)) return;
5769
+ const patch = this.edits(site, scopeVar, base, {});
5770
+ return read((start, end) => patch.slice(start, end));
5771
+ }
5772
+ /** The edits that rewrite the code of a site. */
5773
+ edits(site, scopeVar, base, options) {
5171
5774
  const patch = new Patch(this.file.source);
5172
5775
  const locals = options.locals ?? /* @__PURE__ */ new Set();
5173
5776
  const references = /* @__PURE__ */ new Map();
@@ -5251,7 +5854,16 @@ var Rewriter = class {
5251
5854
  }
5252
5855
  break;
5253
5856
  }
5254
- case "CallExpression":
5857
+ case "CallExpression": {
5858
+ const fn = target(node.callee)?.declaration;
5859
+ if (fn?.kind === "function" && slotIndex(this.plan, fn) === -1) {
5860
+ const owner = scopePath(this.plan, scopeVar, base, instanceScope(this.plan, fn.scope));
5861
+ const open = this.file.source.indexOf("(", node.typeArguments?.end ?? node.callee.end);
5862
+ patch.replace(node.callee.start, node.callee.end, `${fn.name}$`);
5863
+ patch.insert(open + 1, node.arguments.length > 0 ? `${owner}, ` : owner);
5864
+ for (const argument of node.arguments) visit(argument);
5865
+ return;
5866
+ }
5255
5867
  if (node.callee.type === "Identifier" && node.callee.name === "$isPending" && !references.has(node.callee.start)) {
5256
5868
  const memo = node.arguments[0];
5257
5869
  const declaration = memo && references.get(memo.start)?.declaration;
@@ -5275,6 +5887,7 @@ var Rewriter = class {
5275
5887
  return;
5276
5888
  }
5277
5889
  break;
5890
+ }
5278
5891
  case "MemberExpression":
5279
5892
  visit(node.object);
5280
5893
  if (node.computed) visit(node.property);
@@ -5288,12 +5901,24 @@ var Rewriter = class {
5288
5901
  };
5289
5902
  visit(site.node);
5290
5903
  options.edit?.(patch);
5291
- const range = options.range ?? site.node;
5292
- return patch.slice(range.start, range.end);
5904
+ return patch;
5293
5905
  }
5294
5906
  };
5295
5907
  //#endregion
5296
5908
  //#region src/codegen/client.ts
5909
+ /**
5910
+ * About the size of code after a minifier: without comments, extra
5911
+ * whitespace and long generated names. Merging parts compares it.
5912
+ */
5913
+ function minifiedSize(code) {
5914
+ return code.replace(/\/\*[\s\S]*?\*\/|^\s*\/\/[^\n]*/gm, "").replace(/\$\$\w+/g, "e").replace(/\s+/g, " ").replace(/ ?([{}()[\];,:=+\-*/<>!?&|.]) ?/g, "$1").length;
5915
+ }
5916
+ /**
5917
+ * The `merge` of the Vite plugin. Below it, one module costs less than the
5918
+ * entry and the parts that a first event loads: each file has its own
5919
+ * request, imports and gzip header, and the parts wait for the entry.
5920
+ */
5921
+ const DEFAULT_MERGE = 4096;
5297
5922
  const DEFERRED_SITES = /* @__PURE__ */ new Set([
5298
5923
  "function",
5299
5924
  "server-function",
@@ -5303,8 +5928,8 @@ const DEFERRED_SITES = /* @__PURE__ */ new Set([
5303
5928
  ]);
5304
5929
  /**
5305
5930
  * Generates the client entry and its parts. When the parts are smaller than
5306
- * `merge` bytes in all, they become one part, `all`, so the first event loads
5307
- * one module instead of several.
5931
+ * `merge` bytes in all, after minifying, the entry holds their code itself,
5932
+ * so the first event loads one module instead of several.
5308
5933
  */
5309
5934
  function generateClient(file, plan, merge = 0, shared) {
5310
5935
  return new ClientGenerator(file, plan, merge, shared).generate();
@@ -5362,18 +5987,17 @@ var ClientGenerator = class {
5362
5987
  this.checkSupport();
5363
5988
  this.collectRenders();
5364
5989
  this.placeCode();
5365
- this.emitServerStubs();
5366
5990
  this.emitFunctions();
5367
5991
  this.emitRoots();
5368
5992
  this.part = "update";
5369
5993
  this.emitUpdates();
5370
5994
  this.emitRenders();
5371
5995
  const parts = {};
5372
- for (const name of /* @__PURE__ */ new Set([...this.out.keys(), ...this.reach.keys()])) if (name !== "shared") parts[name] = this.assemble(name);
5996
+ for (const name of /* @__PURE__ */ new Set([...this.out.keys(), ...this.reach.keys()])) if (name !== "shared" && (this.out.get(name)?.length ?? 0) > 0) parts[name] = this.assemble(name);
5373
5997
  if (this.out.has("shared") || this.usesModuleScript()) parts.shared = this.assembleShared();
5374
5998
  const names = Object.keys(parts).filter((name) => name !== "shared");
5375
- const size = Object.values(parts).reduce((total, code) => total + code.length, 0);
5376
- const merged = !parts.shared && names.length > 1 && size < this.merge;
5999
+ const size = Object.values(parts).reduce((total, code) => total + minifiedSize(code), 0);
6000
+ const merged = !parts.shared && names.length > 0 && size < this.merge;
5377
6001
  if (merged) {
5378
6002
  for (const name of names) delete parts[name];
5379
6003
  parts.all = this.assembleAll(names);
@@ -5382,16 +6006,45 @@ var ClientGenerator = class {
5382
6006
  const used = new Set([...code.matchAll(/\$\$m(\d+)\./g)].map((match) => Number(match[1])));
5383
6007
  if (used.size > 0) parts[name] = `${[...used].map((index) => `import * as $$m${index} from ${JSON.stringify(this.shared.specifiers[index])};`).join("\n")}\n${code}`;
5384
6008
  }
5385
- const loaders = names.map((name) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(this.partPath(merged ? "all" : name))}),`);
5386
6009
  const refresh = this.refreshTable();
6010
+ const table = [
6011
+ `export const id = ${JSON.stringify(this.plan.id)};`,
6012
+ `export const props = ${this.propsMap()};`,
6013
+ `export const g = ${this.table()};`,
6014
+ ...refresh ? [`export const refresh = ${refresh};`] : []
6015
+ ];
6016
+ const clientCode = names.length > 0;
6017
+ if (merged || !clientCode) {
6018
+ const code = parts.all ?? "";
6019
+ delete parts.all;
6020
+ return {
6021
+ code: [
6022
+ code,
6023
+ ...table,
6024
+ ""
6025
+ ].join("\n"),
6026
+ table: table.join("\n"),
6027
+ parts,
6028
+ loaders: Object.fromEntries(names.map((name) => [name, []])),
6029
+ clientCode,
6030
+ diagnostics: this.diagnostics
6031
+ };
6032
+ }
6033
+ const writers = this.liveWrites();
6034
+ const loaders = {};
6035
+ for (const name of names) loaders[name] = name !== "update" && parts.update && writers.has(name) ? [name, "update"] : [name];
6036
+ const withUpdate = Object.values(loaders).some((list) => list.length > 1);
6037
+ const lines = Object.entries(loaders).map(([name, [own, extra]]) => {
6038
+ if (name === "update" && withUpdate) return " \"update\": update,";
6039
+ const load = `import(${JSON.stringify(this.partPath(own))})`;
6040
+ return ` ${JSON.stringify(name)}: () => ${extra ? `(update().catch(() => {}), ${load})` : load},`;
6041
+ });
5387
6042
  return {
5388
6043
  code: [
5389
- `export const id = ${JSON.stringify(this.plan.id)};`,
5390
- `export const props = ${this.propsMap()};`,
5391
- `export const g = ${this.table()};`,
5392
- ...refresh ? [`export const refresh = ${refresh};`] : [],
6044
+ ...table,
6045
+ ...withUpdate ? [`const update = () => import(${JSON.stringify(this.partPath("update"))});`] : [],
5393
6046
  "const parts = {",
5394
- ...loaders,
6047
+ ...lines,
5395
6048
  "};",
5396
6049
  "/** Imports a part of this module. */",
5397
6050
  "export function load(part) {",
@@ -5399,10 +6052,30 @@ var ClientGenerator = class {
5399
6052
  "}",
5400
6053
  ""
5401
6054
  ].join("\n"),
6055
+ table: table.join("\n"),
5402
6056
  parts,
6057
+ loaders,
6058
+ clientCode,
5403
6059
  diagnostics: this.diagnostics
5404
6060
  };
5405
6061
  }
6062
+ /**
6063
+ * The parts whose code can write a slot that an update reads, or that call
6064
+ * shared code of a module function, which can write one.
6065
+ */
6066
+ liveWrites() {
6067
+ const live = /* @__PURE__ */ new Set();
6068
+ for (const edge of this.plan.graph.edges) {
6069
+ const from = edge.from;
6070
+ if ((from.kind === "source" || from.kind === "memo") && this.updates.has(edge.to)) live.add(from.declaration);
6071
+ }
6072
+ const result = /* @__PURE__ */ new Set();
6073
+ for (const [name, sites] of this.reach) for (const site of sites) if (site.writes.some((write) => live.has(write.declaration)) || site.reads.some((read) => read.declaration.kind === "reset") || this.shared?.find(site.node) !== void 0) {
6074
+ result.add(name);
6075
+ break;
6076
+ }
6077
+ return result;
6078
+ }
5406
6079
  /** The import path of a part, relative to the component's file. */
5407
6080
  partPath(name) {
5408
6081
  return `./${this.file.filename.split(/[\\/]/).pop()}?brumate-client&part=${name}`;
@@ -5479,8 +6152,7 @@ var ClientGenerator = class {
5479
6152
  const shared = [...reads].filter((item) => item.kind === "function" && this.placement.get(item) === "shared" || item.kind === "module" && item.scope === this.model.module).map((item) => item.kind === "function" ? `${item.name}$` : item.name);
5480
6153
  const lines = ["import * as $$b from 'brumate/client';", ...this.importsFor(names, name === "update")];
5481
6154
  if (shared.length > 0) lines.push(`import { ${[...new Set(shared)].join(", ")} } from ${JSON.stringify(this.partPath("shared"))};`);
5482
- if (name === "update") lines.push("", "const $$ctx = $$b.context;");
5483
- lines.push("", ...this.out.get(name) ?? [], "");
6155
+ lines.push("", ...this.serverStubs([name]), ...this.out.get(name) ?? [], "");
5484
6156
  return lines.join("\n");
5485
6157
  }
5486
6158
  /** One module with the code of every part, for a small component. */
@@ -5491,7 +6163,7 @@ var ClientGenerator = class {
5491
6163
  "import * as $$b from 'brumate/client';",
5492
6164
  ...this.importsFor(imports, true),
5493
6165
  "",
5494
- "const $$ctx = $$b.context;"
6166
+ ...this.serverStubs(names)
5495
6167
  ];
5496
6168
  for (const name of names) lines.push("", ...this.out.get(name) ?? []);
5497
6169
  lines.push("");
@@ -5511,7 +6183,7 @@ var ClientGenerator = class {
5511
6183
  const rest = [...this.model.module.declarations.values()].filter((declaration) => declaration.kind === "module" && !exported.has(declaration.name)).map((declaration) => declaration.name);
5512
6184
  if (rest.length > 0) lines.push(`export { ${rest.join(", ")} };`);
5513
6185
  }
5514
- lines.push("", ...this.out.get("shared") ?? [], "");
6186
+ lines.push("", ...this.serverStubs(["shared"]), ...this.out.get("shared") ?? [], "");
5515
6187
  return lines.join("\n");
5516
6188
  }
5517
6189
  checkSupport() {
@@ -5571,15 +6243,17 @@ var ClientGenerator = class {
5571
6243
  }
5572
6244
  return `{ ${entries.join(", ")} }`;
5573
6245
  }
5574
- /** Writes a stub for each server function into each part that calls it. */
5575
- emitServerStubs() {
5576
- for (const name of [...this.reach.keys(), "shared"]) {
5577
- this.part = name;
5578
- for (const declaration of this.reads(this.partSites(name))) if (declaration.kind === "server-function" && declaration.scope !== this.model.module) {
5579
- const ref = serverFunctionId(this.plan, declaration.name);
5580
- this.emit(`const ${declaration.name}$ = (...$$a) => $$b.rpc(${JSON.stringify(ref)}, $$a);`);
5581
- }
6246
+ /**
6247
+ * A stub for each server function that some parts call, also one of the
6248
+ * module script. A merged module gets each stub once.
6249
+ */
6250
+ serverStubs(names) {
6251
+ const result = /* @__PURE__ */ new Set();
6252
+ for (const name of names) for (const declaration of this.reads(this.partSites(name))) if (declaration.kind === "server-function") {
6253
+ const ref = serverFunctionId(this.plan, declaration.name);
6254
+ result.add(`const ${declaration.name}$ = (...$$a) => $$b.rpc(${JSON.stringify(ref)}, $$a);`);
5582
6255
  }
6256
+ return [...result];
5583
6257
  }
5584
6258
  emitFunctions() {
5585
6259
  for (const declaration of this.model.declarations) {
@@ -5619,9 +6293,32 @@ var ClientGenerator = class {
5619
6293
  if (site.node.type === "FunctionExpression" && unmarked(code).trimStart().startsWith("(")) code = `function ${code}`;
5620
6294
  this.part = symbol;
5621
6295
  if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.effect($$s, ${JSON.stringify(symbol)}, ${code});\n}`);
5622
- else this.emit(`export const ${symbol} = ($$s, ...$$a) => (${code})(...$$a);`);
6296
+ else this.emit(this.handlerExport(site, symbol, code, base));
5623
6297
  }
5624
6298
  }
6299
+ /**
6300
+ * The export of a handler, which the core calls with the scope and the
6301
+ * arguments. A local function already takes them, so it is exported as it
6302
+ * is. An arrow function gets the scope as its first parameter.
6303
+ */
6304
+ handlerExport(site, symbol, code, base) {
6305
+ const node = site.node;
6306
+ const fn = node.type === "Identifier" ? site.reads.find((read) => read.range.start === node.start)?.declaration : void 0;
6307
+ if (fn?.kind === "function" && slotIndex(this.plan, fn) === -1) {
6308
+ const owner = scopePath(this.plan, "$$s", base, instanceScope(this.plan, fn.scope));
6309
+ if (owner === "$$s") return `export { ${fn.name}$ as ${symbol} };`;
6310
+ return `export const ${symbol} = ($$s, ...$$a) => ${fn.name}$(${owner}, ...$$a);`;
6311
+ }
6312
+ if (node.type === "ArrowFunctionExpression" && !this.rewriter.sharedCall(site, "$$s", base)) return `export const ${symbol} = ${this.rewriter.rewrite(site, "$$s", base, { edit: (patch) => {
6313
+ const first = node.params[0];
6314
+ if (first) {
6315
+ const parenthesized = this.file.source.lastIndexOf("(", first.start) >= node.start;
6316
+ patch.insert(first.start, parenthesized ? "$$s, " : "($$s, ");
6317
+ if (!parenthesized) patch.insert(first.end, ")");
6318
+ } else patch.insert(this.file.source.indexOf("(", node.start) + 1, "$$s");
6319
+ } })};`;
6320
+ return `export const ${symbol} = ($$s, ...$$a) => (${code})(...$$a);`;
6321
+ }
5625
6322
  emitUpdates() {
5626
6323
  const blocks = /* @__PURE__ */ new Map();
5627
6324
  for (const node of this.plan.graph.nodes) {
@@ -5629,6 +6326,11 @@ var ClientGenerator = class {
5629
6326
  const site = node.site;
5630
6327
  const base = instanceScope(this.plan, site.scope);
5631
6328
  const expression = () => this.withTemplates(site, this.rewriter.rewrite(site, "$$s", base));
6329
+ const classes = (value) => {
6330
+ if ([...site.calls].some((callee) => callee.kind === "template")) return;
6331
+ const parts = this.rewriter.rewriteRanges(site, "$$s", base, (slice) => literalClasses(value, slice));
6332
+ return parts && classText(parts);
6333
+ };
5632
6334
  const name = (prefix) => {
5633
6335
  const value = `${prefix}${site.id}`;
5634
6336
  this.updates.set(node, value);
@@ -5647,7 +6349,7 @@ var ClientGenerator = class {
5647
6349
  this.emit(`export function ${name("e")}($$s) {\n $$b.effect($$s, ${JSON.stringify(`e${site.id}`)}, ${expression()});\n}`);
5648
6350
  break;
5649
6351
  case "binding":
5650
- this.emitBinding(node, site, expression, name);
6352
+ this.emitBinding(node, site, expression, name, classes);
5651
6353
  break;
5652
6354
  case "block": {
5653
6355
  if (site.label === "for key") break;
@@ -5664,12 +6366,15 @@ var ClientGenerator = class {
5664
6366
  }
5665
6367
  }
5666
6368
  }
5667
- emitBinding(node, site, expression, name) {
6369
+ emitBinding(node, site, expression, name, classes) {
5668
6370
  const owner = site.owner;
5669
6371
  if (site.kind === "insert") {
5670
6372
  const insert = this.findInsert(site);
5671
6373
  const anchor = insert && this.plan.anchors.get(insert);
5672
- if (anchor !== void 0) this.emit(`export function ${name("u")}($$s) {\n $$b.text($$s, ${anchor}, ${expression()});\n}`);
6374
+ if (anchor !== void 0) {
6375
+ const fn = this.plan.textContents.has(insert) ? "writeText" : this.plan.contents.has(insert) ? "content" : "text";
6376
+ this.emit(`export function ${name("u")}($$s) {\n $$b.${fn}($$s, ${anchor}, ${expression()});\n}`);
6377
+ }
5673
6378
  return;
5674
6379
  }
5675
6380
  if (site.kind === "title") {
@@ -5678,7 +6383,7 @@ var ClientGenerator = class {
5678
6383
  }
5679
6384
  if (site.kind === "provide") {
5680
6385
  const context = site.extra[0];
5681
- this.emit(`export function ${name("u")}($$s) {\n $$b.provide($$s, ${copy(this.file.source, context.start, context.end)}, ${expression()});\n}`);
6386
+ this.emit(`export function ${name("u")}($$s) {\n $$b.updateContext($$s, ${copy(this.file.source, context.start, context.end)}, ${expression()});\n}`);
5682
6387
  return;
5683
6388
  }
5684
6389
  if (site.kind === "style") {
@@ -5703,7 +6408,10 @@ var ClientGenerator = class {
5703
6408
  return;
5704
6409
  }
5705
6410
  if (attribute.kind === "spread") this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${expression()});\n}`);
5706
- else if (attribute.kind === "value") this.emit(`export function ${name("u")}($$s) {\n $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${expression()});\n}`);
6411
+ else if (attribute.kind === "value") {
6412
+ const value = (attribute.name === "class" ? classes(attribute.value.ast) : void 0) ?? expression();
6413
+ this.emit(`export function ${name("u")}($$s) {\n $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value});\n}`);
6414
+ }
5707
6415
  }
5708
6416
  findInsert(site) {
5709
6417
  for (const target of this.plan.anchors.keys()) if ("expression" in target && target.kind === "insert" && target.expression.ast === site.node) return target;
@@ -5756,9 +6464,12 @@ var ClientGenerator = class {
5756
6464
  case "portal": {
5757
6465
  if (!block.target) return;
5758
6466
  const body = this.plan.bodyScopes.get(block.body);
5759
- this.emit(`export function ${fn}($$s) {\n $$b.portal($$s, ${header(0)}, r${body.id}, [${body.id}]);\n}`);
6467
+ this.emit(`export function ${fn}($$s) {\n $$b.portalTo($$s, ${header(0)}, r${body.id}, [${body.id}]);\n}`);
5760
6468
  return;
5761
6469
  }
6470
+ case "offscreen":
6471
+ this.emit(`export function ${fn}($$s) {\n $$b.offscreen($$s, ${anchor}, ${header(0)}, ${this.renderName(block.body)}, ${this.plan.bodyScopes.get(block.body).id});\n}`);
6472
+ return;
5762
6473
  case "key":
5763
6474
  this.emit(`export function ${fn}($$s) {\n $$b.rekey($$s, ${anchor}, ${header(0)}, ${this.renderName(block.body)}, [${this.kinds([block.body]).join(", ")}]);\n}`);
5764
6475
  return;
@@ -5798,7 +6509,8 @@ var ClientGenerator = class {
5798
6509
  "switch",
5799
6510
  "for",
5800
6511
  "repeat",
5801
- "key"
6512
+ "key",
6513
+ "offscreen"
5802
6514
  ].includes(node.block.kind)) continue;
5803
6515
  for (const body of blockBodies(node.block)) this.renders.set(this.plan.bodyScopes.get(body), {
5804
6516
  body,
@@ -5846,7 +6558,7 @@ var ClientGenerator = class {
5846
6558
  if (block.kind === "portal" && block.target) {
5847
6559
  const header = this.model.sites.find((site) => site.kind === "block" && site.block === block);
5848
6560
  const target = this.rewriter.rewrite(header, "$$s", instanceScope(this.plan, base));
5849
- this.emit(`export function k${scope.id}($$s) {\n $$b.portal($$s, ${target}, r${scope.id});\n}`);
6561
+ this.emit(`export function k${scope.id}($$s) {\n $$b.portalTo($$s, ${target}, r${scope.id});\n}`);
5850
6562
  }
5851
6563
  if (block.kind === "client") {
5852
6564
  const anchor = this.plan.anchors.get(block);
@@ -6127,7 +6839,7 @@ function compile(source, options = {}) {
6127
6839
  const errors = diagnostics.filter((diagnostic) => diagnostic.severity === "error");
6128
6840
  if (errors.length > 0) fail(errors);
6129
6841
  const plan = createPlan(file, graph, options.path, options.hideNames);
6130
- const styleErrors = plan.styles.diagnostics.filter((diagnostic) => diagnostic.severity === "error");
6842
+ const styleErrors = [...plan.styles.diagnostics, ...plan.diagnostics].filter((diagnostic) => diagnostic.severity === "error");
6131
6843
  if (styleErrors.length > 0) fail(styleErrors);
6132
6844
  const captures = checkCaptures(file, plan);
6133
6845
  if (captures.length > 0) fail(captures);
@@ -6158,6 +6870,9 @@ function compile(source, options = {}) {
6158
6870
  server: server.code,
6159
6871
  client: entry.code,
6160
6872
  parts: Object.fromEntries(Object.entries(parts).map(([name, part]) => [name, part.code])),
6873
+ loaders: client.loaders,
6874
+ table: client.table,
6875
+ clientCode: client.clientCode,
6161
6876
  render: render.code,
6162
6877
  maps: {
6163
6878
  server: server.map,
@@ -6255,7 +6970,7 @@ function report(source, result, liveProps, parents) {
6255
6970
  let elements = 0;
6256
6971
  let inserts = 0;
6257
6972
  const count = (node) => {
6258
- if (node.kind === "element" && !plan.anchors.has(node)) elements++;
6973
+ if (node.kind === "element" && !plan.anchors.has(node) && !node.attributes.some((attribute) => attribute.kind === "event")) elements++;
6259
6974
  else if (node.kind === "insert" && !plan.anchors.has(node)) inserts++;
6260
6975
  };
6261
6976
  forEachNode(result.file.children, count);
@@ -6341,6 +7056,6 @@ function inspect(source, options = {}) {
6341
7056
  };
6342
7057
  }
6343
7058
  //#endregion
6344
- export { buildGraph as A, unmarked as C, resolveRelative as D, forEachNode as E, lookup as F, getLocation as M, analyze$1 as N, summarize as O, isWithin as P, builtin as S, analyzeProjectProps as T, hash as _, CompileError as a, sharedSites as b, generateRender as c, slotIndex as d, blockBodies as f, getComponentName as g, functionId as h, scopeLabel as i, BrumateError as j, parse$1 as k, generateServer as l, createPlan as m, inspect as n, compile as o, clientState as p, report as r, generateClient as s, formatReport as t, instanceScope as u, SHARED_QUERY as v, analyzeProject as w, isReactiveModule as x, generateShared as y };
7059
+ export { summarize as A, resolveFromDisk as C, analyzeProjectProps as D, analyzeProject as E, analyze$1 as F, isWithin as I, lookup as L, buildGraph as M, BrumateError as N, forEachNode as O, getLocation as P, isReactiveModule as S, unmarked as T, getComponentName as _, CompileError as a, generateShared as b, generateClient as c, instanceScope as d, slotIndex as f, functionId as g, createPlan as h, scopeLabel as i, parse$1 as j, resolveRelative as k, generateRender as l, clientState as m, inspect as n, compile as o, blockBodies as p, report as r, DEFAULT_MERGE as s, formatReport as t, generateServer as u, hash as v, builtin as w, sharedSites as x, SHARED_QUERY as y };
6345
7060
 
6346
- //# sourceMappingURL=inspect-CGCWfaEx.js.map
7061
+ //# sourceMappingURL=inspect-BPchdWbU.js.map