brumate 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-C0UCNL3J.js +1643 -0
  4. package/dist/client-C0UCNL3J.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/defer-D0bo1Gqx.js +52 -0
  12. package/dist/defer-D0bo1Gqx.js.map +1 -0
  13. package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
  14. package/dist/devtools-C50VH8gZ.js.map +1 -0
  15. package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
  16. package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
  17. package/dist/events-BKWRqtMg.js +52 -0
  18. package/dist/events-BKWRqtMg.js.map +1 -0
  19. package/dist/{files-DdT84mPy.js → files-Bnn1JqHx.js} +18 -3
  20. package/dist/files-Bnn1JqHx.js.map +1 -0
  21. package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
  22. package/dist/html-bHZbkK-h.js.map +1 -0
  23. package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
  24. package/dist/index.d.ts +77 -29
  25. package/dist/index.js +12 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspect-BPchdWbU.js → inspect-BJtACnQp.js} +784 -82
  28. package/dist/inspect-BJtACnQp.js.map +1 -0
  29. package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
  30. package/dist/loader-B18i3_-T.js.map +1 -0
  31. package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
  32. package/dist/navigate-BwuZveDF.js.map +1 -0
  33. package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
  34. package/dist/produce-CWfJ4byV.js.map +1 -0
  35. package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
  36. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  37. package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
  38. package/dist/rpc-B-Zkn6Ch.js.map +1 -0
  39. package/dist/runtime/batch.d.ts +23 -0
  40. package/dist/runtime/batch.js +69 -0
  41. package/dist/runtime/batch.js.map +1 -0
  42. package/dist/runtime/client.d.ts +5 -5
  43. package/dist/runtime/client.js +5 -1345
  44. package/dist/runtime/context.d.ts +2 -2
  45. package/dist/runtime/context.js +1 -1
  46. package/dist/runtime/devtools.d.ts +5 -4
  47. package/dist/runtime/devtools.js +1 -1
  48. package/dist/runtime/env.d.ts +44 -0
  49. package/dist/runtime/env.js +61 -0
  50. package/dist/runtime/env.js.map +1 -0
  51. package/dist/runtime/events.d.ts +27 -0
  52. package/dist/runtime/events.js +1 -0
  53. package/dist/runtime/hot.d.ts +1 -1
  54. package/dist/runtime/html.d.ts +2 -2
  55. package/dist/runtime/html.js +1 -1
  56. package/dist/runtime/loader.d.ts +2 -2
  57. package/dist/runtime/loader.js +2 -2
  58. package/dist/runtime/routes.d.ts +2 -21
  59. package/dist/runtime/routes.js +31 -1
  60. package/dist/runtime/routes.js.map +1 -1
  61. package/dist/runtime/server.d.ts +6 -5
  62. package/dist/runtime/server.js +5 -6
  63. package/dist/runtime/signals.d.ts +22 -1
  64. package/dist/runtime/signals.js +29 -1
  65. package/dist/runtime/signals.js.map +1 -1
  66. package/dist/runtime/static-loader.d.ts +2 -2
  67. package/dist/runtime/static-loader.js +1 -1
  68. package/dist/runtime/testing.d.ts +46 -5
  69. package/dist/runtime/testing.js +240 -33
  70. package/dist/runtime/testing.js.map +1 -1
  71. package/dist/secrets-BxagsJxJ.js +23 -0
  72. package/dist/secrets-BxagsJxJ.js.map +1 -0
  73. package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
  74. package/dist/server-BqfM95r1.js +2762 -0
  75. package/dist/server-BqfM95r1.js.map +1 -0
  76. package/dist/skew-FRmAy9iy.js +49 -0
  77. package/dist/skew-FRmAy9iy.js.map +1 -0
  78. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  79. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
  80. package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
  81. package/dist/static-loader-DOygOFj5.js.map +1 -0
  82. package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
  83. package/dist/stream-JaMHMdBD.js.map +1 -0
  84. package/dist/vite.d.ts +42 -1
  85. package/dist/vite.js +435 -55
  86. package/dist/vite.js.map +1 -1
  87. package/package.json +15 -2
  88. package/types.d.ts +9 -1
  89. package/dist/client-routes-DakuM32C.js.map +0 -1
  90. package/dist/context-BG8KCF3v.js +0 -15
  91. package/dist/context-BG8KCF3v.js.map +0 -1
  92. package/dist/context-aeo9esY9.d.ts +0 -16
  93. package/dist/devtools-BKjnHrnv.js.map +0 -1
  94. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  95. package/dist/files-DdT84mPy.js.map +0 -1
  96. package/dist/html-DEeoepg3.js.map +0 -1
  97. package/dist/inspect-BPchdWbU.js.map +0 -1
  98. package/dist/loader-Dc9OwY5I.js.map +0 -1
  99. package/dist/navigate-CzLjnoPH.js.map +0 -1
  100. package/dist/produce-BRGHP7e0.js.map +0 -1
  101. package/dist/rpc-9fSqL_YK.js.map +0 -1
  102. package/dist/runtime/client.js.map +0 -1
  103. package/dist/server-DZsgnPKS.js +0 -1615
  104. package/dist/server-DZsgnPKS.js.map +0 -1
  105. package/dist/shared-CWYOd0H3.js +0 -40
  106. package/dist/shared-CWYOd0H3.js.map +0 -1
  107. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  108. package/dist/stream-bgNCMcaA.js.map +0 -1
@@ -1,4 +1,5 @@
1
- import { u as insertValue } from "./html-DEeoepg3.js";
1
+ import { t as KEY_NAMES } from "./events-BKWRqtMg.js";
2
+ import { u as insertValue } from "./html-bHZbkK-h.js";
2
3
  import { parseSync } from "oxc-parser";
3
4
  import { parse } from "postcss";
4
5
  import selectorParser from "postcss-selector-parser";
@@ -11,6 +12,8 @@ const MACROS = /* @__PURE__ */ new Set([
11
12
  "$signal",
12
13
  "$memo",
13
14
  "$optimistic",
15
+ "$debounced",
16
+ "$throttled",
14
17
  "$effect",
15
18
  "$client",
16
19
  "$untrack",
@@ -18,6 +21,8 @@ const MACROS = /* @__PURE__ */ new Set([
18
21
  "$isPending",
19
22
  "$setContext",
20
23
  "$getContext",
24
+ "$route",
25
+ "$navigation",
21
26
  "$id",
22
27
  "$title",
23
28
  "$action"
@@ -243,15 +248,34 @@ const REACTIVE = /* @__PURE__ */ new Set([
243
248
  "item",
244
249
  "action"
245
250
  ]);
251
+ /** The module of the wrappers of event handlers, which the compiler reads. */
252
+ const EVENTS_MODULE = "brumate/events";
253
+ /** The wrappers that `brumate/events` exports. */
254
+ const WRAPPERS$1 = /* @__PURE__ */ new Set([
255
+ "prevent",
256
+ "stop",
257
+ "once",
258
+ "capture"
259
+ ]);
260
+ /** The events whose `prevent` can name keys. */
261
+ const KEY_EVENTS = /* @__PURE__ */ new Set([
262
+ "keydown",
263
+ "keyup",
264
+ "keypress"
265
+ ]);
246
266
  const COMPILE_TIME_FUNCTIONS = MACROS;
247
267
  const MISPLACED = {
248
268
  $setContext: "Call $setContext at the top level of a script",
249
269
  $title: "Call $title at the top level of a script",
250
270
  $id: "Create an ID with \"const name = $id()\" at the top level of a script",
251
271
  $getContext: "Read a context with \"const name = $getContext(Context)\" at the top level of a script",
272
+ $route: "Read the route with \"const name = $route()\" at the top level of a script",
273
+ $navigation: "Read the navigation with \"const name = $navigation()\" at the top level of a script",
252
274
  $props: "Call $props() as the value of a const in the component script",
253
275
  $signal: "Declare a signal with \"let name = $signal(value)\" at the top level of a script",
254
276
  $memo: "Declare a memo with \"const name = $memo(value)\" at the top level of a script",
277
+ $debounced: "Declare a debounced value with \"const name = $debounced(value, ms)\" at the top level of a script",
278
+ $throttled: "Declare a throttled value with \"const name = $throttled(value, ms)\" at the top level of a script",
255
279
  $optimistic: "Declare an optimistic value with \"let name = $optimistic(source)\" at the top level of a script",
256
280
  $action: "Declare the result of a form with \"const name = $action(serverFunction)\" at the top level of a script",
257
281
  $effect: "Call $effect at the top level of a script",
@@ -311,7 +335,7 @@ function hasUseServer(fn) {
311
335
  return false;
312
336
  }
313
337
  /** Returns the name of a compile-time function that `node` calls, if any. */
314
- function calleeName(node) {
338
+ function calleeName$1(node) {
315
339
  if (node?.type === "CallExpression" && node.callee.type === "Identifier") return node.callee.name;
316
340
  }
317
341
  function range(node) {
@@ -439,6 +463,44 @@ var Analyzer = class {
439
463
  site.range = range(expression);
440
464
  return site;
441
465
  }
466
+ /**
467
+ * Reads the wrappers of `brumate/events` around a handler, such as
468
+ * `prevent(move, 'Enter')`, into the modifiers that `b-on` holds, so the
469
+ * loader applies them before the handler's code loads. A modifier in the
470
+ * attribute name, such as `onSubmit:prevent`, still works, with a warning.
471
+ */
472
+ readWrappers(site, attribute, scope) {
473
+ if (attribute.modifiers.length > 0) {
474
+ const [first] = attribute.modifiers;
475
+ this.report("warning", `${attribute.name}:${first} is replaced by ${attribute.name}=(${first === "passive" ? "handler" : `${first}(handler)`}) from brumate/events${first === "passive" ? ", since listeners are passive unless a handler prevents" : ""}`, attribute);
476
+ }
477
+ const modifiers = [];
478
+ let node = attribute.handler.ast;
479
+ for (;;) {
480
+ while (node.type === "ParenthesizedExpression") node = node.expression;
481
+ if (node.type !== "CallExpression" || node.callee.type !== "Identifier") break;
482
+ const imported = lookup(scope, node.callee.name)?.imported;
483
+ const name = imported?.source === EVENTS_MODULE ? imported.name : void 0;
484
+ if (name === void 0 || !WRAPPERS$1.has(name)) break;
485
+ const [handler, ...rest] = node.arguments;
486
+ if (!handler || name !== "prevent" && rest.length > 0) {
487
+ this.report("error", `${name} takes a handler`, node);
488
+ break;
489
+ }
490
+ if (rest.length > 0) {
491
+ const keys = rest.map((key) => key.type === "Literal" && typeof key.value === "string" ? key.value : void 0);
492
+ const wrong = rest.find((_, index) => {
493
+ const key = keys[index];
494
+ return key === void 0 || !(KEY_NAMES.includes(key) || /^[A-Za-z0-9]$/.test(key));
495
+ });
496
+ if (!KEY_EVENTS.has(attribute.event)) this.report("error", "Only prevent of a keyboard event takes keys, such as onKeyDown", node);
497
+ else if (wrong) this.report("error", "Name each key of prevent as a string of its event.key, such as 'ArrowDown', 'Space' or 'a'", wrong);
498
+ modifiers.push(`prevent(${keys.join(",")})`);
499
+ } else modifiers.push(name);
500
+ node = handler;
501
+ }
502
+ if (modifiers.length > 0) site.modifiers = modifiers;
503
+ }
442
504
  declareFunction(name, fn, scope, at) {
443
505
  const server = hasUseServer(fn);
444
506
  const kind = server ? "server-function" : "function";
@@ -517,11 +579,14 @@ var Analyzer = class {
517
579
  this.createSite("setup", scope, statement, "setup");
518
580
  break;
519
581
  case "ExpressionStatement": {
520
- const name = calleeName(statement.expression);
582
+ const name = calleeName$1(statement.expression);
521
583
  if (name === "$title") {
522
584
  const call = statement.expression;
523
585
  if (call.arguments.length !== 1) this.report("error", "$title takes one argument, the title", call);
524
- else this.createSite("title", scope, call.arguments[0], "title");
586
+ else {
587
+ this.report("warning", "$title is replaced by <title> in #head, such as #head { <title>{`${count} left`}</title> }, and goes in a later version", call);
588
+ this.createSite("title", scope, call.arguments[0], "title");
589
+ }
525
590
  } else if (name === "$setContext") this.declareProvide(statement.expression, scope);
526
591
  else if (name === "$effect" || name === "$client") this.declareEffect(statement.expression, name, scope);
527
592
  else this.createSite("setup", scope, statement, "setup");
@@ -536,9 +601,12 @@ var Analyzer = class {
536
601
  return type === "TSInterfaceDeclaration" || type === "TSTypeAliasDeclaration";
537
602
  }
538
603
  declareVariable(declarator, kind, scope, isComponent) {
539
- const init = declarator.init;
540
604
  const id = declarator.id;
541
- const name = calleeName(init);
605
+ const awaited = declarator.init?.type === "AwaitExpression" ? declarator.init : void 0;
606
+ const awaitedName = awaited && calleeName$1(awaited.argument);
607
+ if (awaited && awaitedName !== void 0 && MACROS.has(awaitedName) && awaitedName !== "$memo") this.report("error", `await works with $memo, not ${awaitedName}`, awaited);
608
+ const init = awaitedName === "$memo" ? awaited.argument : declarator.init;
609
+ const name = calleeName$1(init);
542
610
  const call = init;
543
611
  if (name === "$props") {
544
612
  if (!isComponent) this.report("error", "$props() can only be called in the component script", declarator);
@@ -568,6 +636,15 @@ var Analyzer = class {
568
636
  declaration.idIndex = [...scope.declarations.values()].filter((item) => item.idIndex !== void 0).length;
569
637
  return;
570
638
  }
639
+ if (name === "$route" || name === "$navigation") {
640
+ if (kind !== "const" || id.type !== "Identifier") {
641
+ this.report("error", MISPLACED[name], declarator);
642
+ return;
643
+ }
644
+ if (name === "$navigation" ? call.arguments.length > 0 : call.arguments.length > 1) this.report("error", name === "$navigation" ? "$navigation takes no arguments" : "$route takes at most one argument, the path of the route", call);
645
+ this.addDeclaration(scope, id.name, "context", id);
646
+ return;
647
+ }
571
648
  if (name === "$getContext") {
572
649
  if (kind !== "const" || id.type !== "Identifier") {
573
650
  this.report("error", "Read a context with \"const name = $getContext(Context)\"", declarator);
@@ -593,6 +670,27 @@ var Analyzer = class {
593
670
  declaration.action = argument.name;
594
671
  return;
595
672
  }
673
+ if (name === "$debounced" || name === "$throttled") {
674
+ if (kind !== "const") this.report("error", `Declare ${name} with const`, declarator);
675
+ if (id.type !== "Identifier") {
676
+ this.report("error", `${name} cannot be destructured`, id);
677
+ return;
678
+ }
679
+ const [argument, wait] = call.arguments;
680
+ const declaration = this.addDeclaration(scope, id.name, "memo", id);
681
+ if (!argument || call.arguments.length !== 2) {
682
+ this.report("error", `${name} takes a value and a wait in milliseconds`, call);
683
+ return;
684
+ }
685
+ const ms = wait?.type === "Literal" && typeof wait.value === "number" ? wait.value : NaN;
686
+ if (!(ms >= 0 && ms <= 2147483647)) this.report("error", `The wait of ${name} must be a number of milliseconds, such as 300`, wait);
687
+ declaration.timing = {
688
+ kind: name === "$debounced" ? "debounced" : "throttled",
689
+ ms
690
+ };
691
+ declaration.site = this.createSite("memo", scope, argument, `memo ${id.name}`, { declaration });
692
+ return;
693
+ }
596
694
  if (name === "$signal" || name === "$memo" || name === "$optimistic") {
597
695
  const expected = name === "$memo" ? "const" : "let";
598
696
  if (kind !== expected) this.report("error", `Declare ${name} with ${expected}`, declarator);
@@ -611,6 +709,7 @@ var Analyzer = class {
611
709
  return;
612
710
  }
613
711
  const declaration = this.addDeclaration(scope, id.name, "memo", id);
712
+ if (awaited && name === "$memo") declaration.awaited = true;
614
713
  if (!argument) {
615
714
  this.report("error", `${name} needs a value`, call);
616
715
  return;
@@ -745,10 +844,13 @@ var Analyzer = class {
745
844
  this.visitNodes(node.children, scope);
746
845
  break;
747
846
  case "listener":
748
- for (const attribute of node.attributes) this.createExpressionSite("event", scope, attribute.handler, `event ${node.target}.${attribute.event}`, {
749
- owner: node,
750
- event: attribute
751
- });
847
+ for (const attribute of node.attributes) {
848
+ const site = this.createExpressionSite("event", scope, attribute.handler, `event ${node.target}.${attribute.event}`, {
849
+ owner: node,
850
+ event: attribute
851
+ });
852
+ this.readWrappers(site, attribute, scope);
853
+ }
752
854
  break;
753
855
  default: this.visitBlock(node, scope);
754
856
  }
@@ -764,12 +866,14 @@ var Analyzer = class {
764
866
  case "value":
765
867
  this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.value, `${isComponent ? "prop" : "attribute"} ${tag}.${attribute.name}`, { owner: node });
766
868
  break;
767
- case "event":
768
- this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
869
+ case "event": {
870
+ const site = this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
769
871
  owner: node,
770
872
  event: isComponent ? void 0 : attribute
771
873
  });
874
+ if (!isComponent) this.readWrappers(site, attribute, scope);
772
875
  break;
876
+ }
773
877
  case "ref":
774
878
  if (node.kind === "element") this.refs.push({
775
879
  attribute,
@@ -847,7 +951,9 @@ var Analyzer = class {
847
951
  this.visitBody(block.body, scope, block);
848
952
  break;
849
953
  case "client":
954
+ case "defer":
850
955
  this.visitBody(block.body, scope, block);
956
+ if (block.fallback) this.visitBody(block.fallback, scope, block);
851
957
  break;
852
958
  case "offscreen":
853
959
  this.header(block, scope, block.visible, "offscreen");
@@ -956,6 +1062,7 @@ var Resolver = class {
956
1062
  this.site.calls.add(declaration);
957
1063
  if (this.untracked === 0) this.site.trackedCalls.add(declaration);
958
1064
  }
1065
+ return reference;
959
1066
  }
960
1067
  visitChildren(node) {
961
1068
  for (const [key, child] of children(node)) if (!TYPE_KEYS.has(key)) this.visit(child);
@@ -1050,10 +1157,20 @@ var Resolver = class {
1050
1157
  case "BreakStatement":
1051
1158
  case "ContinueStatement":
1052
1159
  case "MetaProperty": return;
1053
- case "AwaitExpression":
1160
+ case "AwaitExpression": {
1161
+ const argument = node.argument;
1162
+ if (argument.type === "Identifier") {
1163
+ const declaration = this.isLocal(argument.name) ? void 0 : lookup(this.site.scope, argument.name);
1164
+ if (declaration?.kind === "memo" || declaration?.kind === "async-memo") {
1165
+ const reference = this.reference(argument, "read");
1166
+ if (reference) reference.await = range(node);
1167
+ return;
1168
+ }
1169
+ }
1054
1170
  if (this.functionDepth === 0) this.site.awaits = true;
1055
- this.visit(node.argument);
1171
+ this.visit(argument);
1056
1172
  return;
1173
+ }
1057
1174
  case "CallExpression": {
1058
1175
  if (this.site.kind === "server-function" && node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier" && node.callee.property.name === "refresh" && node.arguments[0]?.type === "Identifier") {
1059
1176
  const target = lookup(this.site.scope, node.arguments[0].name);
@@ -1277,13 +1394,37 @@ function isLiveProp(declaration, liveProps) {
1277
1394
  function resetUsed(model, block, reached) {
1278
1395
  return model.declarations.some((declaration) => declaration.kind === "reset" && declaration.block === block && declaration.reads.some((read) => reached.has(read.site)));
1279
1396
  }
1397
+ /** Sites whose code runs in the browser after the page renders, and can throw there. */
1398
+ const CLIENT_CODE = /* @__PURE__ */ new Set([
1399
+ "event",
1400
+ "effect",
1401
+ "client"
1402
+ ]);
1403
+ /**
1404
+ * True if the body of a `#try` holds code that runs in the browser: a
1405
+ * handler, an effect, a `$client` callback or a memo that loads. An error
1406
+ * in it renders the `#catch` body in the browser, so both bodies ship.
1407
+ */
1408
+ function tryCatchesClient(model, block) {
1409
+ const body = model.scopes.find((scope) => scope.block === block && scope.body === block.body);
1410
+ return body !== void 0 && model.sites.some((site) => (CLIENT_CODE.has(site.kind) || site.kind === "memo" && site.declaration?.kind === "async-memo") && isWithin(site.scope, body));
1411
+ }
1280
1412
  /** True if a site's expression is a function, such as a function passed as a prop. */
1413
+ /** True for a site whose value is a `#template`, such as the prop `item=option`. */
1414
+ function isTemplateValue(site) {
1415
+ return site.node.type === "Identifier" && lookup(site.scope, site.node.name)?.kind === "template";
1416
+ }
1281
1417
  function isFunctionValue(site) {
1282
- const node = site.node;
1418
+ let node = site.node;
1419
+ for (;;) {
1420
+ while (node.type === "ParenthesizedExpression") node = node.expression;
1421
+ if (node.type !== "CallExpression" || node.callee.type !== "Identifier" || lookup(site.scope, node.callee.name)?.imported?.source !== "brumate/events" || !node.arguments[0]) break;
1422
+ node = node.arguments[0];
1423
+ }
1283
1424
  if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") return true;
1284
1425
  if (node.type === "Identifier") {
1285
1426
  const kind = lookup(site.scope, node.name)?.kind;
1286
- return kind === "function" || kind === "server-function";
1427
+ return kind === "function" || kind === "server-function" || kind === "template";
1287
1428
  }
1288
1429
  return false;
1289
1430
  }
@@ -1389,7 +1530,7 @@ function buildGraph(model, options = {}) {
1389
1530
  if (created.has(scope)) continue;
1390
1531
  const block = scope.block;
1391
1532
  const parentCreated = scope.parent !== void 0 && created.has(scope.parent);
1392
- const blockLive = scope.kind === "body" && block !== void 0 && (block.kind === "client" || block.kind === "portal" && block.target !== void 0 || block.kind === "try" && resetUsed(model, block, reached) || (headers.get(block) ?? []).some((node) => live.has(node)) || block.kind === "try" && scope.body === block.fallback && tryChanges(block));
1533
+ const blockLive = scope.kind === "body" && block !== void 0 && (block.kind === "client" && scope.body === block.body || block.kind === "portal" && block.target !== void 0 || block.kind === "try" && (resetUsed(model, block, reached) || tryCatchesClient(model, block)) || (headers.get(block) ?? []).some((node) => live.has(node)) || block.kind === "try" && scope.body === block.fallback && tryChanges(block));
1393
1534
  const templateUsed = scope.kind === "template" && templateCallChanges(scope);
1394
1535
  if (parentCreated || blockLive || templateUsed) created.add(scope);
1395
1536
  }
@@ -1426,6 +1567,24 @@ function buildGraph(model, options = {}) {
1426
1567
  message: "This $effect reads no value that changes on the client, so it never runs",
1427
1568
  range: site.range
1428
1569
  });
1570
+ for (const scope of model.scopes) {
1571
+ const block = scope.block;
1572
+ if (block?.kind !== "defer" || scope.body !== block.body) continue;
1573
+ let message;
1574
+ for (let outer = scope.parent; outer && !message; outer = outer.parent) {
1575
+ const around = outer.block;
1576
+ if (around?.kind === "client" && outer.body === around.body) message = "#defer cannot be inside a #client body";
1577
+ else if (created.has(outer)) message = "#defer cannot be in markup that the browser renders";
1578
+ }
1579
+ if (message) diagnostics.push({
1580
+ severity: "error",
1581
+ message,
1582
+ range: {
1583
+ start: block.start,
1584
+ end: block.start + 6
1585
+ }
1586
+ });
1587
+ }
1429
1588
  return {
1430
1589
  model,
1431
1590
  nodes,
@@ -1985,6 +2144,7 @@ var Parser = class {
1985
2144
  const name = parts[0];
1986
2145
  const modifiers = parts.slice(1);
1987
2146
  for (const modifier of modifiers) if (!MODIFIERS.has(modifier)) this.fail(`Unknown event modifier ":${modifier}"`, start);
2147
+ if (owner === "component" && modifiers.length > 0) this.fail(`Modifiers apply to elements. Put ":${modifiers[0]}" on the element that the component renders`, start);
1988
2148
  if (this.peek() !== "=") this.fail("Expected an event handler", this.pos);
1989
2149
  this.pos++;
1990
2150
  const value = this.parseValue();
@@ -2351,21 +2511,25 @@ var Parser = class {
2351
2511
  body: this.parseBody("portal")
2352
2512
  };
2353
2513
  }
2354
- case "client": {
2355
- const header = this.parseHeader("client", false);
2514
+ case "client":
2515
+ case "defer": {
2516
+ const header = this.parseHeader(keyword, false);
2356
2517
  let trigger = "visible";
2357
2518
  if (header) {
2358
2519
  const code = this.source.slice(header.start, header.end).trim();
2359
2520
  const value = code.slice(1, -1);
2360
- if (!/^(['"]).*\1$/.test(code) || !CLIENT_TRIGGERS.has(value)) this.fail("The trigger of #client must be \"visible\", \"idle\" or \"load\"", header.start);
2521
+ if (!/^(['"]).*\1$/.test(code) || !CLIENT_TRIGGERS.has(value)) this.fail(`The trigger of #${keyword} must be "visible", "idle" or "load"`, header.start);
2361
2522
  trigger = value;
2362
2523
  }
2524
+ const body = this.parseBody(keyword);
2525
+ const fallback = this.parseBranch("else") ? this.parseBody("else") : void 0;
2363
2526
  return {
2364
- kind: "client",
2527
+ kind: keyword,
2365
2528
  start,
2366
2529
  end: this.pos,
2367
2530
  trigger,
2368
- body: this.parseBody("client")
2531
+ body,
2532
+ fallback
2369
2533
  };
2370
2534
  }
2371
2535
  case "offscreen": {
@@ -2380,7 +2544,6 @@ var Parser = class {
2380
2544
  body
2381
2545
  };
2382
2546
  }
2383
- case "defer": return this.fail("#defer is reserved for a future block", start);
2384
2547
  default: return this.fail(`Unknown block #${keyword}`, start);
2385
2548
  }
2386
2549
  }
@@ -2501,12 +2664,13 @@ function childrenOf(node) {
2501
2664
  case "switch": return [...node.cases.flatMap((branch) => branch.body.children), ...node.fallback?.children ?? []];
2502
2665
  case "for":
2503
2666
  case "repeat":
2504
- case "loading": return [...node.body.children, ...node.fallback?.children ?? []];
2667
+ case "loading":
2668
+ case "client":
2669
+ case "defer": return [...node.body.children, ...node.fallback?.children ?? []];
2505
2670
  case "try": return [...node.body.children, ...node.fallback.children];
2506
2671
  case "key":
2507
2672
  case "portal":
2508
2673
  case "head":
2509
- case "client":
2510
2674
  case "offscreen": return node.body.children;
2511
2675
  default: return [];
2512
2676
  }
@@ -2746,6 +2910,16 @@ const SENDABLE = /* @__PURE__ */ new Set([
2746
2910
  "Date",
2747
2911
  "URL",
2748
2912
  "URLSearchParams",
2913
+ "Headers",
2914
+ "FormData",
2915
+ "Request",
2916
+ "Response",
2917
+ "ReadableStream",
2918
+ "Event",
2919
+ "CustomEvent",
2920
+ "DOMException",
2921
+ "AbortSignal",
2922
+ "ImageData",
2749
2923
  "Map",
2750
2924
  "Set",
2751
2925
  "Promise",
@@ -2775,7 +2949,12 @@ const SENDABLE = /* @__PURE__ */ new Set([
2775
2949
  "Boolean"
2776
2950
  ]);
2777
2951
  /** Compile-time functions whose argument is the value, such as `$signal(new Foo())`. */
2778
- const WRAPPERS = /* @__PURE__ */ new Set(["$signal", "$memo"]);
2952
+ const WRAPPERS = /* @__PURE__ */ new Set([
2953
+ "$signal",
2954
+ "$memo",
2955
+ "$debounced",
2956
+ "$throttled"
2957
+ ]);
2779
2958
  /** The value that a declaration holds, by the offset of its name. */
2780
2959
  function initializers(file) {
2781
2960
  const result = /* @__PURE__ */ new Map();
@@ -2820,6 +2999,66 @@ function checkCaptures(file, plan) {
2820
2999
  return diagnostics;
2821
3000
  }
2822
3001
  //#endregion
3002
+ //#region src/env-check.ts
3003
+ /** The property that a read of `env` reads, such as `DATABASE_URL` for `env.DATABASE_URL`. */
3004
+ function propertyAt(node, at) {
3005
+ if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.start === at) {
3006
+ if (node.computed) return node.property.type === "Literal" ? String(node.property.value) : null;
3007
+ return node.property.type === "Identifier" ? node.property.name : null;
3008
+ }
3009
+ for (const [, child] of children(node)) {
3010
+ const found = propertyAt(child, at);
3011
+ if (found !== void 0) return found;
3012
+ }
3013
+ }
3014
+ /** The server variable that a read reads, or `*` for a read of the whole object. */
3015
+ function serverRead(read, server) {
3016
+ const nodes = [read.site.node, ...read.site.extra ?? []];
3017
+ for (const node of nodes) {
3018
+ const property = propertyAt(node, read.range.start);
3019
+ if (property === void 0) continue;
3020
+ if (property === null) return "*";
3021
+ return server.includes(property) ? property : void 0;
3022
+ }
3023
+ return "*";
3024
+ }
3025
+ /** Errors for server variables that code in the browser reads, or that the page state would send. */
3026
+ function checkEnv(file, plan, envImport) {
3027
+ const diagnostics = [];
3028
+ const values = initializers(file);
3029
+ const slots = /* @__PURE__ */ new Set();
3030
+ for (const layout of plan.scopes.values()) for (const declaration of layout.slots) slots.add(declaration);
3031
+ for (const declaration of plan.graph.model.declarations) {
3032
+ if (!declaration.imported) continue;
3033
+ const server = envImport(declaration.imported.source, declaration.imported.name);
3034
+ if (!server) continue;
3035
+ const name = declaration.name;
3036
+ for (const read of declaration.reads) {
3037
+ const variable = serverRead(read, server);
3038
+ if (variable === void 0) continue;
3039
+ const what = variable === "*" ? `${name}, with its server variables,` : `${name}.${variable}, a server variable,`;
3040
+ if (plan.graph.reached.has(read.site)) {
3041
+ diagnostics.push({
3042
+ severity: "error",
3043
+ message: `${what} is read by code that runs in the browser (${read.site.label}). Read it in a server function`,
3044
+ range: read.range
3045
+ });
3046
+ continue;
3047
+ }
3048
+ const holder = [...slots].find((slot) => {
3049
+ const init = values.get(slot.range.start);
3050
+ return init && read.range.start >= init.start && read.range.end <= init.end;
3051
+ });
3052
+ if (holder) diagnostics.push({
3053
+ severity: "error",
3054
+ message: `"${holder.name}" holds ${what} and code that runs in the browser reads it. Keep server variables out of values that the browser reads`,
3055
+ range: read.range
3056
+ });
3057
+ }
3058
+ }
3059
+ return diagnostics;
3060
+ }
3061
+ //#endregion
2823
3062
  //#region src/sourcemap.ts
2824
3063
  const OPEN = "";
2825
3064
  const CLOSE = "";
@@ -3537,7 +3776,18 @@ var Patch = class {
3537
3776
  return result + copy(this.source, position, end);
3538
3777
  }
3539
3778
  };
3779
+ /** The name of the function that a call expression calls, when it is a plain name. */
3780
+ function calleeName(node) {
3781
+ return node.callee.type === "Identifier" ? node.callee.name : void 0;
3782
+ }
3540
3783
  /** The variable that holds a memo on the server, which can be a promise. */
3784
+ /** The compile-time functions that declare a memo of their first argument. The others are options. */
3785
+ const MEMOS = /* @__PURE__ */ new Set([
3786
+ "$memo",
3787
+ "$optimistic",
3788
+ "$debounced",
3789
+ "$throttled"
3790
+ ]);
3541
3791
  function promiseName(name) {
3542
3792
  return `$$p_${name}`;
3543
3793
  }
@@ -3550,8 +3800,26 @@ function promiseName(name) {
3550
3800
  */
3551
3801
  function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE__ */ new Set()) {
3552
3802
  const sitesByNode = /* @__PURE__ */ new Map();
3553
- for (const site of sites) sitesByNode.set(site.node, site);
3803
+ const awaits = /* @__PURE__ */ new Map();
3804
+ const replaced = /* @__PURE__ */ new Set();
3805
+ for (const site of sites) {
3806
+ sitesByNode.set(site.node, site);
3807
+ for (const read of site.reads) if (read.await) awaits.set(read.await.start, read);
3808
+ }
3554
3809
  const visit = (node) => {
3810
+ if (node.type === "AwaitExpression") {
3811
+ const argument = node.argument;
3812
+ if (argument.type === "CallExpression" && calleeName(argument) === "$memo") {
3813
+ patch.replace(node.start, argument.start, "");
3814
+ visit(argument);
3815
+ return;
3816
+ }
3817
+ const read = awaits.get(node.start);
3818
+ if (read && !replaced.has(read)) {
3819
+ patch.replace(node.start, node.end, read.declaration.name);
3820
+ return;
3821
+ }
3822
+ }
3555
3823
  if (node.type === "CallExpression" && node.callee.type === "Identifier") {
3556
3824
  const name = node.callee.name;
3557
3825
  const argument = node.arguments[0];
@@ -3573,16 +3841,20 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
3573
3841
  for (const rest of node.arguments.slice(1)) visit(rest);
3574
3842
  return;
3575
3843
  }
3576
- if (name === "$signal" || name === "$memo" || name === "$optimistic" || name === "$untrack") {
3844
+ if (MEMOS.has(name) || name === "$signal" || name === "$untrack") {
3577
3845
  if (!argument) {
3578
3846
  patch.replace(node.start, node.end, "undefined");
3579
3847
  return;
3580
3848
  }
3581
- const site = name === "$memo" || name === "$optimistic" ? sitesByNode.get(argument) : void 0;
3849
+ const site = MEMOS.has(name) ? sitesByNode.get(argument) : void 0;
3582
3850
  const declaration = site?.declaration && !inline.has(site.declaration) ? site.declaration : void 0;
3583
3851
  if (declaration && mode === "server") patch.replace(declaration.range.start, declaration.range.end, promiseName(declaration.name));
3584
3852
  if (declaration && mode === "server") {
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)})`);
3853
+ 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")) {
3854
+ const range = read.await ?? read.range;
3855
+ patch.replace(range.start, range.end, `$$b.read(${promiseName(read.declaration.name)})`);
3856
+ replaced.add(read);
3857
+ }
3586
3858
  patch.replace(node.start, argument.start, site.awaits ? "$$b.memo(async () => (" : "$$b.memo(() => (");
3587
3859
  patch.replace(argument.end, node.end, "), $$ctx)");
3588
3860
  } else if (site?.awaits) {
@@ -4120,7 +4392,8 @@ function createPlan(file, graph, path, hideNames = false) {
4120
4392
  plan.needsId = true;
4121
4393
  };
4122
4394
  const symbols = /* @__PURE__ */ new Map();
4123
- for (const site of model.sites) if (site.kind === "event" || site.kind === "prop" && isFunctionValue(site)) symbols.set(site, `h${site.id}`);
4395
+ for (const site of model.sites) if (site.kind === "prop" && isTemplateValue(site)) symbols.set(site, `t${site.id}`);
4396
+ else if (site.kind === "event" || site.kind === "prop" && isFunctionValue(site)) symbols.set(site, `h${site.id}`);
4124
4397
  else if (site.kind === "client") {
4125
4398
  symbols.set(site, `c${site.id}`);
4126
4399
  anchor(site.scope, site);
@@ -4228,7 +4501,7 @@ function createPlan(file, graph, path, hideNames = false) {
4228
4501
  };
4229
4502
  const visitBlock = (block, scope, outer) => {
4230
4503
  const portalTarget = block.kind === "portal" && block.target !== void 0;
4231
- const live = block.kind === "client" || portalTarget || block.kind === "try" && resetUsed(model, block, graph.reached) || (headerSites.get(block) ?? []).some((site) => isLiveSite(site));
4504
+ const live = block.kind === "client" || block.kind === "defer" || portalTarget || block.kind === "try" && (resetUsed(model, block, graph.reached) || tryCatchesClient(model, block)) || (headerSites.get(block) ?? []).some((site) => isLiveSite(site));
4232
4505
  if (live) anchor(scope, block);
4233
4506
  if (live && block.kind === "offscreen") scopes.get(bodyScopes.get(block.body)).needsId = true;
4234
4507
  if (block.kind === "portal" || block.kind === "head") scopes.get(bodyScopes.get(block.body)).needsId = true;
@@ -4254,6 +4527,34 @@ function createPlan(file, graph, path, hideNames = false) {
4254
4527
  };
4255
4528
  for (const template of file.templates) visitBody(template.body);
4256
4529
  visitNodes(file.children, model.component);
4530
+ const checkTitles = (nodes, inHead) => {
4531
+ for (const node of nodes) switch (node.kind) {
4532
+ case "element": {
4533
+ const tag = node.tag.toLowerCase();
4534
+ if (tag === "title" && !inHead) diagnostics.push({
4535
+ severity: "error",
4536
+ message: "Put <title> in #head, as <meta> and <link>, such as #head { <title>{`${count} left`}</title> }",
4537
+ range: {
4538
+ start: node.start,
4539
+ end: node.end
4540
+ }
4541
+ });
4542
+ else if (tag !== "head" && tag !== "svg") checkTitles(node.children, inHead);
4543
+ break;
4544
+ }
4545
+ case "component":
4546
+ case "dynamic":
4547
+ case "fragment":
4548
+ checkTitles(node.children, inHead);
4549
+ break;
4550
+ case "text":
4551
+ case "insert":
4552
+ case "listener": break;
4553
+ default: for (const body of blockBodies(node)) checkTitles(body.children, inHead || node.kind === "head");
4554
+ }
4555
+ };
4556
+ for (const template of file.templates) checkTitles(template.body.children, false);
4557
+ checkTitles(file.children, false);
4257
4558
  for (const plan of scopes.values()) {
4258
4559
  if (plan.slots.length > 0) plan.needsId = true;
4259
4560
  if ([...plan.scope.declarations.values()].some((declaration) => declaration.idIndex !== void 0)) plan.needsId = true;
@@ -4305,7 +4606,9 @@ function blockBodies(block) {
4305
4606
  case "switch": return [...block.cases.map((branch) => branch.body), ...block.fallback ? [block.fallback] : []];
4306
4607
  case "for":
4307
4608
  case "repeat":
4308
- case "loading": return [block.body, ...block.fallback ? [block.fallback] : []];
4609
+ case "loading":
4610
+ case "client":
4611
+ case "defer": return [block.body, ...block.fallback ? [block.fallback] : []];
4309
4612
  case "try": return [block.body, block.fallback];
4310
4613
  default: return [block.body];
4311
4614
  }
@@ -4344,30 +4647,55 @@ const DEFERRED_SITES$1 = /* @__PURE__ */ new Set([
4344
4647
  "effect",
4345
4648
  "client"
4346
4649
  ]);
4347
- /** Returns the nearest `#loading` body scope that contains a scope, up to `limit`. */
4650
+ /**
4651
+ * Returns the nearest `#loading` or `#defer` body scope that contains a
4652
+ * scope, up to `limit`. Both render after the rest of the page, so the
4653
+ * page does not wait for the memos that only they read.
4654
+ */
4348
4655
  function loadingBody(scope, limit) {
4349
- for (let current = scope; current && current !== limit; current = current.parent) if (current.block?.kind === "loading" && current.body === current.block.body) return current;
4656
+ for (let current = scope; current && current !== limit; current = current.parent) {
4657
+ const block = current.block;
4658
+ if ((block?.kind === "loading" || block?.kind === "defer") && current.body === block.body) return current;
4659
+ }
4350
4660
  }
4351
4661
  /** Any memo can hold a promise, because its expression can call code that returns one. */
4352
4662
  function isMemo(declaration) {
4353
4663
  return declaration.kind === "memo" || declaration.kind === "async-memo";
4354
4664
  }
4355
4665
  /**
4356
- * Returns the memos that the server awaits where they are declared,
4357
- * because markup or code outside every `#loading` body reads them. The
4358
- * others are awaited by the `#loading` bodies that read them.
4666
+ * The scope whose render waits for a read. A read with `await` inside a
4667
+ * `#loading` body makes the render around the block wait, so it counts as
4668
+ * a read in the scope that holds the block. Inside a `#defer` body, the
4669
+ * request for the body waits, so the read stays where it is. `limit` is
4670
+ * the scope of the declaration, which a read inside it never leaves.
4671
+ */
4672
+ function readScope(read, limit) {
4673
+ const scope = read.site.scope;
4674
+ if (!read.await) return scope;
4675
+ const body = loadingBody(scope, limit);
4676
+ return body?.block?.kind === "loading" ? body.parent : scope;
4677
+ }
4678
+ /**
4679
+ * Returns the memos that the server awaits where they are declared: those
4680
+ * declared with `await $memo(…)`, and those that markup or code outside
4681
+ * every `#loading` body reads, with `await` or without. The others are
4682
+ * awaited by the `#loading` bodies that read them.
4359
4683
  */
4360
4684
  function blockingMemos(plan) {
4361
4685
  const result = /* @__PURE__ */ new Set();
4362
4686
  for (const declaration of plan.graph.model.declarations) {
4363
4687
  if (!isMemo(declaration)) continue;
4688
+ if (declaration.awaited) {
4689
+ result.add(declaration);
4690
+ continue;
4691
+ }
4364
4692
  for (const read of declaration.reads) {
4365
4693
  if (read.range.start === read.range.end) continue;
4366
4694
  const site = read.site;
4367
4695
  if (DEFERRED_SITES$1.has(site.kind) || site.kind === "memo") continue;
4368
4696
  let template = false;
4369
4697
  for (let scope = site.scope; scope; scope = scope.parent) template ||= scope.kind === "template";
4370
- if (template || !loadingBody(site.scope, declaration.scope)) {
4698
+ if (template || !loadingBody(readScope(read, declaration.scope), declaration.scope)) {
4371
4699
  result.add(declaration);
4372
4700
  break;
4373
4701
  }
@@ -4375,18 +4703,62 @@ function blockingMemos(plan) {
4375
4703
  }
4376
4704
  return result;
4377
4705
  }
4378
- /** Returns the memos that a `#loading` body awaits before it renders. */
4706
+ /**
4707
+ * Returns the memos that a `#loading` body waits for before it renders:
4708
+ * the memos that its markup reads, and the memos that a `#loading` body
4709
+ * inside it reads with `await`. Memos that the page or a body around it
4710
+ * waits for are left out.
4711
+ */
4379
4712
  function awaitedMemos(plan, body, blocking) {
4380
4713
  const result = /* @__PURE__ */ new Set();
4381
4714
  for (const site of plan.graph.model.sites) {
4382
- if (DEFERRED_SITES$1.has(site.kind) || loadingBody(site.scope) !== body) continue;
4715
+ if (DEFERRED_SITES$1.has(site.kind)) continue;
4383
4716
  for (const read of site.reads) {
4384
- if (read.range.start === read.range.end) continue;
4717
+ if (read.range.start === read.range.end || loadingBody(readScope(read)) !== body) continue;
4385
4718
  if (isMemo(read.declaration) && !blocking.has(read.declaration)) result.add(read.declaration);
4386
4719
  }
4387
4720
  }
4721
+ const outer = body.parent && loadingBody(body.parent);
4722
+ if (outer) for (const declaration of awaitedMemos(plan, outer, blocking)) result.delete(declaration);
4388
4723
  return [...result];
4389
4724
  }
4725
+ /**
4726
+ * True if the markup of a `#loading` body may wait for something other than
4727
+ * the memos it reads, so the body cannot render in place when those memos
4728
+ * are ready: a child component, a dynamic tag, a template, or an insert of
4729
+ * a prop, which can be a promise or the children of a parent. Bodies that
4730
+ * render later, such as those of a `#loading` or a `#defer` inside it, wait
4731
+ * on their own.
4732
+ */
4733
+ function mayWait(plan, nodes) {
4734
+ const insertWaits = (node) => {
4735
+ const site = plan.graph.model.sites.find((item) => item.node === node.expression.ast);
4736
+ if (!site) return false;
4737
+ for (const read of site.reads) {
4738
+ const kind = read.declaration.kind;
4739
+ if (kind === "prop" || kind === "props-rest" || kind === "template") return true;
4740
+ }
4741
+ return false;
4742
+ };
4743
+ for (const node of nodes) switch (node.kind) {
4744
+ case "component":
4745
+ case "dynamic": return true;
4746
+ case "insert":
4747
+ if (insertWaits(node)) return true;
4748
+ break;
4749
+ case "element":
4750
+ case "fragment":
4751
+ if (mayWait(plan, node.children)) return true;
4752
+ break;
4753
+ case "text":
4754
+ case "listener": break;
4755
+ default: {
4756
+ const bodies = node.kind === "loading" || node.kind === "defer" || node.kind === "client" ? node.fallback ? [node.fallback] : [] : blockBodies(node);
4757
+ for (const body of bodies) if (mayWait(plan, body.children)) return true;
4758
+ }
4759
+ }
4760
+ return false;
4761
+ }
4390
4762
  /** Expressions that run code the compiler cannot see, or that a memo should not hold. */
4391
4763
  const UNSAFE_NODES = /* @__PURE__ */ new Set([
4392
4764
  "CallExpression",
@@ -4526,8 +4898,13 @@ function specialCall(declarator) {
4526
4898
  const init = declarator.init;
4527
4899
  if (init?.type !== "CallExpression" || init.callee.type !== "Identifier") return;
4528
4900
  const name = init.callee.name;
4529
- return name === "$getContext" || name === "$id" ? name : void 0;
4901
+ return name === "$getContext" || name === "$id" || name === "$route" || name === "$navigation" ? name : void 0;
4530
4902
  }
4903
+ /** The contexts that the runtime provides, by the compile-time function that reads them. */
4904
+ const BUILT_IN_CONTEXTS = {
4905
+ $route: "$$b.routeContext",
4906
+ $navigation: "$$b.navigationContext"
4907
+ };
4531
4908
  /** Writes code that renders markup to an HTML string, on the server or on the client. */
4532
4909
  /** The exports of the core that do on the client what the server's render context does. */
4533
4910
  const CLIENT_HELPERS = {
@@ -4546,11 +4923,71 @@ const CLIENT_HELPERS = {
4546
4923
  after: "afterInsert",
4547
4924
  title: "title"
4548
4925
  };
4926
+ /** The named character references that markup reads. Others stay as they are written. */
4927
+ const NAMED = {
4928
+ amp: "&",
4929
+ lt: "<",
4930
+ gt: ">",
4931
+ quot: "\"",
4932
+ apos: "'",
4933
+ nbsp: "\xA0",
4934
+ copy: "©",
4935
+ reg: "®",
4936
+ trade: "™",
4937
+ hellip: "…",
4938
+ mdash: "—",
4939
+ ndash: "–",
4940
+ lsquo: "‘",
4941
+ rsquo: "’",
4942
+ ldquo: "“",
4943
+ rdquo: "”",
4944
+ laquo: "«",
4945
+ raquo: "»",
4946
+ middot: "·",
4947
+ bull: "•",
4948
+ times: "×",
4949
+ euro: "€"
4950
+ };
4951
+ /**
4952
+ * Markup text or a static attribute value, with its character references
4953
+ * read. A number that is no character, such as one past 0x10FFFF, reads as
4954
+ * U+FFFD, as the browser reads it.
4955
+ */
4956
+ function decodeReferences(html) {
4957
+ return html.replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, name) => {
4958
+ if (name[0] === "#") {
4959
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : Number(name.slice(1));
4960
+ return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : "�";
4961
+ }
4962
+ return NAMED[name.toLowerCase()] ?? match;
4963
+ });
4964
+ }
4965
+ /** The value of a static attribute, with its character references read. */
4966
+ function decodeAttribute(text) {
4967
+ return decodeReferences(text);
4968
+ }
4969
+ /** The text that markup text shows, with its character references read. */
4970
+ function decodeText(html) {
4971
+ return decodeReferences(html);
4972
+ }
4549
4973
  /** The markup of an inserted literal, such as `{'<b>'}`, or undefined for other code. */
4550
4974
  function literalText(node) {
4551
4975
  if (node.type === "Literal") return "regex" in node && node.regex ? void 0 : insertValue(node.value);
4552
4976
  if (node.type === "TemplateLiteral" && node.expressions.length === 0) return insertValue(node.quasis[0].value.cooked);
4553
4977
  }
4978
+ /**
4979
+ * Blocks whose shape on the server depends on data: which branch renders,
4980
+ * how many items a list has, whether a body throws or shows. The server
4981
+ * numbers the scopes of their bodies after an ID of the block's own.
4982
+ */
4983
+ const DATA_SHAPED = /* @__PURE__ */ new Set([
4984
+ "if",
4985
+ "switch",
4986
+ "for",
4987
+ "repeat",
4988
+ "try",
4989
+ "offscreen"
4990
+ ]);
4554
4991
  var Emitter = class {
4555
4992
  lines = [];
4556
4993
  file;
@@ -4571,6 +5008,8 @@ var Emitter = class {
4571
5008
  depth = 0;
4572
5009
  /** How many of this component's elements contain the current node. */
4573
5010
  nesting = 0;
5011
+ /** How many `#head` blocks contain the current node, where a `<title>` sets the title of the page. */
5012
+ headBlocks = 0;
4574
5013
  counter = 0;
4575
5014
  constructor(file, plan, patch, options) {
4576
5015
  this.file = file;
@@ -4666,7 +5105,7 @@ var Emitter = class {
4666
5105
  emitSlots(scope) {
4667
5106
  const slots = this.plan.scopes.get(scope)?.slots ?? [];
4668
5107
  if (slots.length > 0) {
4669
- const values = slots.map((slot) => this.isPromise(slot) ? `$$b.wait(${promiseName(slot.name)})` : slot.name);
5108
+ const values = slots.map((slot) => this.isPromise(slot) ? `$$b.stateValue(${promiseName(slot.name)})` : slot.name);
4670
5109
  const names = this.options.mode === "server" ? `, ${JSON.stringify(slots.map((slot) => slot.name))}` : "";
4671
5110
  this.line(`${this.helper("slots")}(${this.scopeVar(scope)}, [${values.join(", ")}]${names});`);
4672
5111
  }
@@ -4681,18 +5120,68 @@ var Emitter = class {
4681
5120
  isPromise(declaration) {
4682
5121
  return this.options.mode === "server" && isMemo(declaration) && !this.blocking.has(declaration) && !this.inline.has(declaration);
4683
5122
  }
4684
- /** Awaits the async memos of a statement that markup outside `#loading` reads. */
4685
- awaitMemos(statement) {
5123
+ /**
5124
+ * The memos of a statement that the server waits for where they are
5125
+ * declared. `awaited` is true when every one of them is declared with
5126
+ * `await $memo(…)`. Such statements in a row form a run: every memo of
5127
+ * the run starts, and the render waits for all of them where the run
5128
+ * ends, so independent memos load at the same time. A memo that the
5129
+ * markup makes the page wait for, without the keyword, is awaited on its
5130
+ * own, as the code reads.
5131
+ */
5132
+ blockingDeclarations(statement) {
4686
5133
  if (this.options.mode !== "server" || statement.type !== "VariableDeclaration") return;
5134
+ const declarations = [];
5135
+ let awaited = true;
4687
5136
  for (const declarator of statement.declarations) {
4688
- const init = declarator.init;
5137
+ let init = declarator.init;
5138
+ if (init?.type === "AwaitExpression") init = init.argument;
4689
5139
  const argument = init?.type === "CallExpression" ? init.arguments[0] : void 0;
4690
5140
  const declaration = argument && this.sitesByNode.get(argument)?.declaration;
4691
- if (declaration && isMemo(declaration) && this.blocking.has(declaration) && !this.inline.has(declaration)) this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5141
+ if (!declaration || !isMemo(declaration) || !this.blocking.has(declaration)) {
5142
+ awaited = false;
5143
+ continue;
5144
+ }
5145
+ awaited &&= declaration.awaited === true;
5146
+ if (!this.inline.has(declaration)) declarations.push(declaration);
5147
+ }
5148
+ return declarations.length === 0 ? void 0 : {
5149
+ declarations,
5150
+ awaited
5151
+ };
5152
+ }
5153
+ /** Waits for the memos of a run of declarations, and gives each its value. */
5154
+ awaitRun(run) {
5155
+ if (run.length === 1) {
5156
+ const [declaration] = run;
5157
+ this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5158
+ return;
4692
5159
  }
5160
+ const names = run.map((declaration) => promiseName(declaration.name));
5161
+ this.line(`if (($$t = $$b.waitAll([${names.join(", ")}])) !== undefined) await $$t;`);
5162
+ for (const declaration of run) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
4693
5163
  }
4694
5164
  emitStatements(statements, scope) {
5165
+ let run = [];
5166
+ const endRun = () => {
5167
+ if (run.length > 0) {
5168
+ this.awaitRun(run);
5169
+ run = [];
5170
+ }
5171
+ };
4695
5172
  for (const statement of statements) {
5173
+ const blocking = this.blockingDeclarations(statement);
5174
+ if (blocking?.awaited) {
5175
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
5176
+ run.push(...blocking.declarations);
5177
+ continue;
5178
+ }
5179
+ endRun();
5180
+ if (blocking) {
5181
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
5182
+ for (const declaration of blocking.declarations) this.awaitRun([declaration]);
5183
+ continue;
5184
+ }
4696
5185
  if (statement.type === "ExpressionStatement") {
4697
5186
  const expression = statement.expression;
4698
5187
  const name = expression.type === "CallExpression" && expression.callee.type === "Identifier" ? expression.callee.name : void 0;
@@ -4717,8 +5206,8 @@ var Emitter = class {
4717
5206
  if (!this.options.functions && this.isFunctionStatement(statement)) continue;
4718
5207
  }
4719
5208
  this.raw(this.patch.slice(statement.start, statement.end), statement.start);
4720
- this.awaitMemos(statement);
4721
5209
  }
5210
+ endRun();
4722
5211
  }
4723
5212
  source(node) {
4724
5213
  return this.patch.slice(node.start, node.end);
@@ -4738,13 +5227,14 @@ var Emitter = class {
4738
5227
  this.line(`const ${declaration.name} = ${this.helper("id")}(${target}, ${declaration.idIndex});`);
4739
5228
  continue;
4740
5229
  }
4741
- if (call !== "$getContext" || declarator.id.type !== "Identifier" || !init.arguments[0]) {
5230
+ const context = call && BUILT_IN_CONTEXTS[call] ? BUILT_IN_CONTEXTS[call] : call === "$getContext" && init.arguments[0] ? this.source(init.arguments[0]) : void 0;
5231
+ if (!context || declarator.id.type !== "Identifier") {
4742
5232
  this.line(`${statement.kind} ${this.source(declarator)};`);
4743
5233
  continue;
4744
5234
  }
4745
5235
  const slot = declaration ? slotIndex(this.plan, declaration) : -1;
4746
5236
  const record = slot === -1 ? "" : `, ${slot}`;
4747
- this.line(`const ${declarator.id.name} = ${this.helper("consume")}(${this.source(init.arguments[0])}, ${target}${record});`);
5237
+ this.line(`const ${declarator.id.name} = ${this.helper("consume")}(${context}, ${target}${record});`);
4748
5238
  }
4749
5239
  return true;
4750
5240
  }
@@ -4766,7 +5256,21 @@ var Emitter = class {
4766
5256
  const anchor = this.anchor(scope, site);
4767
5257
  this.html("<template b-b=\"");
4768
5258
  this.code(anchor.scope);
4769
- this.html(`:${anchor.index}" b-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"></template>`);
5259
+ this.html(`:${anchor.index}" b-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"`);
5260
+ const near = site.trigger === "visible" ? this.refElement(site, scope) : void 0;
5261
+ if (near !== void 0) {
5262
+ this.html(" b-near=\"");
5263
+ this.code(anchor.scope);
5264
+ this.html(`:${near}"`);
5265
+ }
5266
+ this.html("></template>");
5267
+ }
5268
+ }
5269
+ /** The anchor of the first element of `scope` that a site reads through `ref`. */
5270
+ refElement(site, scope) {
5271
+ for (const read of site.reads) for (const ref of read.declaration.refs) {
5272
+ const index = ref.scope === scope ? this.plan.anchors.get(ref.element) : void 0;
5273
+ if (index !== void 0) return index;
4770
5274
  }
4771
5275
  }
4772
5276
  /** Emits the content of the component, without creating its scope. */
@@ -4865,7 +5369,9 @@ var Emitter = class {
4865
5369
  return;
4866
5370
  case "insert": {
4867
5371
  const anchor = this.anchor(scope, node);
4868
- const at = this.options.mode === "server" ? `, $$ctx, ${this.scopeVar(instanceScope(this.plan, scope))}` : "";
5372
+ const ast = node.expression.ast;
5373
+ const kind = ast.type === "Identifier" ? lookup(scope, ast.name)?.kind : void 0;
5374
+ const at = this.options.mode === "server" || kind === "prop" || kind === "props-rest" ? `, ${this.ctxArgument}, ${this.scopeVar(instanceScope(this.plan, scope))}` : "";
4869
5375
  const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${this.expression(node.expression)})` : this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
4870
5376
  const text = literalText(node.expression.ast);
4871
5377
  const emitValue = () => text === void 0 ? this.code(value) : this.html(text);
@@ -4892,18 +5398,22 @@ var Emitter = class {
4892
5398
  return;
4893
5399
  case "listener": {
4894
5400
  const anchor = this.anchor(scope, node);
4895
- const events = node.attributes.map((attribute) => this.eventEntry(attribute.event, attribute.modifiers, attribute.handler));
5401
+ const events = node.attributes.map((attribute) => this.eventEntry(attribute));
4896
5402
  this.html("<template b-b=\"");
4897
5403
  this.code(anchor.scope);
4898
5404
  this.html(`:${anchor.index}" b-listen="${node.target}" b-on="${events.join(" ")}"></template>`);
4899
5405
  return;
4900
5406
  }
4901
- default: this.emitBlock(node, scope);
5407
+ default: if (this.options.mode === "server" && DATA_SHAPED.has(node.kind)) {
5408
+ this.line("$$ctx.enter();");
5409
+ this.emitBlock(node, scope);
5410
+ this.line("$$ctx.leave();");
5411
+ } else this.emitBlock(node, scope);
4902
5412
  }
4903
5413
  }
4904
- eventEntry(event, modifiers, handler) {
5414
+ eventEntry({ event, modifiers, handler }) {
4905
5415
  const site = this.sitesByNode.get(handler.ast);
4906
- return `${[event, ...modifiers].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
5416
+ return `${[event, ...[.../* @__PURE__ */ new Set([...modifiers, ...site.modifiers ?? []])]].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
4907
5417
  }
4908
5418
  emitRef(target, attribute, anchor) {
4909
5419
  const declaration = this.refTargets.get(attribute);
@@ -4959,14 +5469,23 @@ var Emitter = class {
4959
5469
  return `\`\${${this.scopeVar(instanceScope(this.plan, declaration.scope))}}:${slot}\``;
4960
5470
  }
4961
5471
  emitElement(node, scope) {
5472
+ const pageTitle = node.tag === "title" && this.headBlocks > 0;
5473
+ if (pageTitle && this.options.mode === "server") this.line(`${this.helper("title")}(${this.titleText(node)}, true);`);
5474
+ let spreadHandlers;
5475
+ if (this.options.mode === "server" && node.attributes.some((attribute) => attribute.kind === "spread")) {
5476
+ spreadHandlers = this.unique("on");
5477
+ this.line(`const ${spreadHandlers}: string[] = [];`);
5478
+ }
4962
5479
  this.html(`<${node.tag}`);
4963
5480
  if (this.hasScope(node.tag, staticClasses(node.attributes))) this.html(` ${this.plan.styles.attribute}`);
4964
5481
  const ownStyle = this.emitVariables(node);
4965
5482
  const events = [];
4966
5483
  let prefetch;
4967
5484
  const anchor = this.anchor(scope, node);
5485
+ const merged = node.attributes.some((attribute) => attribute.kind === "spread") ? [] : void 0;
4968
5486
  for (const attribute of node.attributes) {
4969
5487
  if (ownStyle && (attribute.kind === "static" || attribute.kind === "value") && attribute.name === "style") continue;
5488
+ if (merged && this.mergedAttribute(node, attribute, scope, merged)) continue;
4970
5489
  switch (attribute.kind) {
4971
5490
  case "static":
4972
5491
  this.html(attribute.value === true ? ` ${attribute.name}` : ` ${attribute.name}="${attribute.value}"`);
@@ -4986,13 +5505,13 @@ var Emitter = class {
4986
5505
  break;
4987
5506
  }
4988
5507
  case "spread":
4989
- this.code(`$$b.spread(${this.expression(attribute.value)})`);
5508
+ this.code(`$$b.spread(${this.expression(attribute.value)}${spreadHandlers ? `, ${spreadHandlers}` : ""})`);
4990
5509
  break;
4991
5510
  case "computed":
4992
5511
  this.code(`$$b.attribute(${this.expression(attribute.name)}, ${attribute.value === true ? "true" : this.expression(attribute.value)})`);
4993
5512
  break;
4994
5513
  case "event":
4995
- events.push(this.eventEntry(attribute.event, attribute.modifiers, attribute.handler));
5514
+ events.push(this.eventEntry(attribute));
4996
5515
  break;
4997
5516
  case "ref":
4998
5517
  if (anchor) this.emitRef(attribute.target, attribute, anchor);
@@ -5000,15 +5519,16 @@ var Emitter = class {
5000
5519
  case "prefetch": prefetch = attribute.strategy;
5001
5520
  }
5002
5521
  }
5522
+ if (merged) this.code(`$$b.spread($$b.mergeAttributes([${merged.join(", ")}])${spreadHandlers ? `, ${spreadHandlers}` : ""})`);
5003
5523
  if (anchor) {
5004
5524
  this.html(" b-b=\"");
5005
5525
  this.code(anchor.scope);
5006
5526
  this.html(`:${anchor.index}"`);
5007
5527
  }
5008
- if (events.length > 0) {
5009
- this.html(` b-on="${events.join(" ")}"`);
5010
- if (prefetch) this.html(` data-prefetch="${prefetch}"`);
5011
- }
5528
+ if (pageTitle) this.html(" b-t");
5529
+ if (spreadHandlers) this.code(`$$b.onAttribute(${spreadHandlers}, ${JSON.stringify(events.join(" "))})`);
5530
+ else if (events.length > 0) this.html(` b-on="${events.join(" ")}"`);
5531
+ if (events.length > 0 && prefetch) this.html(` data-prefetch="${prefetch}"`);
5012
5532
  this.html(">");
5013
5533
  if (VOID_ELEMENTS.has(node.tag)) return;
5014
5534
  this.nesting++;
@@ -5017,6 +5537,42 @@ var Emitter = class {
5017
5537
  this.html(`</${node.tag}>`);
5018
5538
  }
5019
5539
  /**
5540
+ * Adds an attribute of an element with spreads to `parts`, the objects
5541
+ * that its spread merges. Returns false for an attribute that stays apart,
5542
+ * such as a handler or a `ref`.
5543
+ */
5544
+ mergedAttribute(node, attribute, scope, parts) {
5545
+ switch (attribute.kind) {
5546
+ case "static":
5547
+ parts.push(`{ ${JSON.stringify(attribute.name)}: ${attribute.value === true ? "true" : JSON.stringify(decodeAttribute(attribute.value))} }`);
5548
+ return true;
5549
+ case "value":
5550
+ if (this.formAction(node, attribute.name, attribute.value, scope)) return false;
5551
+ parts.push(`{ ${JSON.stringify(attribute.name)}: ${this.expression(attribute.value)} }`);
5552
+ return true;
5553
+ case "computed":
5554
+ parts.push(`{ [${this.expression(attribute.name)}]: ${attribute.value === true ? "true" : this.expression(attribute.value)} }`);
5555
+ return true;
5556
+ case "spread":
5557
+ parts.push(this.expression(attribute.value));
5558
+ return true;
5559
+ default: return false;
5560
+ }
5561
+ }
5562
+ /**
5563
+ * The text of a `<title>`, as code: its one insert, or its text and the
5564
+ * inserts in it joined, such as `Items ({count})`.
5565
+ */
5566
+ titleText(node) {
5567
+ const [only] = node.children;
5568
+ if (only?.kind === "insert" && node.children.length === 1) return this.expression(only.expression);
5569
+ const parts = node.children.flatMap((child) => {
5570
+ if (child.kind === "insert") return [`(${this.expression(child.expression)} ?? '')`];
5571
+ return child.kind === "text" ? [JSON.stringify(decodeText(cleanText(child.value)))] : [];
5572
+ });
5573
+ return parts.length === 0 ? "\"\"" : parts.join(" + ");
5574
+ }
5575
+ /**
5020
5576
  * Renders a literal `class` value as the runtime renders it, without
5021
5577
  * building the value. A class with a condition is added when the condition
5022
5578
  * is truthy. No class leaves the attribute out.
@@ -5060,12 +5616,21 @@ var Emitter = class {
5060
5616
  emitChildren(nodes, scope) {
5061
5617
  if (nodes.length === 0) return;
5062
5618
  const name = this.unique("children");
5063
- this.line(`const ${name} = ${this.wait}(${this.async}() => {`);
5619
+ if (this.options.mode === "server") {
5620
+ this.line(`const ${name} = $$b.children(${this.scopeVar(instanceScope(this.plan, scope))}, async ($$ctx) => {`);
5621
+ this.line(`let $$html = '';`);
5622
+ this.atTopLevel(() => this.emitNodes(nodes, scope));
5623
+ this.flush();
5624
+ this.line("return $$html;");
5625
+ this.close("});");
5626
+ return name;
5627
+ }
5628
+ this.line(`const ${name} = $$b.children(${this.scopeVar(instanceScope(this.plan, scope))}, () => {`);
5064
5629
  this.line(`let $$html = '';`);
5065
5630
  this.atTopLevel(() => this.emitNodes(nodes, scope));
5066
5631
  this.flush();
5067
- this.line("return $$b.raw($$html);");
5068
- this.close("})();");
5632
+ this.line("return $$html;");
5633
+ this.close("});");
5069
5634
  return name;
5070
5635
  }
5071
5636
  props(attributes, scope, extra = []) {
@@ -5138,7 +5703,7 @@ var Emitter = class {
5138
5703
  if (this.hasScope(void 0, staticClasses(node.attributes))) extra.push(`${JSON.stringify(this.plan.styles.attribute)}: true`);
5139
5704
  const anchor = this.anchor(scope, node);
5140
5705
  if (anchor) extra.push(`"b-b": \`\${${anchor.scope}}:${anchor.index}\``);
5141
- const events = node.attributes.flatMap((attribute) => attribute.kind === "event" ? [this.eventEntry(attribute.event, attribute.modifiers, attribute.handler)] : []);
5706
+ const events = node.attributes.flatMap((attribute) => attribute.kind === "event" ? [this.eventEntry(attribute)] : []);
5142
5707
  if (events.length > 0) extra.push(`"b-on": ${JSON.stringify(events.join(" "))}`);
5143
5708
  let attributes = node.attributes.filter((attribute) => attribute.kind !== "event");
5144
5709
  const { variables } = this.plan.styles;
@@ -5175,7 +5740,9 @@ var Emitter = class {
5175
5740
  this.html("<!--P");
5176
5741
  this.code(this.scopeVar(body));
5177
5742
  this.html("-->");
5743
+ this.headBlocks += block.kind === "head" ? 1 : 0;
5178
5744
  this.atTopLevel(() => this.emitBody(block.body, false));
5745
+ this.headBlocks -= block.kind === "head" ? 1 : 0;
5179
5746
  this.html("<!--/P-->");
5180
5747
  this.flush();
5181
5748
  this.line("return $$html;");
@@ -5183,13 +5750,35 @@ var Emitter = class {
5183
5750
  this.line(`${this.helper(block.kind === "head" ? "head" : "portal")}(${name});`);
5184
5751
  }
5185
5752
  /**
5186
- * Writes the fallback of `#loading` and renders its body after the rest of
5187
- * the page, so data that the body waits for does not hold up the page.
5753
+ * Renders a `#loading` block. When the memos that its body reads are
5754
+ * ready, and the body waits for nothing else, the body renders in place,
5755
+ * in the ID space of its boundary. Otherwise the fallback renders, and the
5756
+ * body renders after the rest of the page, so data that the body waits
5757
+ * for does not hold up the page. The memos that the body reads with
5758
+ * `await` are ready here, because the render around the block waited for
5759
+ * them.
5188
5760
  */
5189
5761
  emitLoading(block, scope) {
5190
5762
  const boundary = this.unique("boundary");
5191
5763
  const body = this.plan.bodyScopes.get(block.body);
5764
+ const memos = awaitedMemos(this.plan, body, this.blocking).filter((declaration) => !this.inline.has(declaration));
5765
+ const names = memos.map((declaration) => promiseName(declaration.name));
5766
+ const inPlace = !mayWait(this.plan, block.body.children);
5767
+ if (inPlace && memos.length === 0) {
5768
+ this.line("$$ctx.enter();");
5769
+ this.emitBody(block.body);
5770
+ this.line("$$ctx.leave();");
5771
+ return;
5772
+ }
5192
5773
  this.line(`const ${boundary} = $$ctx.boundary();`);
5774
+ if (inPlace) {
5775
+ this.line(`if ($$b.settled([${names.join(", ")}])) {`);
5776
+ this.line(`$$ctx.enter(${boundary});`);
5777
+ for (const declaration of memos) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
5778
+ this.emitBody(block.body);
5779
+ this.line("$$ctx.leave();");
5780
+ this.close("} else {");
5781
+ }
5193
5782
  this.open(scope, block);
5194
5783
  this.html("<!--l");
5195
5784
  this.code(boundary);
@@ -5203,6 +5792,41 @@ var Emitter = class {
5203
5792
  this.end(block);
5204
5793
  this.line(`$$ctx.defer(${boundary}, async ($$ctx) => {`);
5205
5794
  this.line(`let $$html = '';`);
5795
+ for (const declaration of memos) this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5796
+ this.emitBody(block.body);
5797
+ this.flush();
5798
+ this.line("return $$html;");
5799
+ this.close("});");
5800
+ if (inPlace) this.close();
5801
+ }
5802
+ /**
5803
+ * Renders the fallback of a `#defer` block between the markers of a
5804
+ * boundary, and a template that the loader starts when the trigger fires.
5805
+ * The body renders only in the request for it, and replaces the fallback
5806
+ * as a `#loading` body does.
5807
+ */
5808
+ emitDefer(block, scope) {
5809
+ const boundary = this.unique("boundary");
5810
+ const anchor = this.anchor(scope, block);
5811
+ const body = this.plan.bodyScopes.get(block.body);
5812
+ this.line(`const ${boundary} = $$ctx.boundary();`);
5813
+ this.html("<template b-b=\"");
5814
+ this.code(anchor.scope);
5815
+ this.html(`:${anchor.index}" b-defer="${block.trigger}:`);
5816
+ this.code(boundary);
5817
+ this.html(":");
5818
+ this.code("$$ctx.base()");
5819
+ this.html("\"></template><!--l");
5820
+ this.code(boundary);
5821
+ this.html("-->");
5822
+ if (block.fallback) {
5823
+ this.line("{");
5824
+ this.emitBody(block.fallback);
5825
+ this.close();
5826
+ }
5827
+ this.html("<!--/l-->");
5828
+ this.line(`$$ctx.deferBlock(${boundary}, ${anchor.scope} + ${JSON.stringify(`:${anchor.index}`)}, async ($$ctx) => {`);
5829
+ this.line(`let $$html = '';`);
5206
5830
  for (const declaration of awaitedMemos(this.plan, body, this.blocking)) {
5207
5831
  if (this.inline.has(declaration)) continue;
5208
5832
  this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
@@ -5298,9 +5922,25 @@ var Emitter = class {
5298
5922
  this.code(anchor.scope);
5299
5923
  this.html(`:${anchor.index}" b-client="${block.trigger}=${this.plan.id}#k${body.id}"></template>`);
5300
5924
  this.open(scope, block);
5925
+ if (block.fallback) {
5926
+ this.line("{");
5927
+ this.emitBody(block.fallback);
5928
+ this.close();
5929
+ }
5301
5930
  this.end(block);
5302
5931
  return;
5303
5932
  }
5933
+ case "defer":
5934
+ if (this.options.mode === "server") this.emitDefer(block, scope);
5935
+ else {
5936
+ this.line(`$$b.deferInBrowser(${JSON.stringify(this.plan.id)});`);
5937
+ if (block.fallback) {
5938
+ this.line("{");
5939
+ this.emitBody(block.fallback);
5940
+ this.close();
5941
+ }
5942
+ }
5943
+ return;
5304
5944
  case "loading":
5305
5945
  if (this.options.mode === "server") {
5306
5946
  this.emitLoading(block, scope);
@@ -5530,6 +6170,8 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
5530
6170
  case "for":
5531
6171
  case "repeat":
5532
6172
  case "loading":
6173
+ case "client":
6174
+ case "defer":
5533
6175
  componentNames(node.body.children, names);
5534
6176
  componentNames(node.fallback?.children ?? [], names);
5535
6177
  break;
@@ -5540,7 +6182,6 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
5540
6182
  case "key":
5541
6183
  case "portal":
5542
6184
  case "head":
5543
- case "client":
5544
6185
  case "offscreen": componentNames(node.body.children, names);
5545
6186
  }
5546
6187
  return names;
@@ -5585,6 +6226,10 @@ function clientModuleScript(file, plan) {
5585
6226
  }
5586
6227
  return result;
5587
6228
  }
6229
+ /** True if the render of the component awaits a promise, outside memos and the code of handlers. */
6230
+ function awaitsPromise(plan) {
6231
+ return plan.graph.model.sites.some((site) => site.awaits && site.kind !== "memo" && site.kind !== "function" && !SKIPPED_SITES.has(site.kind));
6232
+ }
5588
6233
  /**
5589
6234
  * Generates the render module: the component's render function for the
5590
6235
  * client, used when a parent renders it inside a block that changes.
@@ -5626,6 +6271,17 @@ function generateRender(file, plan) {
5626
6271
  });
5627
6272
  const generics = file.generics ? `<${file.generics}>` : "";
5628
6273
  emitter.line(`export default function ${plan.name}${generics}($$props: ${propsType(file)}): string {`);
6274
+ if (awaitsPromise(plan)) {
6275
+ emitter.line(`throw new Error(${JSON.stringify(`${plan.name} awaits a promise in its script or markup, so only the server can render it`)});`);
6276
+ emitter.close();
6277
+ return [
6278
+ ...header,
6279
+ ...moduleBody,
6280
+ "",
6281
+ ...emitter.lines,
6282
+ ""
6283
+ ].join("\n");
6284
+ }
5629
6285
  emitter.line(`let $$html = '';`);
5630
6286
  emitter.line(`const ${emitter.scopeVar(model.component)} = $$b.createScope(${model.component.id}, undefined, ${JSON.stringify(plan.id)});`);
5631
6287
  emitter.emitComponentContent(setup);
@@ -5789,6 +6445,15 @@ var Rewriter = class {
5789
6445
  if (value) patch.replace(node.start, node.end, value);
5790
6446
  return;
5791
6447
  }
6448
+ case "AwaitExpression": {
6449
+ const reference = target(node.argument);
6450
+ if (reference?.await) {
6451
+ const value = this.value(reference.declaration, scopeVar, base);
6452
+ patch.replace(node.start, node.end, value ?? reference.declaration.name);
6453
+ return;
6454
+ }
6455
+ break;
6456
+ }
5792
6457
  case "Property":
5793
6458
  if (node.shorthand && node.value.type === "Identifier") {
5794
6459
  const reference = target(node.value);
@@ -5984,8 +6649,8 @@ var ClientGenerator = class {
5984
6649
  lines.push(code);
5985
6650
  }
5986
6651
  generate() {
5987
- this.checkSupport();
5988
6652
  this.collectRenders();
6653
+ this.checkSupport();
5989
6654
  this.placeCode();
5990
6655
  this.emitFunctions();
5991
6656
  this.emitRoots();
@@ -6007,11 +6672,13 @@ var ClientGenerator = class {
6007
6672
  if (used.size > 0) parts[name] = `${[...used].map((index) => `import * as $$m${index} from ${JSON.stringify(this.shared.specifiers[index])};`).join("\n")}\n${code}`;
6008
6673
  }
6009
6674
  const refresh = this.refreshTable();
6675
+ const tries = this.triesTable();
6010
6676
  const table = [
6011
6677
  `export const id = ${JSON.stringify(this.plan.id)};`,
6012
6678
  `export const props = ${this.propsMap()};`,
6013
6679
  `export const g = ${this.table()};`,
6014
- ...refresh ? [`export const refresh = ${refresh};`] : []
6680
+ ...refresh ? [`export const refresh = ${refresh};`] : [],
6681
+ ...tries ? [`export const t = ${tries};`] : []
6015
6682
  ];
6016
6683
  const clientCode = names.length > 0;
6017
6684
  if (merged || !clientCode) {
@@ -6187,7 +6854,12 @@ var ClientGenerator = class {
6187
6854
  return lines.join("\n");
6188
6855
  }
6189
6856
  checkSupport() {
6190
- for (const site of this.model.sites) if (this.live.has(site) && site.kind === "tag" && !site.owner?.keyed) this.error("A dynamic tag that changes on the client is not supported yet", site.range);
6857
+ const rendered = this.renderedScopes();
6858
+ for (const site of this.model.sites) {
6859
+ const live = this.live.has(site);
6860
+ if (live && site.kind === "tag" && !site.owner?.keyed) this.error("A dynamic tag that changes on the client is not supported yet", site.range);
6861
+ if (site.awaits && site.kind !== "memo" && !DEFERRED_SITES.has(site.kind) && (live || rendered.some((scope) => isWithin(site.scope, scope)))) this.error(live ? "Code that the browser updates can await only a memo. Load the promise in a memo instead" : "Markup that the browser renders can await only a memo. Load the promise in a memo instead", site.range);
6862
+ }
6191
6863
  }
6192
6864
  clientReads() {
6193
6865
  const reads = /* @__PURE__ */ new Set();
@@ -6289,7 +6961,7 @@ var ClientGenerator = class {
6289
6961
  const symbol = this.plan.symbols.get(site);
6290
6962
  if (!symbol) continue;
6291
6963
  const base = instanceScope(this.plan, site.scope);
6292
- let code = this.rewriter.rewrite(site, "$$s", base);
6964
+ let code = this.withTemplates(site, this.rewriter.rewrite(site, "$$s", base));
6293
6965
  if (site.node.type === "FunctionExpression" && unmarked(code).trimStart().startsWith("(")) code = `function ${code}`;
6294
6966
  this.part = symbol;
6295
6967
  if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.effect($$s, ${JSON.stringify(symbol)}, ${code});\n}`);
@@ -6341,7 +7013,9 @@ var ClientGenerator = class {
6341
7013
  const slot = slotIndex(this.plan, node.declaration);
6342
7014
  if (slot !== -1) {
6343
7015
  const value = site.awaits ? `(async () => (${expression()}))()` : expression();
6344
- this.emit(`export function ${name("m")}($$s) {\n $$b.memo($$s, ${slot}, () => ${value});\n}`);
7016
+ const timing = node.declaration.timing;
7017
+ const call = timing ? `$$b.timed($$s, ${slot}, ${timing.ms}, ${timing.kind === "throttled"}, () => ${value})` : `$$b.memo($$s, ${slot}, () => ${value})`;
7018
+ this.emit(`export function ${name("m")}($$s) {\n ${call};\n}`);
6345
7019
  }
6346
7020
  break;
6347
7021
  }
@@ -6407,8 +7081,16 @@ var ClientGenerator = class {
6407
7081
  this.emit(`export function ${name("u")}($$s) {\n $$b.prop($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${expression()});\n}`);
6408
7082
  return;
6409
7083
  }
6410
- if (attribute.kind === "spread") this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${expression()});\n}`);
6411
- else if (attribute.kind === "value") {
7084
+ if (attribute.kind === "spread") {
7085
+ const own = owner.attributes.flatMap((item) => item.kind === "static" || item.kind === "value" ? [item.name] : []);
7086
+ if (this.plan.styles.css) own.push(this.plan.styles.attribute, "style");
7087
+ const parts = owner.attributes.flatMap((item) => {
7088
+ if (item === attribute) return [expression()];
7089
+ return item.kind === "static" ? [`{ ${JSON.stringify(item.name)}: ${item.value === true ? "true" : JSON.stringify(decodeAttribute(item.value))} }`] : [];
7090
+ });
7091
+ const value = parts.length > 1 ? `$$b.mergeAttributes([${parts.join(", ")}])` : expression();
7092
+ this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${value}, ${JSON.stringify(own)});\n}`);
7093
+ } else if (attribute.kind === "value") {
6412
7094
  const value = (attribute.name === "class" ? classes(attribute.value.ast) : void 0) ?? expression();
6413
7095
  this.emit(`export function ${name("u")}($$s) {\n $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value});\n}`);
6414
7096
  }
@@ -6519,7 +7201,7 @@ var ClientGenerator = class {
6519
7201
  }
6520
7202
  for (const scope of this.model.scopes) {
6521
7203
  const block = scope.block;
6522
- const clientOnly = block?.kind === "client" || block?.kind === "portal" && block.target !== void 0 || block?.kind === "try" && this.plan.anchors.has(block);
7204
+ const clientOnly = block?.kind === "client" && scope.body === block.body || block?.kind === "portal" && block.target !== void 0 || block?.kind === "try" && this.plan.anchors.has(block);
6523
7205
  if (scope.kind === "body" && block && clientOnly && scope.body) this.renders.set(scope, {
6524
7206
  body: scope.body,
6525
7207
  block
@@ -6562,7 +7244,8 @@ var ClientGenerator = class {
6562
7244
  }
6563
7245
  if (block.kind === "client") {
6564
7246
  const anchor = this.plan.anchors.get(block);
6565
- this.emit(`export function k${scope.id}($$s) {\n $$b.fill($$s, ${anchor}, r${scope.id});\n}`);
7247
+ const fallback = block.fallback ? `, [${this.kinds([block.fallback]).join(", ")}]` : "";
7248
+ this.emit(`export function k${scope.id}($$s) {\n $$b.fill($$s, ${anchor}, r${scope.id}${fallback});\n}`);
6566
7249
  }
6567
7250
  }
6568
7251
  }
@@ -6573,7 +7256,8 @@ var ClientGenerator = class {
6573
7256
  */
6574
7257
  withTemplates(site, code) {
6575
7258
  const templates = [];
6576
- for (const callee of site.calls) {
7259
+ const used = [...site.calls, ...site.reads.map((read) => read.declaration).filter((item) => item.kind === "template")];
7260
+ for (const callee of used) {
6577
7261
  if (callee.kind !== "template") continue;
6578
7262
  const template = this.model.scopes.find((item) => item.template?.name === callee.name && item.parent === callee.scope);
6579
7263
  for (const item of template ? this.inside(template) : []) if (!templates.includes(item)) templates.push(item);
@@ -6614,6 +7298,24 @@ var ClientGenerator = class {
6614
7298
  * The memos to load again when a server function calls `refresh(fn)`:
6615
7299
  * by the ID of `fn`, the scope kind and the update of each memo.
6616
7300
  */
7301
+ /**
7302
+ * The `#try` blocks that catch errors of client code, by the scope kinds
7303
+ * inside their bodies: the kind of the scope that holds the block, the
7304
+ * anchor of the block, the render functions of the body and the `#catch`
7305
+ * body, and the kinds of both bodies.
7306
+ */
7307
+ triesTable() {
7308
+ const entries = [];
7309
+ for (const scope of this.model.scopes) {
7310
+ const block = scope.block;
7311
+ if (block?.kind !== "try" || scope.body !== block.body || !this.plan.anchors.has(block) || !tryCatchesClient(this.model, block)) continue;
7312
+ const owner = instanceScope(this.plan, scope.parent);
7313
+ const fallback = this.plan.bodyScopes.get(block.fallback);
7314
+ const entry = `[${owner.id}, ${this.plan.anchors.get(block)}, ${JSON.stringify(`r${scope.id}`)}, ${JSON.stringify(`r${fallback.id}`)}, [${this.kinds(blockBodies(block)).join(", ")}]]`;
7315
+ for (const inside of this.model.scopes) if (isWithin(inside, scope)) entries.push(`${inside.id}: ${entry}`);
7316
+ }
7317
+ return entries.length > 0 ? `{ ${entries.join(", ")} }` : void 0;
7318
+ }
6617
7319
  refreshTable() {
6618
7320
  const table = /* @__PURE__ */ new Map();
6619
7321
  for (const node of this.plan.graph.nodes) {
@@ -6841,7 +7543,7 @@ function compile(source, options = {}) {
6841
7543
  const plan = createPlan(file, graph, options.path, options.hideNames);
6842
7544
  const styleErrors = [...plan.styles.diagnostics, ...plan.diagnostics].filter((diagnostic) => diagnostic.severity === "error");
6843
7545
  if (styleErrors.length > 0) fail(styleErrors);
6844
- const captures = checkCaptures(file, plan);
7546
+ const captures = [...checkCaptures(file, plan), ...options.envImport ? checkEnv(file, plan, options.envImport) : []];
6845
7547
  if (captures.length > 0) fail(captures);
6846
7548
  const shared = sharedContext(origin, modules, calls, options.path ?? filename);
6847
7549
  const client = generateClient(file, plan, options.merge, shared);
@@ -7058,4 +7760,4 @@ function inspect(source, options = {}) {
7058
7760
  //#endregion
7059
7761
  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 };
7060
7762
 
7061
- //# sourceMappingURL=inspect-BPchdWbU.js.map
7763
+ //# sourceMappingURL=inspect-BJtACnQp.js.map