brumate 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-C25Sa6vq.d.ts} +27 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-BD6XT-s5.js +1968 -0
  4. package/dist/client-BD6XT-s5.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-D0CqSxoO.d.ts} +211 -30
  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/{cookies-Av5WFmcf.js → cookies-BzllthiF.js} +2 -1
  12. package/dist/cookies-BzllthiF.js.map +1 -0
  13. package/dist/defer-BbD7JQhj.js +56 -0
  14. package/dist/defer-BbD7JQhj.js.map +1 -0
  15. package/dist/devtools-CQgD7NPB.js +623 -0
  16. package/dist/devtools-CQgD7NPB.js.map +1 -0
  17. package/dist/devtools-panel-BVB-W5q4.js +1930 -0
  18. package/dist/devtools-panel-BVB-W5q4.js.map +1 -0
  19. package/dist/events-CSs7OwIC.js +85 -0
  20. package/dist/events-CSs7OwIC.js.map +1 -0
  21. package/dist/{files-DdT84mPy.js → files-BXSSrQgc.js} +34 -6
  22. package/dist/files-BXSSrQgc.js.map +1 -0
  23. package/dist/forms-Bg-CwGqX.js +406 -0
  24. package/dist/forms-Bg-CwGqX.js.map +1 -0
  25. package/dist/forms-Cl21hkHt.d.ts +281 -0
  26. package/dist/highlight.d.ts +17 -0
  27. package/dist/highlight.js +269 -0
  28. package/dist/highlight.js.map +1 -0
  29. package/dist/html-Bq1rFxX_.d.ts +92 -0
  30. package/dist/html-mNTKzaDD.js +241 -0
  31. package/dist/html-mNTKzaDD.js.map +1 -0
  32. package/dist/index.d.ts +123 -30
  33. package/dist/index.js +14 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/{inspect-BPchdWbU.js → inspect-BHpOw1LF.js} +1400 -121
  36. package/dist/inspect-BHpOw1LF.js.map +1 -0
  37. package/dist/{loader-Dc9OwY5I.js → loader-Dos_3NP0.js} +47 -11
  38. package/dist/loader-Dos_3NP0.js.map +1 -0
  39. package/dist/{navigate-CzLjnoPH.js → navigate-O78d_zGN.js} +115 -13
  40. package/dist/navigate-O78d_zGN.js.map +1 -0
  41. package/dist/produce-D0V0ICkz.d.ts +114 -0
  42. package/dist/produce-Doc91GkX.js +274 -0
  43. package/dist/produce-Doc91GkX.js.map +1 -0
  44. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  45. package/dist/{rpc-9fSqL_YK.js → rpc-ygMRPmN4.js} +39 -23
  46. package/dist/rpc-ygMRPmN4.js.map +1 -0
  47. package/dist/runtime/batch.d.ts +23 -0
  48. package/dist/runtime/batch.js +69 -0
  49. package/dist/runtime/batch.js.map +1 -0
  50. package/dist/runtime/client.d.ts +5 -5
  51. package/dist/runtime/client.js +5 -1345
  52. package/dist/runtime/context.d.ts +2 -2
  53. package/dist/runtime/context.js +1 -1
  54. package/dist/runtime/devtools.d.ts +191 -5
  55. package/dist/runtime/devtools.js +1 -1
  56. package/dist/runtime/env.d.ts +44 -0
  57. package/dist/runtime/env.js +61 -0
  58. package/dist/runtime/env.js.map +1 -0
  59. package/dist/runtime/events.d.ts +42 -0
  60. package/dist/runtime/events.js +1 -0
  61. package/dist/runtime/forms.d.ts +2 -0
  62. package/dist/runtime/forms.js +1 -0
  63. package/dist/runtime/gather.d.ts +25 -0
  64. package/dist/runtime/gather.js +33 -0
  65. package/dist/runtime/gather.js.map +1 -0
  66. package/dist/runtime/hot.d.ts +1 -1
  67. package/dist/runtime/html.d.ts +2 -2
  68. package/dist/runtime/html.js +1 -1
  69. package/dist/runtime/loader.d.ts +2 -2
  70. package/dist/runtime/loader.js +2 -2
  71. package/dist/runtime/routes.d.ts +2 -21
  72. package/dist/runtime/routes.js +31 -1
  73. package/dist/runtime/routes.js.map +1 -1
  74. package/dist/runtime/server.d.ts +7 -5
  75. package/dist/runtime/server.js +6 -7
  76. package/dist/runtime/signals.d.ts +60 -3
  77. package/dist/runtime/signals.js +40 -2
  78. package/dist/runtime/signals.js.map +1 -1
  79. package/dist/runtime/static-loader.d.ts +2 -2
  80. package/dist/runtime/static-loader.js +1 -1
  81. package/dist/runtime/testing.d.ts +46 -5
  82. package/dist/runtime/testing.js +240 -33
  83. package/dist/runtime/testing.js.map +1 -1
  84. package/dist/runtime/values.d.ts +2 -0
  85. package/dist/runtime/values.js +24 -0
  86. package/dist/runtime/values.js.map +1 -0
  87. package/dist/secrets-BxagsJxJ.js +23 -0
  88. package/dist/secrets-BxagsJxJ.js.map +1 -0
  89. package/dist/server-CxVDYE_V.js +3417 -0
  90. package/dist/server-CxVDYE_V.js.map +1 -0
  91. package/dist/server-DuFYRXrd.d.ts +1460 -0
  92. package/dist/skew-FRmAy9iy.js +49 -0
  93. package/dist/skew-FRmAy9iy.js.map +1 -0
  94. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  95. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-Drpr0AzI.d.ts} +2 -2
  96. package/dist/static-loader-nZssh66R.js +333 -0
  97. package/dist/static-loader-nZssh66R.js.map +1 -0
  98. package/dist/stream-DCYZO4IF.js +424 -0
  99. package/dist/stream-DCYZO4IF.js.map +1 -0
  100. package/dist/values-B8C7CLvG.d.ts +63 -0
  101. package/dist/vite.d.ts +49 -1
  102. package/dist/vite.js +598 -68
  103. package/dist/vite.js.map +1 -1
  104. package/forms/forms.brm.ts +141 -0
  105. package/package.json +45 -3
  106. package/types.d.ts +9 -1
  107. package/dist/client-routes-DakuM32C.js.map +0 -1
  108. package/dist/context-BG8KCF3v.js +0 -15
  109. package/dist/context-BG8KCF3v.js.map +0 -1
  110. package/dist/context-aeo9esY9.d.ts +0 -16
  111. package/dist/cookies-Av5WFmcf.js.map +0 -1
  112. package/dist/devtools-BKjnHrnv.js +0 -113
  113. package/dist/devtools-BKjnHrnv.js.map +0 -1
  114. package/dist/devtools-panel-AWOn0VK2.js +0 -434
  115. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  116. package/dist/files-DdT84mPy.js.map +0 -1
  117. package/dist/html-DEeoepg3.js +0 -152
  118. package/dist/html-DEeoepg3.js.map +0 -1
  119. package/dist/html-Du8jY2Cc.d.ts +0 -53
  120. package/dist/inspect-BPchdWbU.js.map +0 -1
  121. package/dist/loader-Dc9OwY5I.js.map +0 -1
  122. package/dist/navigate-CzLjnoPH.js.map +0 -1
  123. package/dist/produce-BRGHP7e0.js +0 -126
  124. package/dist/produce-BRGHP7e0.js.map +0 -1
  125. package/dist/produce-CtZ32UGG.d.ts +0 -60
  126. package/dist/rpc-9fSqL_YK.js.map +0 -1
  127. package/dist/runtime/client.js.map +0 -1
  128. package/dist/server-BxqjLUnV.d.ts +0 -753
  129. package/dist/server-DZsgnPKS.js +0 -1615
  130. package/dist/server-DZsgnPKS.js.map +0 -1
  131. package/dist/shared-CWYOd0H3.js +0 -40
  132. package/dist/shared-CWYOd0H3.js.map +0 -1
  133. package/dist/static-loader-ClNkHZGn.js +0 -185
  134. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  135. package/dist/stream-bgNCMcaA.js +0 -280
  136. 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-CSs7OwIC.js";
2
+ import { f as insertValue } from "./html-mNTKzaDD.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,9 +21,13 @@ 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
- "$action"
28
+ "$action",
29
+ "$handler",
30
+ "$bind"
24
31
  ]);
25
32
  /** Compile-time functions that have a new name, by old name. */
26
33
  const RENAMED_MACROS = /* @__PURE__ */ new Map([["$provide", "$setContext"], ["$context", "$getContext"]]);
@@ -243,15 +250,34 @@ const REACTIVE = /* @__PURE__ */ new Set([
243
250
  "item",
244
251
  "action"
245
252
  ]);
253
+ /** The module of the wrappers of event handlers, which the compiler reads. */
254
+ const EVENTS_MODULE = "brumate/events";
255
+ /** The wrappers that `brumate/events` exports. */
256
+ const WRAPPERS$1 = /* @__PURE__ */ new Set([
257
+ "prevent",
258
+ "stop",
259
+ "once",
260
+ "capture"
261
+ ]);
262
+ /** The events whose `prevent` can name keys. */
263
+ const KEY_EVENTS = /* @__PURE__ */ new Set([
264
+ "keydown",
265
+ "keyup",
266
+ "keypress"
267
+ ]);
246
268
  const COMPILE_TIME_FUNCTIONS = MACROS;
247
269
  const MISPLACED = {
248
270
  $setContext: "Call $setContext at the top level of a script",
249
271
  $title: "Call $title at the top level of a script",
250
272
  $id: "Create an ID with \"const name = $id()\" at the top level of a script",
251
273
  $getContext: "Read a context with \"const name = $getContext(Context)\" at the top level of a script",
274
+ $route: "Read the route with \"const name = $route()\" at the top level of a script",
275
+ $navigation: "Read the navigation with \"const name = $navigation()\" at the top level of a script",
252
276
  $props: "Call $props() as the value of a const in the component script",
253
277
  $signal: "Declare a signal with \"let name = $signal(value)\" at the top level of a script",
254
278
  $memo: "Declare a memo with \"const name = $memo(value)\" at the top level of a script",
279
+ $debounced: "Declare a debounced value with \"const name = $debounced(value, ms)\" at the top level of a script",
280
+ $throttled: "Declare a throttled value with \"const name = $throttled(value, ms)\" at the top level of a script",
255
281
  $optimistic: "Declare an optimistic value with \"let name = $optimistic(source)\" at the top level of a script",
256
282
  $action: "Declare the result of a form with \"const name = $action(serverFunction)\" at the top level of a script",
257
283
  $effect: "Call $effect at the top level of a script",
@@ -311,7 +337,7 @@ function hasUseServer(fn) {
311
337
  return false;
312
338
  }
313
339
  /** Returns the name of a compile-time function that `node` calls, if any. */
314
- function calleeName(node) {
340
+ function calleeName$1(node) {
315
341
  if (node?.type === "CallExpression" && node.callee.type === "Identifier") return node.callee.name;
316
342
  }
317
343
  function range(node) {
@@ -320,6 +346,27 @@ function range(node) {
320
346
  end: node.end
321
347
  };
322
348
  }
349
+ /**
350
+ * The names of the props that a type marks `Bindable`, such as `open` in
351
+ * `{ open?: Bindable<boolean> }`. A name of a type is looked up among the
352
+ * interfaces and the type aliases of the scripts.
353
+ */
354
+ function bindableNames(type, file) {
355
+ let members;
356
+ if (type.type === "TSTypeLiteral") members = type.members;
357
+ else if (type.type === "TSTypeReference" && type.typeName.type === "Identifier") {
358
+ const name = type.typeName.name;
359
+ const statements = [...file.moduleScript?.program.body ?? [], ...file.instanceScript?.program.body ?? []].map((statement) => statement.type === "ExportNamedDeclaration" && statement.declaration ? statement.declaration : statement);
360
+ for (const statement of statements) if (statement.type === "TSInterfaceDeclaration" && statement.id.name === name) members = statement.body.body;
361
+ else if (statement.type === "TSTypeAliasDeclaration" && statement.id.name === name) return bindableNames(statement.typeAnnotation, file);
362
+ }
363
+ return (members ?? []).flatMap((member) => {
364
+ const annotation = member.type === "TSPropertySignature" ? member.typeAnnotation?.typeAnnotation : void 0;
365
+ if (!(annotation?.type === "TSTypeReference" && annotation.typeName.type === "Identifier" && annotation.typeName.name === "Bindable") || member.type !== "TSPropertySignature" || member.computed) return [];
366
+ if (member.key.type === "Identifier") return [member.key.name];
367
+ return member.key.type === "Literal" ? [String(member.key.value)] : [];
368
+ });
369
+ }
323
370
  function analyze$1(file) {
324
371
  return new Analyzer(file).run();
325
372
  }
@@ -328,8 +375,11 @@ var Analyzer = class {
328
375
  scopes = [];
329
376
  declarations = [];
330
377
  sites = [];
378
+ bindings = [];
331
379
  diagnostics = [];
332
380
  refs = [];
381
+ /** The type arguments of the `$props<T>()` calls. */
382
+ propsTypes = [];
333
383
  module;
334
384
  component;
335
385
  constructor(file) {
@@ -346,6 +396,7 @@ var Analyzer = class {
346
396
  for (const style of this.file.styles) for (const variable of style.variables) this.createExpressionSite("style", this.component, variable, "style");
347
397
  this.visitNodes(this.file.children, this.component);
348
398
  this.addProvidedFunctions();
399
+ this.checkBindableProps();
349
400
  for (const site of this.sites) new Resolver(this, site).run();
350
401
  this.addPendingReads();
351
402
  this.resolveRefs();
@@ -356,6 +407,7 @@ var Analyzer = class {
356
407
  scopes: this.scopes,
357
408
  declarations: this.declarations,
358
409
  sites: this.sites,
410
+ bindings: this.bindings,
359
411
  diagnostics: this.diagnostics
360
412
  };
361
413
  }
@@ -379,6 +431,20 @@ var Analyzer = class {
379
431
  reference.site.reads.push(read);
380
432
  }
381
433
  }
434
+ /**
435
+ * Warns about a prop that the type of `$props<T>()` marks `Bindable`, but
436
+ * that the component reads only with `const`, so a binding of it never
437
+ * changes the parent's value. It reads the type in the file: a type
438
+ * literal, or an interface or a type alias of the scripts.
439
+ */
440
+ checkBindableProps() {
441
+ const bindable = /* @__PURE__ */ new Set();
442
+ for (const type of this.propsTypes) for (const name of bindableNames(type, this.file)) bindable.add(name);
443
+ if (bindable.size === 0) return;
444
+ const props = this.declarations.filter((declaration) => declaration.kind === "prop" && declaration.scope === this.component && declaration.propKey !== void 0 && bindable.has(declaration.propKey));
445
+ const written = new Set(props.filter((declaration) => declaration.writable).map((declaration) => declaration.propKey));
446
+ for (const declaration of props) if (!written.has(declaration.propKey)) this.report("warning", `The prop "${declaration.propKey}" is Bindable, but the component reads it with const and never writes it. Destructure it with let`, declaration.range);
447
+ }
382
448
  report(severity, message, at) {
383
449
  this.diagnostics.push({
384
450
  severity,
@@ -439,6 +505,48 @@ var Analyzer = class {
439
505
  site.range = range(expression);
440
506
  return site;
441
507
  }
508
+ /**
509
+ * Reads the wrappers of `brumate/events` around a handler, such as
510
+ * `prevent(move, 'Enter')`, into the modifiers that `b-on` holds, so the
511
+ * loader applies them before the handler's code loads. A modifier in the
512
+ * attribute name, such as `onSubmit:prevent`, still works, with a warning.
513
+ */
514
+ readWrappers(site, attribute, scope) {
515
+ if (attribute.modifiers.length > 0) {
516
+ const [first] = attribute.modifiers;
517
+ 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);
518
+ }
519
+ const modifiers = [];
520
+ let node = attribute.handler.ast;
521
+ for (;;) {
522
+ while (node.type === "ParenthesizedExpression") node = node.expression;
523
+ if (node.type !== "CallExpression" || node.callee.type !== "Identifier") break;
524
+ const imported = lookup(scope, node.callee.name)?.imported;
525
+ const name = imported?.source === EVENTS_MODULE ? imported.name : void 0;
526
+ if (name === "transition" && node.arguments[0]) {
527
+ node = node.arguments[0];
528
+ continue;
529
+ }
530
+ if (name === void 0 || !WRAPPERS$1.has(name)) break;
531
+ const [handler, ...rest] = node.arguments;
532
+ if (!handler || name !== "prevent" && rest.length > 0) {
533
+ this.report("error", `${name} takes a handler`, node);
534
+ break;
535
+ }
536
+ if (rest.length > 0) {
537
+ const keys = rest.map((key) => key.type === "Literal" && typeof key.value === "string" ? key.value : void 0);
538
+ const wrong = rest.find((_, index) => {
539
+ const key = keys[index];
540
+ return key === void 0 || !(KEY_NAMES.includes(key) || /^[A-Za-z0-9]$/.test(key));
541
+ });
542
+ if (!KEY_EVENTS.has(attribute.event)) this.report("error", "Only prevent of a keyboard event takes keys, such as onKeyDown", node);
543
+ 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);
544
+ modifiers.push(`prevent(${keys.join(",")})`);
545
+ } else modifiers.push(name);
546
+ node = handler;
547
+ }
548
+ if (modifiers.length > 0) site.modifiers = modifiers;
549
+ }
442
550
  declareFunction(name, fn, scope, at) {
443
551
  const server = hasUseServer(fn);
444
552
  const kind = server ? "server-function" : "function";
@@ -481,7 +589,8 @@ var Analyzer = class {
481
589
  if (specifier.type === "ImportSpecifier" && specifier.importKind === "type") continue;
482
590
  const declaration = this.addDeclaration(scope, specifier.local.name, "import", specifier.local);
483
591
  if (specifier.type !== "ImportNamespaceSpecifier") {
484
- const imported = specifier.type === "ImportDefaultSpecifier" ? "default" : specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
592
+ let imported = "default";
593
+ if (specifier.type !== "ImportDefaultSpecifier") imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
485
594
  declaration.imported = {
486
595
  source: statement.source.value,
487
596
  name: imported
@@ -517,11 +626,14 @@ var Analyzer = class {
517
626
  this.createSite("setup", scope, statement, "setup");
518
627
  break;
519
628
  case "ExpressionStatement": {
520
- const name = calleeName(statement.expression);
629
+ const name = calleeName$1(statement.expression);
521
630
  if (name === "$title") {
522
631
  const call = statement.expression;
523
632
  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");
633
+ else {
634
+ this.report("warning", "$title is replaced by <title> in #head, such as #head { <title>{`${count} left`}</title> }, and goes in a later version", call);
635
+ this.createSite("title", scope, call.arguments[0], "title");
636
+ }
525
637
  } else if (name === "$setContext") this.declareProvide(statement.expression, scope);
526
638
  else if (name === "$effect" || name === "$client") this.declareEffect(statement.expression, name, scope);
527
639
  else this.createSite("setup", scope, statement, "setup");
@@ -536,21 +648,28 @@ var Analyzer = class {
536
648
  return type === "TSInterfaceDeclaration" || type === "TSTypeAliasDeclaration";
537
649
  }
538
650
  declareVariable(declarator, kind, scope, isComponent) {
539
- const init = declarator.init;
540
651
  const id = declarator.id;
541
- const name = calleeName(init);
652
+ const awaited = declarator.init?.type === "AwaitExpression" ? declarator.init : void 0;
653
+ const awaitedName = awaited && calleeName$1(awaited.argument);
654
+ if (awaited && awaitedName !== void 0 && MACROS.has(awaitedName) && awaitedName !== "$memo") this.report("error", `await works with $memo, not ${awaitedName}`, awaited);
655
+ const init = awaitedName === "$memo" ? awaited.argument : declarator.init;
656
+ const name = calleeName$1(init);
542
657
  const call = init;
543
658
  if (name === "$props") {
544
659
  if (!isComponent) this.report("error", "$props() can only be called in the component script", declarator);
545
- if (kind !== "const") this.report("error", "Assign $props() to a const", declarator);
660
+ if (kind !== "const" && kind !== "let") this.report("error", "Assign $props() to a const or a let", declarator);
546
661
  if (call.arguments.length > 0) this.report("error", "$props() takes no arguments", call);
662
+ const type = call.typeArguments?.params[0];
663
+ if (type) this.propsTypes.push(type);
547
664
  if (id.type === "ObjectPattern") {
548
665
  for (const property of id.properties) if (property.type === "RestElement") for (const binding of getPatternNames(property.argument)) this.addDeclaration(scope, binding.name, "props-rest", binding);
549
666
  else {
550
- const key = property.computed ? void 0 : property.key.type === "Identifier" ? property.key.name : String(property.key.value);
667
+ let key;
668
+ if (!property.computed) key = property.key.type === "Identifier" ? property.key.name : String(property.key.value);
551
669
  for (const binding of getPatternNames(property.value)) {
552
670
  const declaration = this.addDeclaration(scope, binding.name, "prop", binding);
553
671
  declaration.propKey = key;
672
+ if (kind === "let") declaration.writable = true;
554
673
  }
555
674
  }
556
675
  this.createDefaultSites(id, scope);
@@ -568,6 +687,15 @@ var Analyzer = class {
568
687
  declaration.idIndex = [...scope.declarations.values()].filter((item) => item.idIndex !== void 0).length;
569
688
  return;
570
689
  }
690
+ if (name === "$route" || name === "$navigation") {
691
+ if (kind !== "const" || id.type !== "Identifier") {
692
+ this.report("error", MISPLACED[name], declarator);
693
+ return;
694
+ }
695
+ 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);
696
+ this.addDeclaration(scope, id.name, "context", id);
697
+ return;
698
+ }
571
699
  if (name === "$getContext") {
572
700
  if (kind !== "const" || id.type !== "Identifier") {
573
701
  this.report("error", "Read a context with \"const name = $getContext(Context)\"", declarator);
@@ -593,6 +721,27 @@ var Analyzer = class {
593
721
  declaration.action = argument.name;
594
722
  return;
595
723
  }
724
+ if (name === "$debounced" || name === "$throttled") {
725
+ if (kind !== "const") this.report("error", `Declare ${name} with const`, declarator);
726
+ if (id.type !== "Identifier") {
727
+ this.report("error", `${name} cannot be destructured`, id);
728
+ return;
729
+ }
730
+ const [argument, wait] = call.arguments;
731
+ const declaration = this.addDeclaration(scope, id.name, "memo", id);
732
+ if (!argument || call.arguments.length !== 2) {
733
+ this.report("error", `${name} takes a value and a wait in milliseconds`, call);
734
+ return;
735
+ }
736
+ const ms = wait?.type === "Literal" && typeof wait.value === "number" ? wait.value : NaN;
737
+ if (!(ms >= 0 && ms <= 2147483647)) this.report("error", `The wait of ${name} must be a number of milliseconds, such as 300`, wait);
738
+ declaration.timing = {
739
+ kind: name === "$debounced" ? "debounced" : "throttled",
740
+ ms
741
+ };
742
+ declaration.site = this.createSite("memo", scope, argument, `memo ${id.name}`, { declaration });
743
+ return;
744
+ }
596
745
  if (name === "$signal" || name === "$memo" || name === "$optimistic") {
597
746
  const expected = name === "$memo" ? "const" : "let";
598
747
  if (kind !== expected) this.report("error", `Declare ${name} with ${expected}`, declarator);
@@ -611,6 +760,7 @@ var Analyzer = class {
611
760
  return;
612
761
  }
613
762
  const declaration = this.addDeclaration(scope, id.name, "memo", id);
763
+ if (awaited && name === "$memo") declaration.awaited = true;
614
764
  if (!argument) {
615
765
  this.report("error", `${name} needs a value`, call);
616
766
  return;
@@ -667,6 +817,78 @@ var Analyzer = class {
667
817
  for (const part of parts) if (isFunction$2(part) || part.type === "Identifier" && ["function", "server-function"].includes(lookup(site.scope, part.name)?.kind ?? "")) this.createSite("prop", site.scope, part, "provided function");
668
818
  }
669
819
  }
820
+ /**
821
+ * `$handler(fn, ...args)`: `fn` is a client root, as a function prop is, and
822
+ * its reference goes with the arguments. `isLocal` tells a name that a
823
+ * function around the call declares: `fn` cannot read one, since only the
824
+ * values of the scope and the arguments reach the browser.
825
+ */
826
+ declareHandler(call, scope, isLocal) {
827
+ const [fn] = call.arguments;
828
+ if (!fn || fn.type === "SpreadElement" || !this.isHandlerFunction(fn, scope)) {
829
+ this.report("error", "$handler needs a function as its first argument: a function expression, a function of the script, or one of them in a wrapper of brumate/events", call);
830
+ return;
831
+ }
832
+ for (const name of freeNames(fn)) if (isLocal(name)) {
833
+ this.report("error", `The handler reads "${name}", a value of the function around $handler, which the browser does not have. Pass it as an argument: $handler(fn, ${name})`, fn);
834
+ return;
835
+ }
836
+ if (call.arguments.slice(1).some((argument) => argument.type === "SpreadElement")) this.report("error", "The arguments of $handler cannot be spread", call);
837
+ this.createSite("prop", scope, fn, "handler", {
838
+ handler: call,
839
+ modifiers: this.handlerModifiers(fn, scope)
840
+ });
841
+ }
842
+ /**
843
+ * The function of `$bind(name, fn)`, which a write of the binding calls
844
+ * with the new value in place of writing the name. It compiles as a
845
+ * handler does, with its own part.
846
+ */
847
+ declareSetter(call, scope, isLocal) {
848
+ const fn = call.arguments[1];
849
+ if (fn.type === "SpreadElement" || !this.isHandlerFunction(fn, scope)) {
850
+ this.report("error", "The second argument of $bind is a function that takes the new value: a function expression, or a function of the script", fn);
851
+ return;
852
+ }
853
+ for (const name of freeNames(fn)) if (isLocal(name)) {
854
+ this.report("error", `The setter reads "${name}", a value of the function around $bind, which the browser does not have`, fn);
855
+ return;
856
+ }
857
+ return this.createSite("prop", scope, fn, "setter", { setter: call });
858
+ }
859
+ /**
860
+ * The modifiers of the wrappers around the function of `$handler`, such as
861
+ * `prevent`, as `b-on` holds them. Markup that the browser renders writes
862
+ * them without loading the code of the handler.
863
+ */
864
+ handlerModifiers(node, scope) {
865
+ const modifiers = [];
866
+ while (node.type === "CallExpression" && node.callee.type === "Identifier") {
867
+ const imported = lookup(scope, node.callee.name)?.imported;
868
+ const name = imported?.source === EVENTS_MODULE ? imported.name : void 0;
869
+ const [handler, ...keys] = node.arguments;
870
+ if (name === "transition" && handler) {
871
+ node = handler;
872
+ continue;
873
+ }
874
+ if (name === void 0 || !WRAPPERS$1.has(name) || !handler) break;
875
+ const names = keys.map((key) => key.type === "Literal" && typeof key.value === "string" ? key.value : void 0);
876
+ if (names.some((key) => key === void 0)) this.report("error", "Name each key of prevent as a string, such as 'Enter'", node);
877
+ modifiers.push(names.length > 0 ? `${name}(${names.join(",")})` : name);
878
+ node = handler;
879
+ }
880
+ return modifiers.length > 0 ? modifiers : void 0;
881
+ }
882
+ /** A function, a function of the script, or one of them in wrappers of `brumate/events`. */
883
+ isHandlerFunction(node, scope) {
884
+ while (node.type === "CallExpression" && node.callee.type === "Identifier" && lookup(scope, node.callee.name)?.imported?.source === EVENTS_MODULE && node.arguments[0]) node = node.arguments[0];
885
+ if (isFunction$2(node)) return true;
886
+ if (node.type === "Identifier") {
887
+ const kind = lookup(scope, node.name)?.kind;
888
+ return kind === "function" || kind === "server-function";
889
+ }
890
+ return false;
891
+ }
670
892
  declareProvide(call, scope) {
671
893
  const [context, value] = call.arguments;
672
894
  if (!context || !value || call.arguments.length !== 2) {
@@ -745,17 +967,22 @@ var Analyzer = class {
745
967
  this.visitNodes(node.children, scope);
746
968
  break;
747
969
  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
- });
970
+ for (const attribute of node.attributes) {
971
+ const site = this.createExpressionSite("event", scope, attribute.handler, `event ${node.target}.${attribute.event}`, {
972
+ owner: node,
973
+ event: attribute
974
+ });
975
+ this.readWrappers(site, attribute, scope);
976
+ }
752
977
  break;
753
978
  default: this.visitBlock(node, scope);
754
979
  }
755
980
  }
756
981
  visitAttributes(node, scope) {
757
982
  const isComponent = node.kind === "component";
758
- const tag = node.kind === "element" ? node.tag : node.kind === "component" ? node.name : "dynamic";
983
+ let tag = "dynamic";
984
+ if (node.kind === "element") tag = node.tag;
985
+ else if (node.kind === "component") tag = node.name;
759
986
  for (const attribute of node.attributes) {
760
987
  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
988
  switch (attribute.kind) {
@@ -764,12 +991,14 @@ var Analyzer = class {
764
991
  case "value":
765
992
  this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.value, `${isComponent ? "prop" : "attribute"} ${tag}.${attribute.name}`, { owner: node });
766
993
  break;
767
- case "event":
768
- this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
994
+ case "event": {
995
+ const site = this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
769
996
  owner: node,
770
997
  event: isComponent ? void 0 : attribute
771
998
  });
999
+ if (!isComponent) this.readWrappers(site, attribute, scope);
772
1000
  break;
1001
+ }
773
1002
  case "ref":
774
1003
  if (node.kind === "element") this.refs.push({
775
1004
  attribute,
@@ -847,7 +1076,9 @@ var Analyzer = class {
847
1076
  this.visitBody(block.body, scope, block);
848
1077
  break;
849
1078
  case "client":
1079
+ case "defer":
850
1080
  this.visitBody(block.body, scope, block);
1081
+ if (block.fallback) this.visitBody(block.fallback, scope, block);
851
1082
  break;
852
1083
  case "offscreen":
853
1084
  this.header(block, scope, block.visible, "offscreen");
@@ -956,6 +1187,45 @@ var Resolver = class {
956
1187
  this.site.calls.add(declaration);
957
1188
  if (this.untracked === 0) this.site.trackedCalls.add(declaration);
958
1189
  }
1190
+ return reference;
1191
+ }
1192
+ /**
1193
+ * `$bind(name)` passes a child a reference to a signal, or to a prop that
1194
+ * the component writes, so the child's writes reach it. It is the whole
1195
+ * value of a prop of a component. The name gets a slot, which the
1196
+ * reference points to.
1197
+ */
1198
+ declareBinding(call) {
1199
+ let node = this.site.node;
1200
+ while (node.type === "ParenthesizedExpression") node = node.expression;
1201
+ const owner = this.site.owner;
1202
+ const element = this.site.kind === "attribute" && owner?.kind === "element" ? owner.attributes.find((attribute) => attribute.kind === "value" && attribute.value.ast === this.site.node) : void 0;
1203
+ const onElement = element?.kind === "value" && (element.name === "value" || element.name === "checked") && [
1204
+ "input",
1205
+ "select",
1206
+ "textarea"
1207
+ ].includes(owner.tag.toLowerCase());
1208
+ if (!(this.site.kind === "prop" || onElement) || node !== call) {
1209
+ this.analyzer.report("error", "Pass $bind(name) as the value of a prop of a component, or of value or checked of an input, a select or a textarea", call);
1210
+ return;
1211
+ }
1212
+ const [target, fn, ...rest] = call.arguments;
1213
+ if (!target || target.type !== "Identifier" || rest.length > 0) {
1214
+ this.analyzer.report("error", "$bind takes the name of a signal, and a function that writes it, such as $bind(open) or $bind(open, (next) => (open = next))", call);
1215
+ return;
1216
+ }
1217
+ const declaration = this.isLocal(target.name) ? void 0 : lookup(this.site.scope, target.name);
1218
+ if (!declaration || !(declaration.kind === "signal" || declaration.kind === "prop" && declaration.writable)) {
1219
+ this.analyzer.report("error", `$bind takes a signal, or a prop that the component destructures with let, and "${target.name}" is not one`, target);
1220
+ return;
1221
+ }
1222
+ declaration.bound = true;
1223
+ const setter = fn === void 0 ? void 0 : this.analyzer.declareSetter(call, this.site.scope, (local) => this.isLocal(local));
1224
+ this.analyzer.bindings.push({
1225
+ call,
1226
+ declaration,
1227
+ setter
1228
+ });
959
1229
  }
960
1230
  visitChildren(node) {
961
1231
  for (const [key, child] of children(node)) if (!TYPE_KEYS.has(key)) this.visit(child);
@@ -1050,10 +1320,20 @@ var Resolver = class {
1050
1320
  case "BreakStatement":
1051
1321
  case "ContinueStatement":
1052
1322
  case "MetaProperty": return;
1053
- case "AwaitExpression":
1323
+ case "AwaitExpression": {
1324
+ const argument = node.argument;
1325
+ if (argument.type === "Identifier") {
1326
+ const declaration = this.isLocal(argument.name) ? void 0 : lookup(this.site.scope, argument.name);
1327
+ if (declaration?.kind === "memo" || declaration?.kind === "async-memo") {
1328
+ const reference = this.reference(argument, "read");
1329
+ if (reference) reference.await = range(node);
1330
+ return;
1331
+ }
1332
+ }
1054
1333
  if (this.functionDepth === 0) this.site.awaits = true;
1055
- this.visit(node.argument);
1334
+ this.visit(argument);
1056
1335
  return;
1336
+ }
1057
1337
  case "CallExpression": {
1058
1338
  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
1339
  const target = lookup(this.site.scope, node.arguments[0].name);
@@ -1087,6 +1367,16 @@ var Resolver = class {
1087
1367
  for (const argument of recipe ? [recipe, ...rest] : rest) this.visit(argument);
1088
1368
  return;
1089
1369
  }
1370
+ if (name === "$bind") {
1371
+ this.declareBinding(node);
1372
+ for (const argument of node.arguments) this.visit(argument);
1373
+ return;
1374
+ }
1375
+ if (name === "$handler") {
1376
+ this.analyzer.declareHandler(node, this.site.scope, (local) => this.isLocal(local));
1377
+ for (const argument of node.arguments.slice(1)) this.visit(argument);
1378
+ return;
1379
+ }
1090
1380
  if (COMPILE_TIME_FUNCTIONS.has(name)) this.analyzer.report("error", MISPLACED[name] ?? `${name} cannot be used here`, node);
1091
1381
  else if (name in REMOVED) this.analyzer.report("error", REMOVED[name], node);
1092
1382
  }
@@ -1192,6 +1482,40 @@ function varNames(node, names = []) {
1192
1482
  }
1193
1483
  return names;
1194
1484
  }
1485
+ /**
1486
+ * The names that code reads and does not declare itself, such as what a
1487
+ * function reads from around it. Property names are not reads.
1488
+ */
1489
+ function freeNames(node) {
1490
+ const free = /* @__PURE__ */ new Set();
1491
+ const visit = (current, bound) => {
1492
+ if (isFunction$2(current)) {
1493
+ const inner = new Set(bound);
1494
+ for (const param of current.params) for (const name of getPatternNames(param)) inner.add(name.name);
1495
+ if (current.type === "FunctionExpression" && current.id) inner.add(current.id.name);
1496
+ const body = current.body;
1497
+ if (body?.type === "BlockStatement") for (const name of [...lexicalNames(body.body), ...varNames(body)]) inner.add(name);
1498
+ for (const param of current.params) visit(param, inner);
1499
+ if (body) visit(body, inner);
1500
+ return;
1501
+ }
1502
+ if (current.type === "Identifier") {
1503
+ if (!bound.has(current.name)) free.add(current.name);
1504
+ return;
1505
+ }
1506
+ if (current.type === "MemberExpression" && !current.computed) {
1507
+ visit(current.object, bound);
1508
+ return;
1509
+ }
1510
+ if (current.type === "Property" && !current.computed) {
1511
+ visit(current.value, bound);
1512
+ return;
1513
+ }
1514
+ for (const [, child] of children(current)) visit(child, bound);
1515
+ };
1516
+ visit(node, /* @__PURE__ */ new Set());
1517
+ return free;
1518
+ }
1195
1519
  //#endregion
1196
1520
  //#region src/error.ts
1197
1521
  function getLocation(source, offset) {
@@ -1277,13 +1601,37 @@ function isLiveProp(declaration, liveProps) {
1277
1601
  function resetUsed(model, block, reached) {
1278
1602
  return model.declarations.some((declaration) => declaration.kind === "reset" && declaration.block === block && declaration.reads.some((read) => reached.has(read.site)));
1279
1603
  }
1604
+ /** Sites whose code runs in the browser after the page renders, and can throw there. */
1605
+ const CLIENT_CODE = /* @__PURE__ */ new Set([
1606
+ "event",
1607
+ "effect",
1608
+ "client"
1609
+ ]);
1610
+ /**
1611
+ * True if the body of a `#try` holds code that runs in the browser: a
1612
+ * handler, an effect, a `$client` callback or a memo that loads. An error
1613
+ * in it renders the `#catch` body in the browser, so both bodies ship.
1614
+ */
1615
+ function tryCatchesClient(model, block) {
1616
+ const body = model.scopes.find((scope) => scope.block === block && scope.body === block.body);
1617
+ 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));
1618
+ }
1280
1619
  /** True if a site's expression is a function, such as a function passed as a prop. */
1620
+ /** True for a site whose value is a `#template`, such as the prop `item=option`. */
1621
+ function isTemplateValue(site) {
1622
+ return site.node.type === "Identifier" && lookup(site.scope, site.node.name)?.kind === "template";
1623
+ }
1281
1624
  function isFunctionValue(site) {
1282
- const node = site.node;
1625
+ let node = site.node;
1626
+ for (;;) {
1627
+ while (node.type === "ParenthesizedExpression") node = node.expression;
1628
+ if (node.type !== "CallExpression" || node.callee.type !== "Identifier" || lookup(site.scope, node.callee.name)?.imported?.source !== "brumate/events" || !node.arguments[0]) break;
1629
+ node = node.arguments[0];
1630
+ }
1283
1631
  if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") return true;
1284
1632
  if (node.type === "Identifier") {
1285
1633
  const kind = lookup(site.scope, node.name)?.kind;
1286
- return kind === "function" || kind === "server-function";
1634
+ return kind === "function" || kind === "server-function" || kind === "template";
1287
1635
  }
1288
1636
  return false;
1289
1637
  }
@@ -1389,14 +1737,14 @@ function buildGraph(model, options = {}) {
1389
1737
  if (created.has(scope)) continue;
1390
1738
  const block = scope.block;
1391
1739
  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));
1740
+ 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
1741
  const templateUsed = scope.kind === "template" && templateCallChanges(scope);
1394
1742
  if (parentCreated || blockLive || templateUsed) created.add(scope);
1395
1743
  }
1396
1744
  for (const site of model.sites) if (site.kind === "event" || site.kind === "client" || site.kind === "prop" && isFunctionValue(site) || site.kind === "effect" && live.has(siteNodes.get(site)) || created.has(site.scope)) reach(site);
1397
1745
  for (const [declaration, node] of declarationNodes) {
1398
1746
  if (live.has(node)) continue;
1399
- if ((declaration.kind === "prop" || declaration.kind === "props-rest") && isLiveProp(declaration, options.liveProps) || declaration.kind === "context" || declaration.kind === "action" || isMemoKind(declaration.kind) && [...declaration.site?.calls ?? []].some((callee) => callee.refreshed) || declaration.optimistic !== void 0 && declaration.writes.some((write) => reached.has(write.site)) || declaration.kind === "signal" && (declaration.writes.some((write) => reached.has(write.site)) || declaration.refs.some((ref) => created.has(ref.scope))) || declaration.kind === "error" && declaration.block?.kind === "try" && tryChanges(declaration.block) || declaration.kind === "template-param" && templateCallChanges(declaration.scope)) live.add(node);
1747
+ if ((declaration.kind === "prop" || declaration.kind === "props-rest") && isLiveProp(declaration, options.liveProps) || declaration.kind === "context" || declaration.kind === "action" || isMemoKind(declaration.kind) && [...declaration.site?.calls ?? []].some((callee) => callee.refreshed) || declaration.optimistic !== void 0 && declaration.writes.some((write) => reached.has(write.site)) || declaration.kind === "signal" && (declaration.writes.some((write) => reached.has(write.site)) || declaration.refs.some((ref) => created.has(ref.scope))) || declaration.kind === "error" && declaration.block?.kind === "try" && tryChanges(declaration.block) || declaration.bound === true || declaration.kind === "template-param" && templateCallChanges(declaration.scope)) live.add(node);
1400
1748
  }
1401
1749
  for (let propagated = true; propagated;) {
1402
1750
  propagated = false;
@@ -1426,6 +1774,24 @@ function buildGraph(model, options = {}) {
1426
1774
  message: "This $effect reads no value that changes on the client, so it never runs",
1427
1775
  range: site.range
1428
1776
  });
1777
+ for (const scope of model.scopes) {
1778
+ const block = scope.block;
1779
+ if (block?.kind !== "defer" || scope.body !== block.body) continue;
1780
+ let message;
1781
+ for (let outer = scope.parent; outer && !message; outer = outer.parent) {
1782
+ const around = outer.block;
1783
+ if (around?.kind === "client" && outer.body === around.body) message = "#defer cannot be inside a #client body";
1784
+ else if (created.has(outer)) message = "#defer cannot be in markup that the browser renders";
1785
+ }
1786
+ if (message) diagnostics.push({
1787
+ severity: "error",
1788
+ message,
1789
+ range: {
1790
+ start: block.start,
1791
+ end: block.start + 6
1792
+ }
1793
+ });
1794
+ }
1429
1795
  return {
1430
1796
  model,
1431
1797
  nodes,
@@ -1638,6 +2004,7 @@ const BLOCK_KEYWORDS = /* @__PURE__ */ new Set([
1638
2004
  "head",
1639
2005
  "client",
1640
2006
  "offscreen",
2007
+ "reveal",
1641
2008
  "defer",
1642
2009
  "template"
1643
2010
  ]);
@@ -1985,6 +2352,7 @@ var Parser = class {
1985
2352
  const name = parts[0];
1986
2353
  const modifiers = parts.slice(1);
1987
2354
  for (const modifier of modifiers) if (!MODIFIERS.has(modifier)) this.fail(`Unknown event modifier ":${modifier}"`, start);
2355
+ if (owner === "component" && modifiers.length > 0) this.fail(`Modifiers apply to elements. Put ":${modifiers[0]}" on the element that the component renders`, start);
1988
2356
  if (this.peek() !== "=") this.fail("Expected an event handler", this.pos);
1989
2357
  this.pos++;
1990
2358
  const value = this.parseValue();
@@ -2183,6 +2551,39 @@ var Parser = class {
2183
2551
  };
2184
2552
  }
2185
2553
  /** Parses `( … )` at the current position, after optional whitespace. */
2554
+ /**
2555
+ * `#reveal ('sequential', collapsed) { … }`: an order as a string, and
2556
+ * `collapsed`, both optional. The body is the children of a fragment.
2557
+ */
2558
+ parseReveal(start) {
2559
+ const header = this.parseHeader("reveal", false);
2560
+ const reveal = {
2561
+ order: "sequential",
2562
+ collapsed: false
2563
+ };
2564
+ if (header) {
2565
+ const code = this.source.slice(header.start, header.end);
2566
+ let offset = header.start;
2567
+ for (const part of code.split(",")) {
2568
+ const word = part.trim();
2569
+ const string = /^(['"])(sequential|backwards|together|natural)\1$/.exec(word);
2570
+ if (string) reveal.order = string[2];
2571
+ else if (word === "collapsed") reveal.collapsed = true;
2572
+ else this.fail("#reveal takes an order, 'sequential', 'backwards', 'together' or 'natural', and collapsed, such as #reveal ('sequential', collapsed)", offset + part.length - part.trimStart().length);
2573
+ offset += part.length + 1;
2574
+ }
2575
+ }
2576
+ if (reveal.collapsed && reveal.order !== "sequential") this.fail(`collapsed shows the fallback of the next body to show, so it needs the order 'sequential', not '${reveal.order}'`, header.start);
2577
+ const body = this.parseBody("reveal");
2578
+ if (body.script) this.fail("#reveal has no script of its own", body.script.start);
2579
+ return {
2580
+ kind: "fragment",
2581
+ start,
2582
+ end: this.pos,
2583
+ children: body.children,
2584
+ reveal
2585
+ };
2586
+ }
2186
2587
  parseHeader(keyword, required) {
2187
2588
  this.skipWhitespace();
2188
2589
  if (this.peek() !== "(") {
@@ -2340,6 +2741,7 @@ var Parser = class {
2340
2741
  end: this.pos,
2341
2742
  body: this.parseBody("head")
2342
2743
  };
2744
+ case "reveal": return this.parseReveal(start);
2343
2745
  case "portal": {
2344
2746
  const header = this.parseHeader("portal", false);
2345
2747
  const target = header ? this.expression(header.start, header.end) : void 0;
@@ -2351,21 +2753,25 @@ var Parser = class {
2351
2753
  body: this.parseBody("portal")
2352
2754
  };
2353
2755
  }
2354
- case "client": {
2355
- const header = this.parseHeader("client", false);
2756
+ case "client":
2757
+ case "defer": {
2758
+ const header = this.parseHeader(keyword, false);
2356
2759
  let trigger = "visible";
2357
2760
  if (header) {
2358
2761
  const code = this.source.slice(header.start, header.end).trim();
2359
2762
  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);
2763
+ if (!/^(['"]).*\1$/.test(code) || !CLIENT_TRIGGERS.has(value)) this.fail(`The trigger of #${keyword} must be "visible", "idle" or "load"`, header.start);
2361
2764
  trigger = value;
2362
2765
  }
2766
+ const body = this.parseBody(keyword);
2767
+ const fallback = this.parseBranch("else") ? this.parseBody("else") : void 0;
2363
2768
  return {
2364
- kind: "client",
2769
+ kind: keyword,
2365
2770
  start,
2366
2771
  end: this.pos,
2367
2772
  trigger,
2368
- body: this.parseBody("client")
2773
+ body,
2774
+ fallback
2369
2775
  };
2370
2776
  }
2371
2777
  case "offscreen": {
@@ -2380,7 +2786,6 @@ var Parser = class {
2380
2786
  body
2381
2787
  };
2382
2788
  }
2383
- case "defer": return this.fail("#defer is reserved for a future block", start);
2384
2789
  default: return this.fail(`Unknown block #${keyword}`, start);
2385
2790
  }
2386
2791
  }
@@ -2501,12 +2906,13 @@ function childrenOf(node) {
2501
2906
  case "switch": return [...node.cases.flatMap((branch) => branch.body.children), ...node.fallback?.children ?? []];
2502
2907
  case "for":
2503
2908
  case "repeat":
2504
- case "loading": return [...node.body.children, ...node.fallback?.children ?? []];
2909
+ case "loading":
2910
+ case "client":
2911
+ case "defer": return [...node.body.children, ...node.fallback?.children ?? []];
2505
2912
  case "try": return [...node.body.children, ...node.fallback.children];
2506
2913
  case "key":
2507
2914
  case "portal":
2508
2915
  case "head":
2509
- case "client":
2510
2916
  case "offscreen": return node.body.children;
2511
2917
  default: return [];
2512
2918
  }
@@ -2737,6 +3143,34 @@ function checkAccessibility(file) {
2737
3143
  roots.forEach((nodes) => visit(nodes, false));
2738
3144
  return diagnostics;
2739
3145
  }
3146
+ const NAME = "[A-Za-z_$][\\w$]*";
3147
+ const REFRESH = new RegExp(`\\.refresh\\(\\s*(${NAME}(?:\\s*\\.\\s*${NAME})*)?\\s*([,)])`, "g");
3148
+ const IMPORT = /import\s+(?:type\s+)?\{([^}]*)\}\s*from/g;
3149
+ /**
3150
+ * The names of the server functions that the sources pass to `refresh`, by
3151
+ * the name that their file exports. A local name of an import, such as `ln`
3152
+ * of `import { listNotes as ln }`, counts as the name that it imports. A
3153
+ * call that the scan cannot read, such as `refresh(pick())`, adds `ANY`.
3154
+ */
3155
+ function refreshedNames(sources) {
3156
+ const names = /* @__PURE__ */ new Set();
3157
+ for (const source of sources) {
3158
+ if (!source.includes(".refresh(")) continue;
3159
+ const aliases = /* @__PURE__ */ new Map();
3160
+ for (const [, list] of source.matchAll(IMPORT)) for (const item of list.split(",")) {
3161
+ const [imported, local] = item.trim().replace(/^type\s+/, "").split(/\s+as\s+/);
3162
+ if (imported && local) aliases.set(local.trim(), imported.trim());
3163
+ }
3164
+ for (const match of source.matchAll(REFRESH)) {
3165
+ const target = match[1];
3166
+ if (target === void 0) continue;
3167
+ const last = target.split(".").at(-1).trim();
3168
+ names.add(aliases.get(last) ?? last);
3169
+ }
3170
+ if (source.split(".refresh(").length - 1 > [...source.matchAll(REFRESH)].length) names.add("*");
3171
+ }
3172
+ return names;
3173
+ }
2740
3174
  //#endregion
2741
3175
  //#region src/captures.ts
2742
3176
  /** Classes whose instances brumate can send to the browser. */
@@ -2746,6 +3180,16 @@ const SENDABLE = /* @__PURE__ */ new Set([
2746
3180
  "Date",
2747
3181
  "URL",
2748
3182
  "URLSearchParams",
3183
+ "Headers",
3184
+ "FormData",
3185
+ "Request",
3186
+ "Response",
3187
+ "ReadableStream",
3188
+ "Event",
3189
+ "CustomEvent",
3190
+ "DOMException",
3191
+ "AbortSignal",
3192
+ "ImageData",
2749
3193
  "Map",
2750
3194
  "Set",
2751
3195
  "Promise",
@@ -2775,7 +3219,12 @@ const SENDABLE = /* @__PURE__ */ new Set([
2775
3219
  "Boolean"
2776
3220
  ]);
2777
3221
  /** Compile-time functions whose argument is the value, such as `$signal(new Foo())`. */
2778
- const WRAPPERS = /* @__PURE__ */ new Set(["$signal", "$memo"]);
3222
+ const WRAPPERS = /* @__PURE__ */ new Set([
3223
+ "$signal",
3224
+ "$memo",
3225
+ "$debounced",
3226
+ "$throttled"
3227
+ ]);
2779
3228
  /** The value that a declaration holds, by the offset of its name. */
2780
3229
  function initializers(file) {
2781
3230
  const result = /* @__PURE__ */ new Map();
@@ -2790,21 +3239,41 @@ function initializers(file) {
2790
3239
  if (file.instanceScript) visit(file.instanceScript.program);
2791
3240
  return result;
2792
3241
  }
2793
- /** The class of a value made with `new`, unless brumate can send it. */
2794
- function unsendableClass(node) {
3242
+ /** The class of a value made with `new`, unless brumate or a plugin of the app can send it. */
3243
+ function unsendableClass(node, sendable) {
2795
3244
  if (node.type !== "NewExpression") return;
2796
3245
  const callee = node.callee;
2797
- const name = callee.type === "Identifier" ? callee.name : callee.type === "MemberExpression" && callee.property.type === "Identifier" ? callee.property.name : "class";
2798
- return SENDABLE.has(name) ? void 0 : name;
3246
+ let name = "class";
3247
+ if (callee.type === "Identifier") name = callee.name;
3248
+ else if (callee.type === "MemberExpression" && callee.property.type === "Identifier") name = callee.property.name;
3249
+ return SENDABLE.has(name) || sendable.includes(name) ? void 0 : name;
3250
+ }
3251
+ /**
3252
+ * The classes that the plugins of a serial entry send: the names on the
3253
+ * right of `instanceof` in the file, such as `Money` in
3254
+ * `test: (value) => value instanceof Money`.
3255
+ */
3256
+ function entryClasses(program) {
3257
+ const names = /* @__PURE__ */ new Set();
3258
+ const visit = (node) => {
3259
+ if (node.type === "BinaryExpression" && node.operator === "instanceof") {
3260
+ const right = node.right;
3261
+ if (right.type === "Identifier") names.add(right.name);
3262
+ else if (right.type === "MemberExpression" && right.property.type === "Identifier") names.add(right.property.name);
3263
+ }
3264
+ for (const [, child] of children(node)) visit(child);
3265
+ };
3266
+ visit(program);
3267
+ return [...names];
2799
3268
  }
2800
3269
  /** Errors for values that the browser reads but that cannot be sent to it. */
2801
- function checkCaptures(file, plan) {
3270
+ function checkCaptures(file, plan, sendable = []) {
2802
3271
  const values = initializers(file);
2803
3272
  const diagnostics = [];
2804
3273
  const reported = /* @__PURE__ */ new Set();
2805
3274
  for (const layout of plan.scopes.values()) for (const declaration of layout.slots) {
2806
3275
  const init = values.get(declaration.range.start);
2807
- const kind = init && unsendableClass(init);
3276
+ const kind = init && unsendableClass(init, sendable);
2808
3277
  if (!kind || reported.has(declaration)) continue;
2809
3278
  reported.add(declaration);
2810
3279
  const reader = declaration.reads.find((read) => plan.graph.reached.has(read.site))?.site;
@@ -2820,6 +3289,66 @@ function checkCaptures(file, plan) {
2820
3289
  return diagnostics;
2821
3290
  }
2822
3291
  //#endregion
3292
+ //#region src/env-check.ts
3293
+ /** The property that a read of `env` reads, such as `DATABASE_URL` for `env.DATABASE_URL`. */
3294
+ function propertyAt(node, at) {
3295
+ if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.start === at) {
3296
+ if (node.computed) return node.property.type === "Literal" ? String(node.property.value) : null;
3297
+ return node.property.type === "Identifier" ? node.property.name : null;
3298
+ }
3299
+ for (const [, child] of children(node)) {
3300
+ const found = propertyAt(child, at);
3301
+ if (found !== void 0) return found;
3302
+ }
3303
+ }
3304
+ /** The server variable that a read reads, or `*` for a read of the whole object. */
3305
+ function serverRead(read, server) {
3306
+ const nodes = [read.site.node, ...read.site.extra ?? []];
3307
+ for (const node of nodes) {
3308
+ const property = propertyAt(node, read.range.start);
3309
+ if (property === void 0) continue;
3310
+ if (property === null) return "*";
3311
+ return server.includes(property) ? property : void 0;
3312
+ }
3313
+ return "*";
3314
+ }
3315
+ /** Errors for server variables that code in the browser reads, or that the page state would send. */
3316
+ function checkEnv(file, plan, envImport) {
3317
+ const diagnostics = [];
3318
+ const values = initializers(file);
3319
+ const slots = /* @__PURE__ */ new Set();
3320
+ for (const layout of plan.scopes.values()) for (const declaration of layout.slots) slots.add(declaration);
3321
+ for (const declaration of plan.graph.model.declarations) {
3322
+ if (!declaration.imported) continue;
3323
+ const server = envImport(declaration.imported.source, declaration.imported.name);
3324
+ if (!server) continue;
3325
+ const name = declaration.name;
3326
+ for (const read of declaration.reads) {
3327
+ const variable = serverRead(read, server);
3328
+ if (variable === void 0) continue;
3329
+ const what = variable === "*" ? `${name}, with its server variables,` : `${name}.${variable}, a server variable,`;
3330
+ if (plan.graph.reached.has(read.site)) {
3331
+ diagnostics.push({
3332
+ severity: "error",
3333
+ message: `${what} is read by code that runs in the browser (${read.site.label}). Read it in a server function`,
3334
+ range: read.range
3335
+ });
3336
+ continue;
3337
+ }
3338
+ const holder = [...slots].find((slot) => {
3339
+ const init = values.get(slot.range.start);
3340
+ return init && read.range.start >= init.start && read.range.end <= init.end;
3341
+ });
3342
+ if (holder) diagnostics.push({
3343
+ severity: "error",
3344
+ message: `"${holder.name}" holds ${what} and code that runs in the browser reads it. Keep server variables out of values that the browser reads`,
3345
+ range: read.range
3346
+ });
3347
+ }
3348
+ }
3349
+ return diagnostics;
3350
+ }
3351
+ //#endregion
2823
3352
  //#region src/sourcemap.ts
2824
3353
  const OPEN = "";
2825
3354
  const CLOSE = "";
@@ -2936,6 +3465,57 @@ function finish(code, files, place = (offset) => ({
2936
3465
  }
2937
3466
  };
2938
3467
  }
3468
+ /**
3469
+ * The place in a source that a position of generated code came from, by a
3470
+ * source map. Lines and columns count from 1. Undefined when the map has no
3471
+ * mapping on that line at or before the column.
3472
+ */
3473
+ function originalPosition(map, line, column) {
3474
+ const state = [
3475
+ 0,
3476
+ 0,
3477
+ 0,
3478
+ 0
3479
+ ];
3480
+ let found;
3481
+ const lines = map.mappings.split(";");
3482
+ for (let index = 0; index < line && index < lines.length; index++) {
3483
+ let generated = 0;
3484
+ for (const segment of lines[index].split(",")) {
3485
+ if (!segment) continue;
3486
+ const fields = [];
3487
+ let value = 0;
3488
+ let shift = 0;
3489
+ for (const char of segment) {
3490
+ const digit = BASE64.indexOf(char);
3491
+ value += (digit & 31) << shift;
3492
+ if (digit & 32) shift += 5;
3493
+ else {
3494
+ fields.push(value & 1 ? -(value >>> 1) : value >>> 1);
3495
+ value = 0;
3496
+ shift = 0;
3497
+ }
3498
+ }
3499
+ generated += fields[0];
3500
+ if (fields.length >= 4) {
3501
+ state[1] += fields[1];
3502
+ state[2] += fields[2];
3503
+ state[3] += fields[3];
3504
+ }
3505
+ if (index === line - 1 && fields.length >= 4 && generated <= column - 1) found = [
3506
+ state[1],
3507
+ state[2],
3508
+ state[3]
3509
+ ];
3510
+ }
3511
+ }
3512
+ const source = found && map.sources[found[0]];
3513
+ return found && source ? {
3514
+ source,
3515
+ line: found[1] + 1,
3516
+ column: found[2] + 1
3517
+ } : void 0;
3518
+ }
2939
3519
  //#endregion
2940
3520
  //#region src/node.ts
2941
3521
  /** Returns a Node built-in, or undefined outside Node. */
@@ -3050,10 +3630,16 @@ function parseModule(module) {
3050
3630
  case "TSEnumDeclaration": if (node.id) declarations.set(node.id.name, exported ? node.id.name : void 0);
3051
3631
  }
3052
3632
  };
3053
- for (const statement of program.body) if (statement.type === "ImportDeclaration") for (const specifier of statement.specifiers) imports.set(specifier.local.name, {
3054
- specifier: statement.source.value,
3055
- imported: specifier.type === "ImportDefaultSpecifier" ? "default" : specifier.type === "ImportNamespaceSpecifier" ? "*" : specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value
3056
- });
3633
+ for (const statement of program.body) if (statement.type === "ImportDeclaration") for (const specifier of statement.specifiers) {
3634
+ let imported;
3635
+ if (specifier.type === "ImportDefaultSpecifier") imported = "default";
3636
+ else if (specifier.type === "ImportNamespaceSpecifier") imported = "*";
3637
+ else imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
3638
+ imports.set(specifier.local.name, {
3639
+ specifier: statement.source.value,
3640
+ imported
3641
+ });
3642
+ }
3057
3643
  else if (statement.type === "ExportNamedDeclaration" && statement.declaration) declare(statement.declaration, true);
3058
3644
  else declare(statement, false);
3059
3645
  for (const statement of program.body) if (statement.type === "ExportNamedDeclaration" && !statement.declaration && !statement.source) for (const specifier of statement.specifiers) {
@@ -3226,6 +3812,7 @@ function expandModules(file, path, resolve) {
3226
3812
  const source = file.source;
3227
3813
  const program = file.instanceScript?.program;
3228
3814
  if (!program) return;
3815
+ const reactive = (specifier) => isReactiveModule(specifier) || !specifier.startsWith(".") && specifier !== "brumate/signals" && isReactiveModule(resolve(specifier, path)?.path ?? "");
3229
3816
  const imported = /* @__PURE__ */ new Map();
3230
3817
  const macroNames = /* @__PURE__ */ new Map();
3231
3818
  const topNames = /* @__PURE__ */ new Set();
@@ -3233,7 +3820,7 @@ function expandModules(file, path, resolve) {
3233
3820
  topNames.add(specifier.local.name);
3234
3821
  if (specifier.type !== "ImportSpecifier") continue;
3235
3822
  const name = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
3236
- if (isReactiveModule(statement.source.value)) imported.set(specifier.local.name, {
3823
+ if (reactive(statement.source.value)) imported.set(specifier.local.name, {
3237
3824
  specifier: statement.source.value,
3238
3825
  name
3239
3826
  });
@@ -3488,7 +4075,12 @@ function expandModules(file, path, resolve) {
3488
4075
  builder.add(source.slice(0, importsOffset), { offset: 0 }, true);
3489
4076
  const lines = [];
3490
4077
  if (macrosToImport.size > 0) lines.push(`\nimport { ${[...macrosToImport].join(", ")} } from '${SIGNALS_MODULE}';`);
3491
- for (const [alias, { specifier, imported: name }] of imports) lines.push(name === "*" ? `\nimport * as ${alias} from '${specifier}';` : name === "default" ? `\nimport ${alias} from '${specifier}';` : `\nimport { ${name === alias ? name : `${name} as ${alias}`} } from '${specifier}';`);
4078
+ for (const [alias, { specifier, imported: name }] of imports) if (name === "*") lines.push(`\nimport * as ${alias} from '${specifier}';`);
4079
+ else if (name === "default") lines.push(`\nimport ${alias} from '${specifier}';`);
4080
+ else {
4081
+ const binding = name === alias ? name : `${name} as ${alias}`;
4082
+ lines.push(`\nimport { ${binding} } from '${specifier}';`);
4083
+ }
3492
4084
  builder.add(lines.join(""), { offset: importsOffset }, false);
3493
4085
  const offset = builder.text.length;
3494
4086
  for (const piece of after.pieces) builder.pieces.push({
@@ -3537,7 +4129,18 @@ var Patch = class {
3537
4129
  return result + copy(this.source, position, end);
3538
4130
  }
3539
4131
  };
4132
+ /** The name of the function that a call expression calls, when it is a plain name. */
4133
+ function calleeName(node) {
4134
+ return node.callee.type === "Identifier" ? node.callee.name : void 0;
4135
+ }
3540
4136
  /** The variable that holds a memo on the server, which can be a promise. */
4137
+ /** The compile-time functions that declare a memo of their first argument. The others are options. */
4138
+ const MEMOS = /* @__PURE__ */ new Set([
4139
+ "$memo",
4140
+ "$optimistic",
4141
+ "$debounced",
4142
+ "$throttled"
4143
+ ]);
3541
4144
  function promiseName(name) {
3542
4145
  return `$$p_${name}`;
3543
4146
  }
@@ -3548,15 +4151,51 @@ function promiseName(name) {
3548
4151
  * `$$p_<name>`, because it can hold a promise that is awaited where it is read.
3549
4152
  * The memos in `inline` are plain values on the server too.
3550
4153
  */
4154
+ /** The name of the key of a property, or undefined for a computed key. */
4155
+ function keyName(property) {
4156
+ if (property.computed) return;
4157
+ if (property.key.type === "Identifier") return property.key.name;
4158
+ return property.key.type === "Literal" ? String(property.key.value) : void 0;
4159
+ }
3551
4160
  function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE__ */ new Set()) {
3552
4161
  const sitesByNode = /* @__PURE__ */ new Map();
3553
- for (const site of sites) sitesByNode.set(site.node, site);
4162
+ const propNames = /* @__PURE__ */ new Map();
4163
+ for (const statement of file.instanceScript?.program.body ?? []) {
4164
+ if (statement.type !== "VariableDeclaration") continue;
4165
+ for (const declarator of statement.declarations) {
4166
+ const init = declarator.init;
4167
+ if (init?.type === "CallExpression" && calleeName(init) === "$props" && declarator.id.type === "ObjectPattern") propNames.set(init, declarator.id.properties.flatMap((property) => {
4168
+ const name = property.type === "Property" ? keyName(property) : void 0;
4169
+ return name === void 0 ? [] : [name];
4170
+ }));
4171
+ }
4172
+ }
4173
+ const awaits = /* @__PURE__ */ new Map();
4174
+ const replaced = /* @__PURE__ */ new Set();
4175
+ for (const site of sites) {
4176
+ sitesByNode.set(site.node, site);
4177
+ for (const read of site.reads) if (read.await) awaits.set(read.await.start, read);
4178
+ }
3554
4179
  const visit = (node) => {
4180
+ if (node.type === "AwaitExpression") {
4181
+ const argument = node.argument;
4182
+ if (argument.type === "CallExpression" && calleeName(argument) === "$memo") {
4183
+ patch.replace(node.start, argument.start, "");
4184
+ visit(argument);
4185
+ return;
4186
+ }
4187
+ const read = awaits.get(node.start);
4188
+ if (read && !replaced.has(read)) {
4189
+ patch.replace(node.start, node.end, read.declaration.name);
4190
+ return;
4191
+ }
4192
+ }
3555
4193
  if (node.type === "CallExpression" && node.callee.type === "Identifier") {
3556
4194
  const name = node.callee.name;
3557
4195
  const argument = node.arguments[0];
3558
4196
  if (name === "$props") {
3559
- patch.replace(node.start, node.end, "$$props");
4197
+ const names = propNames.get(node);
4198
+ patch.replace(node.start, node.end, names ? `$$b.unbind($$props, ${JSON.stringify(names)})` : "$$b.unbind($$props)");
3560
4199
  return;
3561
4200
  }
3562
4201
  if (name === "$action") {
@@ -3573,18 +4212,22 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
3573
4212
  for (const rest of node.arguments.slice(1)) visit(rest);
3574
4213
  return;
3575
4214
  }
3576
- if (name === "$signal" || name === "$memo" || name === "$optimistic" || name === "$untrack") {
4215
+ if (MEMOS.has(name) || name === "$signal" || name === "$untrack") {
3577
4216
  if (!argument) {
3578
4217
  patch.replace(node.start, node.end, "undefined");
3579
4218
  return;
3580
4219
  }
3581
- const site = name === "$memo" || name === "$optimistic" ? sitesByNode.get(argument) : void 0;
4220
+ const site = MEMOS.has(name) ? sitesByNode.get(argument) : void 0;
3582
4221
  const declaration = site?.declaration && !inline.has(site.declaration) ? site.declaration : void 0;
3583
4222
  if (declaration && mode === "server") patch.replace(declaration.range.start, declaration.range.end, promiseName(declaration.name));
3584
4223
  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)})`);
4224
+ 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")) {
4225
+ const range = read.await ?? read.range;
4226
+ patch.replace(range.start, range.end, `$$b.read(${promiseName(read.declaration.name)})`);
4227
+ replaced.add(read);
4228
+ }
3586
4229
  patch.replace(node.start, argument.start, site.awaits ? "$$b.memo(async () => (" : "$$b.memo(() => (");
3587
- patch.replace(argument.end, node.end, "), $$ctx)");
4230
+ patch.replace(argument.end, node.end, `), $$ctx, ${JSON.stringify(declaration.name)})`);
3588
4231
  } else if (site?.awaits) {
3589
4232
  patch.replace(node.start, argument.start, "(async () => (");
3590
4233
  patch.replace(argument.end, node.end, "))()");
@@ -3645,7 +4288,8 @@ const UNSHARED = /* @__PURE__ */ new Set([
3645
4288
  "$setContext",
3646
4289
  "$title",
3647
4290
  "$action",
3648
- "$props"
4291
+ "$props",
4292
+ "$handler"
3649
4293
  ]);
3650
4294
  const analyses = /* @__PURE__ */ new WeakMap();
3651
4295
  function isFunction$1(node) {
@@ -3699,7 +4343,10 @@ function analyze(module) {
3699
4343
  if (locals.has(identifier.name)) reads.add(identifier.name);
3700
4344
  });
3701
4345
  const findWrites = (current) => {
3702
- const target = current.type === "AssignmentExpression" ? current.left : current.type === "UpdateExpression" ? current.argument : current.type === "CallExpression" && current.callee.type === "Identifier" && macros.get(current.callee.name) === "$produce" ? current.arguments[0] : void 0;
4346
+ let target;
4347
+ if (current.type === "AssignmentExpression") target = current.left;
4348
+ else if (current.type === "UpdateExpression") target = current.argument;
4349
+ else if (current.type === "CallExpression" && current.callee.type === "Identifier" && macros.get(current.callee.name) === "$produce") target = current.arguments[0];
3703
4350
  if (target?.type === "Identifier" && locals.has(target.name)) writes.add(target.name);
3704
4351
  for (const [, child] of children(current)) findWrites(child);
3705
4352
  };
@@ -3816,6 +4463,27 @@ function scopeTarget(compound) {
3816
4463
  * `:global(…)`. Each scoped compound goes into `targets`.
3817
4464
  */
3818
4465
  const scopeSelector = (attribute, targets) => selectorParser((selectors) => {
4466
+ for (let index = 0; index < selectors.nodes.length; index++) {
4467
+ const selector = selectors.nodes[index];
4468
+ let list;
4469
+ selector.walkPseudos((pseudo) => {
4470
+ if (!list && pseudo.value === ":global" && pseudo.nodes.length > 1) list = pseudo;
4471
+ });
4472
+ if (!list) continue;
4473
+ const copies = list.nodes.map((_, item) => {
4474
+ const copy = selector.clone();
4475
+ let found;
4476
+ copy.walkPseudos((pseudo) => {
4477
+ if (!found && pseudo.value === ":global" && pseudo.nodes.length > 1) found = pseudo;
4478
+ });
4479
+ const only = found.nodes[item];
4480
+ if (only.first) only.first.spaces.before = "";
4481
+ found.nodes = [only];
4482
+ return copy;
4483
+ });
4484
+ selector.replaceWith(...copies);
4485
+ index--;
4486
+ }
3819
4487
  selectors.each((selector) => {
3820
4488
  const compounds = [[]];
3821
4489
  selector.each((node) => {
@@ -3994,6 +4662,12 @@ function compileStyles(file, scope, filePath) {
3994
4662
  }
3995
4663
  //#endregion
3996
4664
  //#region src/plan.ts
4665
+ /** A node without the parentheses around it. */
4666
+ function unparen(node) {
4667
+ let current = node;
4668
+ while (current.type === "ParenthesizedExpression") current = current.expression;
4669
+ return current;
4670
+ }
3997
4671
  /**
3998
4672
  * Elements that the HTML parser can end before their end tag, or whose
3999
4673
  * content it moves out, when they hold some other elements: a `<p>` ends at
@@ -4092,7 +4766,7 @@ function clientState(graph) {
4092
4766
  const slots = /* @__PURE__ */ new Map();
4093
4767
  for (const scope of model.scopes) {
4094
4768
  if (scope.kind === "module") continue;
4095
- slots.set(scope, [...scope.declarations.values()].filter((declaration) => !NO_SLOT.has(declaration.kind) && declaration.reads.some((read) => clientSites.has(read.site))));
4769
+ slots.set(scope, [...scope.declarations.values()].filter((declaration) => !NO_SLOT.has(declaration.kind) && (declaration.reads.some((read) => clientSites.has(read.site)) || declaration.bound === true || declaration.kind === "prop" && declaration.writable === true && declaration.writes.some((write) => clientSites.has(write.site)))));
4096
4770
  }
4097
4771
  return {
4098
4772
  isLiveSite,
@@ -4113,14 +4787,18 @@ function createPlan(file, graph, path, hideNames = false) {
4113
4787
  needsId: scope.kind === "component",
4114
4788
  anchors: 0
4115
4789
  });
4790
+ const boundCalls = new Set(model.bindings.map((binding) => binding.call));
4116
4791
  const anchors = /* @__PURE__ */ new Map();
4792
+ const anchorScopes = /* @__PURE__ */ new Map();
4117
4793
  const anchor = (scope, target) => {
4118
4794
  const plan = scopes.get(scope);
4119
4795
  anchors.set(target, plan.anchors++);
4796
+ anchorScopes.set(target, scope);
4120
4797
  plan.needsId = true;
4121
4798
  };
4122
4799
  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}`);
4800
+ for (const site of model.sites) if (site.kind === "prop" && isTemplateValue(site)) symbols.set(site, `t${site.id}`);
4801
+ else if (site.kind === "event" || site.kind === "prop" && isFunctionValue(site)) symbols.set(site, `h${site.id}`);
4124
4802
  else if (site.kind === "client") {
4125
4803
  symbols.set(site, `c${site.id}`);
4126
4804
  anchor(site.scope, site);
@@ -4173,10 +4851,12 @@ function createPlan(file, graph, path, hideNames = false) {
4173
4851
  });
4174
4852
  const content = node.kind === "element" ? liveContent(node) : void 0;
4175
4853
  const events = sites.some((site) => site.kind === "event");
4854
+ const bound = node.kind === "element" && node.attributes.some((attribute) => attribute.kind === "value" && boundCalls.has(unparen(attribute.value.ast)));
4176
4855
  const implied = node.kind === "element" && outer === scope;
4177
- if (hasRef || content || itemRoots.has(node) || sites.some((site) => isLiveSite(site)) || events && !implied) anchor(scope, node);
4856
+ if (hasRef || bound || content || itemRoots.has(node) || sites.some((site) => isLiveSite(site)) || events && !implied) anchor(scope, node);
4178
4857
  if (content) {
4179
4858
  anchors.set(content, anchors.get(node));
4859
+ anchorScopes.set(content, scope);
4180
4860
  contents.add(content);
4181
4861
  if (node.kind === "element" && RAW_TEXT.has(node.tag.toLowerCase())) textContents.add(content);
4182
4862
  return;
@@ -4228,7 +4908,7 @@ function createPlan(file, graph, path, hideNames = false) {
4228
4908
  };
4229
4909
  const visitBlock = (block, scope, outer) => {
4230
4910
  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));
4911
+ 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
4912
  if (live) anchor(scope, block);
4233
4913
  if (live && block.kind === "offscreen") scopes.get(bodyScopes.get(block.body)).needsId = true;
4234
4914
  if (block.kind === "portal" || block.kind === "head") scopes.get(bodyScopes.get(block.body)).needsId = true;
@@ -4254,6 +4934,34 @@ function createPlan(file, graph, path, hideNames = false) {
4254
4934
  };
4255
4935
  for (const template of file.templates) visitBody(template.body);
4256
4936
  visitNodes(file.children, model.component);
4937
+ const checkTitles = (nodes, inHead) => {
4938
+ for (const node of nodes) switch (node.kind) {
4939
+ case "element": {
4940
+ const tag = node.tag.toLowerCase();
4941
+ if (tag === "title" && !inHead) diagnostics.push({
4942
+ severity: "error",
4943
+ message: "Put <title> in #head, as <meta> and <link>, such as #head { <title>{`${count} left`}</title> }",
4944
+ range: {
4945
+ start: node.start,
4946
+ end: node.end
4947
+ }
4948
+ });
4949
+ else if (tag !== "head" && tag !== "svg") checkTitles(node.children, inHead);
4950
+ break;
4951
+ }
4952
+ case "component":
4953
+ case "dynamic":
4954
+ case "fragment":
4955
+ checkTitles(node.children, inHead);
4956
+ break;
4957
+ case "text":
4958
+ case "insert":
4959
+ case "listener": break;
4960
+ default: for (const body of blockBodies(node)) checkTitles(body.children, inHead || node.kind === "head");
4961
+ }
4962
+ };
4963
+ for (const template of file.templates) checkTitles(template.body.children, false);
4964
+ checkTitles(file.children, false);
4257
4965
  for (const plan of scopes.values()) {
4258
4966
  if (plan.slots.length > 0) plan.needsId = true;
4259
4967
  if ([...plan.scope.declarations.values()].some((declaration) => declaration.idIndex !== void 0)) plan.needsId = true;
@@ -4270,6 +4978,7 @@ function createPlan(file, graph, path, hideNames = false) {
4270
4978
  scopes,
4271
4979
  bodyScopes,
4272
4980
  anchors,
4981
+ anchorScopes,
4273
4982
  contents,
4274
4983
  textContents,
4275
4984
  elementItems,
@@ -4305,7 +5014,9 @@ function blockBodies(block) {
4305
5014
  case "switch": return [...block.cases.map((branch) => branch.body), ...block.fallback ? [block.fallback] : []];
4306
5015
  case "for":
4307
5016
  case "repeat":
4308
- case "loading": return [block.body, ...block.fallback ? [block.fallback] : []];
5017
+ case "loading":
5018
+ case "client":
5019
+ case "defer": return [block.body, ...block.fallback ? [block.fallback] : []];
4309
5020
  case "try": return [block.body, block.fallback];
4310
5021
  default: return [block.body];
4311
5022
  }
@@ -4344,30 +5055,55 @@ const DEFERRED_SITES$1 = /* @__PURE__ */ new Set([
4344
5055
  "effect",
4345
5056
  "client"
4346
5057
  ]);
4347
- /** Returns the nearest `#loading` body scope that contains a scope, up to `limit`. */
5058
+ /**
5059
+ * Returns the nearest `#loading` or `#defer` body scope that contains a
5060
+ * scope, up to `limit`. Both render after the rest of the page, so the
5061
+ * page does not wait for the memos that only they read.
5062
+ */
4348
5063
  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;
5064
+ for (let current = scope; current && current !== limit; current = current.parent) {
5065
+ const block = current.block;
5066
+ if ((block?.kind === "loading" || block?.kind === "defer") && current.body === block.body) return current;
5067
+ }
4350
5068
  }
4351
5069
  /** Any memo can hold a promise, because its expression can call code that returns one. */
4352
5070
  function isMemo(declaration) {
4353
5071
  return declaration.kind === "memo" || declaration.kind === "async-memo";
4354
5072
  }
4355
5073
  /**
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.
5074
+ * The scope whose render waits for a read. A read with `await` inside a
5075
+ * `#loading` body makes the render around the block wait, so it counts as
5076
+ * a read in the scope that holds the block. Inside a `#defer` body, the
5077
+ * request for the body waits, so the read stays where it is. `limit` is
5078
+ * the scope of the declaration, which a read inside it never leaves.
5079
+ */
5080
+ function readScope(read, limit) {
5081
+ const scope = read.site.scope;
5082
+ if (!read.await) return scope;
5083
+ const body = loadingBody(scope, limit);
5084
+ return body?.block?.kind === "loading" ? body.parent : scope;
5085
+ }
5086
+ /**
5087
+ * Returns the memos that the server awaits where they are declared: those
5088
+ * declared with `await $memo(…)`, and those that markup or code outside
5089
+ * every `#loading` body reads, with `await` or without. The others are
5090
+ * awaited by the `#loading` bodies that read them.
4359
5091
  */
4360
5092
  function blockingMemos(plan) {
4361
5093
  const result = /* @__PURE__ */ new Set();
4362
5094
  for (const declaration of plan.graph.model.declarations) {
4363
5095
  if (!isMemo(declaration)) continue;
5096
+ if (declaration.awaited) {
5097
+ result.add(declaration);
5098
+ continue;
5099
+ }
4364
5100
  for (const read of declaration.reads) {
4365
5101
  if (read.range.start === read.range.end) continue;
4366
5102
  const site = read.site;
4367
5103
  if (DEFERRED_SITES$1.has(site.kind) || site.kind === "memo") continue;
4368
5104
  let template = false;
4369
5105
  for (let scope = site.scope; scope; scope = scope.parent) template ||= scope.kind === "template";
4370
- if (template || !loadingBody(site.scope, declaration.scope)) {
5106
+ if (template || !loadingBody(readScope(read, declaration.scope), declaration.scope)) {
4371
5107
  result.add(declaration);
4372
5108
  break;
4373
5109
  }
@@ -4375,18 +5111,64 @@ function blockingMemos(plan) {
4375
5111
  }
4376
5112
  return result;
4377
5113
  }
4378
- /** Returns the memos that a `#loading` body awaits before it renders. */
5114
+ /**
5115
+ * Returns the memos that a `#loading` body waits for before it renders:
5116
+ * the memos that its markup reads, and the memos that a `#loading` body
5117
+ * inside it reads with `await`. Memos that the page or a body around it
5118
+ * waits for are left out.
5119
+ */
4379
5120
  function awaitedMemos(plan, body, blocking) {
4380
5121
  const result = /* @__PURE__ */ new Set();
4381
5122
  for (const site of plan.graph.model.sites) {
4382
- if (DEFERRED_SITES$1.has(site.kind) || loadingBody(site.scope) !== body) continue;
5123
+ if (DEFERRED_SITES$1.has(site.kind)) continue;
4383
5124
  for (const read of site.reads) {
4384
- if (read.range.start === read.range.end) continue;
5125
+ if (read.range.start === read.range.end || loadingBody(readScope(read)) !== body) continue;
4385
5126
  if (isMemo(read.declaration) && !blocking.has(read.declaration)) result.add(read.declaration);
4386
5127
  }
4387
5128
  }
5129
+ const outer = body.parent && loadingBody(body.parent);
5130
+ if (outer) for (const declaration of awaitedMemos(plan, outer, blocking)) result.delete(declaration);
4388
5131
  return [...result];
4389
5132
  }
5133
+ /**
5134
+ * True if the markup of a `#loading` body may wait for something other than
5135
+ * the memos it reads, so the body cannot render in place when those memos
5136
+ * are ready: a child component, a dynamic tag, a template, or an insert of
5137
+ * a prop, which can be a promise or the children of a parent. Bodies that
5138
+ * render later, such as those of a `#loading` or a `#defer` inside it, wait
5139
+ * on their own.
5140
+ */
5141
+ function mayWait(plan, nodes) {
5142
+ const insertWaits = (node) => {
5143
+ const site = plan.graph.model.sites.find((item) => item.node === node.expression.ast);
5144
+ if (!site) return false;
5145
+ for (const read of site.reads) {
5146
+ const kind = read.declaration.kind;
5147
+ if (kind === "prop" || kind === "props-rest" || kind === "template") return true;
5148
+ }
5149
+ return false;
5150
+ };
5151
+ for (const node of nodes) switch (node.kind) {
5152
+ case "component":
5153
+ case "dynamic": return true;
5154
+ case "insert":
5155
+ if (insertWaits(node)) return true;
5156
+ break;
5157
+ case "element":
5158
+ case "fragment":
5159
+ if (mayWait(plan, node.children)) return true;
5160
+ break;
5161
+ case "text":
5162
+ case "listener": break;
5163
+ default: {
5164
+ let bodies;
5165
+ if (node.kind === "loading" || node.kind === "defer" || node.kind === "client") bodies = node.fallback ? [node.fallback] : [];
5166
+ else bodies = blockBodies(node);
5167
+ for (const body of bodies) if (mayWait(plan, body.children)) return true;
5168
+ }
5169
+ }
5170
+ return false;
5171
+ }
4390
5172
  /** Expressions that run code the compiler cannot see, or that a memo should not hold. */
4391
5173
  const UNSAFE_NODES = /* @__PURE__ */ new Set([
4392
5174
  "CallExpression",
@@ -4526,10 +5308,19 @@ function specialCall(declarator) {
4526
5308
  const init = declarator.init;
4527
5309
  if (init?.type !== "CallExpression" || init.callee.type !== "Identifier") return;
4528
5310
  const name = init.callee.name;
4529
- return name === "$getContext" || name === "$id" ? name : void 0;
4530
- }
5311
+ return name === "$getContext" || name === "$id" || name === "$route" || name === "$navigation" ? name : void 0;
5312
+ }
5313
+ /** The attribute that sets the method of a form, by the attribute that sets its action. */
5314
+ const FORM_METHODS = /* @__PURE__ */ new Map([["action", "method"], ["formaction", "formmethod"]]);
5315
+ /** The contexts that the runtime provides, by the compile-time function that reads them. */
5316
+ const BUILT_IN_CONTEXTS = {
5317
+ $route: "$$b.routeContext",
5318
+ $navigation: "$$b.navigationContext"
5319
+ };
4531
5320
  /** Writes code that renders markup to an HTML string, on the server or on the client. */
4532
5321
  /** The exports of the core that do on the client what the server's render context does. */
5322
+ /** The `$handler` calls that each patch has edited, since emitters of a file share its patch. */
5323
+ const handlerEdits = /* @__PURE__ */ new WeakMap();
4533
5324
  const CLIENT_HELPERS = {
4534
5325
  scope: "createScope",
4535
5326
  slots: "setSlots",
@@ -4543,14 +5334,75 @@ const CLIENT_HELPERS = {
4543
5334
  portal: "addPortal",
4544
5335
  style: "addStyle",
4545
5336
  fn: "handlerProp",
5337
+ bindings: "bindings",
4546
5338
  after: "afterInsert",
4547
5339
  title: "title"
4548
5340
  };
5341
+ /** The named character references that markup reads. Others stay as they are written. */
5342
+ const NAMED = {
5343
+ amp: "&",
5344
+ lt: "<",
5345
+ gt: ">",
5346
+ quot: "\"",
5347
+ apos: "'",
5348
+ nbsp: "\xA0",
5349
+ copy: "©",
5350
+ reg: "®",
5351
+ trade: "™",
5352
+ hellip: "…",
5353
+ mdash: "—",
5354
+ ndash: "–",
5355
+ lsquo: "‘",
5356
+ rsquo: "’",
5357
+ ldquo: "“",
5358
+ rdquo: "”",
5359
+ laquo: "«",
5360
+ raquo: "»",
5361
+ middot: "·",
5362
+ bull: "•",
5363
+ times: "×",
5364
+ euro: "€"
5365
+ };
5366
+ /**
5367
+ * Markup text or a static attribute value, with its character references
5368
+ * read. A number that is no character, such as one past 0x10FFFF, reads as
5369
+ * U+FFFD, as the browser reads it.
5370
+ */
5371
+ function decodeReferences(html) {
5372
+ return html.replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, name) => {
5373
+ if (name[0] === "#") {
5374
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : Number(name.slice(1));
5375
+ return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : "�";
5376
+ }
5377
+ return NAMED[name.toLowerCase()] ?? match;
5378
+ });
5379
+ }
5380
+ /** The value of a static attribute, with its character references read. */
5381
+ function decodeAttribute(text) {
5382
+ return decodeReferences(text);
5383
+ }
5384
+ /** The text that markup text shows, with its character references read. */
5385
+ function decodeText(html) {
5386
+ return decodeReferences(html);
5387
+ }
4549
5388
  /** The markup of an inserted literal, such as `{'<b>'}`, or undefined for other code. */
4550
5389
  function literalText(node) {
4551
5390
  if (node.type === "Literal") return "regex" in node && node.regex ? void 0 : insertValue(node.value);
4552
5391
  if (node.type === "TemplateLiteral" && node.expressions.length === 0) return insertValue(node.quasis[0].value.cooked);
4553
5392
  }
5393
+ /**
5394
+ * Blocks whose shape on the server depends on data: which branch renders,
5395
+ * how many items a list has, whether a body throws or shows. The server
5396
+ * numbers the scopes of their bodies after an ID of the block's own.
5397
+ */
5398
+ const DATA_SHAPED = /* @__PURE__ */ new Set([
5399
+ "if",
5400
+ "switch",
5401
+ "for",
5402
+ "repeat",
5403
+ "try",
5404
+ "offscreen"
5405
+ ]);
4554
5406
  var Emitter = class {
4555
5407
  lines = [];
4556
5408
  file;
@@ -4571,6 +5423,8 @@ var Emitter = class {
4571
5423
  depth = 0;
4572
5424
  /** How many of this component's elements contain the current node. */
4573
5425
  nesting = 0;
5426
+ /** How many `#head` blocks contain the current node, where a `<title>` sets the title of the page. */
5427
+ headBlocks = 0;
4574
5428
  counter = 0;
4575
5429
  constructor(file, plan, patch, options) {
4576
5430
  this.file = file;
@@ -4583,8 +5437,66 @@ var Emitter = class {
4583
5437
  this.blocking = blockingMemos(plan);
4584
5438
  this.inline = options.mode === "server" ? plainValues(plan, this.blocking) : /* @__PURE__ */ new Set();
4585
5439
  for (const site of plan.graph.model.sites) this.sitesByNode.set(site.node, site);
5440
+ this.addHandlerEdits();
5441
+ this.addBindEdits();
4586
5442
  for (const declaration of plan.graph.model.declarations) for (const ref of declaration.refs) this.refTargets.set(ref.attribute, declaration);
4587
5443
  }
5444
+ /**
5445
+ * `$handler(fn, ...args)` marks its function as a client function with its
5446
+ * arguments, `fn(fn, "<id>#<export>", scope, [args])`, so a spread can
5447
+ * pass it on. The calls are edits of the source, wherever they are in a
5448
+ * script. Emitters of one file share its patch, so each call is edited once.
5449
+ */
5450
+ addHandlerEdits() {
5451
+ let edited = handlerEdits.get(this.patch);
5452
+ if (!edited) handlerEdits.set(this.patch, edited = /* @__PURE__ */ new Set());
5453
+ for (const site of this.plan.graph.model.sites) {
5454
+ const call = site.handler;
5455
+ const fn = call?.arguments[0];
5456
+ if (!call || !fn || edited.has(call)) continue;
5457
+ edited.add(call);
5458
+ const args = call.arguments.slice(1);
5459
+ const symbol = this.plan.symbols.get(site);
5460
+ if (!symbol) {
5461
+ this.patch.replace(call.start, fn.start, "(");
5462
+ this.patch.replace(fn.end, call.end, ")");
5463
+ continue;
5464
+ }
5465
+ const ref = JSON.stringify(`${this.plan.id}#${symbol}`);
5466
+ const scope = this.scopeVar(instanceScope(this.plan, site.scope));
5467
+ this.patch.replace(call.start, fn.start, `${this.helper("fn")}(`);
5468
+ if (args.length === 0) this.patch.replace(fn.end, call.end, `, ${ref}, ${scope})`);
5469
+ else {
5470
+ this.patch.replace(fn.end, args[0].start, `, ${ref}, ${scope}, [`);
5471
+ this.patch.replace(args.at(-1).end, call.end, "])");
5472
+ }
5473
+ }
5474
+ }
5475
+ /**
5476
+ * `$bind(name)` passes the child the value of the name with its slot,
5477
+ * `binding(name, scope, slot)`, so the child's writes reach it.
5478
+ */
5479
+ addBindEdits() {
5480
+ let edited = handlerEdits.get(this.patch);
5481
+ if (!edited) handlerEdits.set(this.patch, edited = /* @__PURE__ */ new Set());
5482
+ for (const { call, declaration, setter } of this.plan.graph.model.bindings) {
5483
+ const [target, fn] = call.arguments;
5484
+ if (!target || edited.has(call)) continue;
5485
+ edited.add(call);
5486
+ const scope = this.scopeVar(instanceScope(this.plan, declaration.scope));
5487
+ const slot = slotIndex(this.plan, declaration);
5488
+ this.patch.replace(call.start, target.start, "$$b.binding((");
5489
+ const symbol = setter && this.plan.symbols.get(setter);
5490
+ if (!fn || !setter || !symbol) {
5491
+ this.patch.replace(target.end, call.end, `), ${scope}, ${slot})`);
5492
+ continue;
5493
+ }
5494
+ const ref = JSON.stringify(`${this.plan.id}#${symbol}`);
5495
+ const owner = this.scopeVar(instanceScope(this.plan, setter.scope));
5496
+ this.patch.replace(target.end, fn.start, `), ${scope}, ${slot}, ${this.helper("fn")}(`);
5497
+ this.patch.replace(fn.end, call.end, `, ${ref}, ${owner}))`);
5498
+ }
5499
+ }
4588
5500
  line(code) {
4589
5501
  this.flush();
4590
5502
  this.lines.push(`${" ".repeat(this.depth)}${code}`);
@@ -4666,10 +5578,14 @@ var Emitter = class {
4666
5578
  emitSlots(scope) {
4667
5579
  const slots = this.plan.scopes.get(scope)?.slots ?? [];
4668
5580
  if (slots.length > 0) {
4669
- const values = slots.map((slot) => this.isPromise(slot) ? `$$b.wait(${promiseName(slot.name)})` : slot.name);
5581
+ const values = slots.map((slot) => this.isPromise(slot) ? `$$b.stateValue(${promiseName(slot.name)})` : slot.name);
4670
5582
  const names = this.options.mode === "server" ? `, ${JSON.stringify(slots.map((slot) => slot.name))}` : "";
4671
5583
  this.line(`${this.helper("slots")}(${this.scopeVar(scope)}, [${values.join(", ")}]${names});`);
4672
5584
  }
5585
+ if (scope.kind === "component") {
5586
+ const bindable = slots.flatMap((slot, index) => slot.kind === "prop" && slot.writable && slot.propKey !== void 0 ? [`${JSON.stringify(slot.propKey)}: ${index}`] : []);
5587
+ if (bindable.length > 0) this.line(`${this.helper("bindings")}(${this.scopeVar(scope)}, $$props, { ${bindable.join(", ")} });`);
5588
+ }
4673
5589
  }
4674
5590
  /** True if the server inserts a primitive, such as a memo that it computes as a plain value. */
4675
5591
  isPrimitiveInsert(expression) {
@@ -4681,18 +5597,68 @@ var Emitter = class {
4681
5597
  isPromise(declaration) {
4682
5598
  return this.options.mode === "server" && isMemo(declaration) && !this.blocking.has(declaration) && !this.inline.has(declaration);
4683
5599
  }
4684
- /** Awaits the async memos of a statement that markup outside `#loading` reads. */
4685
- awaitMemos(statement) {
5600
+ /**
5601
+ * The memos of a statement that the server waits for where they are
5602
+ * declared. `awaited` is true when every one of them is declared with
5603
+ * `await $memo(…)`. Such statements in a row form a run: every memo of
5604
+ * the run starts, and the render waits for all of them where the run
5605
+ * ends, so independent memos load at the same time. A memo that the
5606
+ * markup makes the page wait for, without the keyword, is awaited on its
5607
+ * own, as the code reads.
5608
+ */
5609
+ blockingDeclarations(statement) {
4686
5610
  if (this.options.mode !== "server" || statement.type !== "VariableDeclaration") return;
5611
+ const declarations = [];
5612
+ let awaited = true;
4687
5613
  for (const declarator of statement.declarations) {
4688
- const init = declarator.init;
5614
+ let init = declarator.init;
5615
+ if (init?.type === "AwaitExpression") init = init.argument;
4689
5616
  const argument = init?.type === "CallExpression" ? init.arguments[0] : void 0;
4690
5617
  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)};`);
5618
+ if (!declaration || !isMemo(declaration) || !this.blocking.has(declaration)) {
5619
+ awaited = false;
5620
+ continue;
5621
+ }
5622
+ awaited &&= declaration.awaited === true;
5623
+ if (!this.inline.has(declaration)) declarations.push(declaration);
4692
5624
  }
5625
+ return declarations.length === 0 ? void 0 : {
5626
+ declarations,
5627
+ awaited
5628
+ };
5629
+ }
5630
+ /** Waits for the memos of a run of declarations, and gives each its value. */
5631
+ awaitRun(run) {
5632
+ if (run.length === 1) {
5633
+ const [declaration] = run;
5634
+ this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5635
+ return;
5636
+ }
5637
+ const names = run.map((declaration) => promiseName(declaration.name));
5638
+ this.line(`if (($$t = $$b.waitAll([${names.join(", ")}])) !== undefined) await $$t;`);
5639
+ for (const declaration of run) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
4693
5640
  }
4694
5641
  emitStatements(statements, scope) {
5642
+ let run = [];
5643
+ const endRun = () => {
5644
+ if (run.length > 0) {
5645
+ this.awaitRun(run);
5646
+ run = [];
5647
+ }
5648
+ };
4695
5649
  for (const statement of statements) {
5650
+ const blocking = this.blockingDeclarations(statement);
5651
+ if (blocking?.awaited) {
5652
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
5653
+ run.push(...blocking.declarations);
5654
+ continue;
5655
+ }
5656
+ endRun();
5657
+ if (blocking) {
5658
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
5659
+ for (const declaration of blocking.declarations) this.awaitRun([declaration]);
5660
+ continue;
5661
+ }
4696
5662
  if (statement.type === "ExpressionStatement") {
4697
5663
  const expression = statement.expression;
4698
5664
  const name = expression.type === "CallExpression" && expression.callee.type === "Identifier" ? expression.callee.name : void 0;
@@ -4717,8 +5683,8 @@ var Emitter = class {
4717
5683
  if (!this.options.functions && this.isFunctionStatement(statement)) continue;
4718
5684
  }
4719
5685
  this.raw(this.patch.slice(statement.start, statement.end), statement.start);
4720
- this.awaitMemos(statement);
4721
5686
  }
5687
+ endRun();
4722
5688
  }
4723
5689
  source(node) {
4724
5690
  return this.patch.slice(node.start, node.end);
@@ -4738,13 +5704,16 @@ var Emitter = class {
4738
5704
  this.line(`const ${declaration.name} = ${this.helper("id")}(${target}, ${declaration.idIndex});`);
4739
5705
  continue;
4740
5706
  }
4741
- if (call !== "$getContext" || declarator.id.type !== "Identifier" || !init.arguments[0]) {
5707
+ let context;
5708
+ if (call && BUILT_IN_CONTEXTS[call]) context = BUILT_IN_CONTEXTS[call];
5709
+ else if (call === "$getContext" && init.arguments[0]) context = this.source(init.arguments[0]);
5710
+ if (!context || declarator.id.type !== "Identifier") {
4742
5711
  this.line(`${statement.kind} ${this.source(declarator)};`);
4743
5712
  continue;
4744
5713
  }
4745
5714
  const slot = declaration ? slotIndex(this.plan, declaration) : -1;
4746
5715
  const record = slot === -1 ? "" : `, ${slot}`;
4747
- this.line(`const ${declarator.id.name} = ${this.helper("consume")}(${this.source(init.arguments[0])}, ${target}${record});`);
5716
+ this.line(`const ${declarator.id.name} = ${this.helper("consume")}(${context}, ${target}${record});`);
4748
5717
  }
4749
5718
  return true;
4750
5719
  }
@@ -4766,7 +5735,21 @@ var Emitter = class {
4766
5735
  const anchor = this.anchor(scope, site);
4767
5736
  this.html("<template b-b=\"");
4768
5737
  this.code(anchor.scope);
4769
- this.html(`:${anchor.index}" b-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"></template>`);
5738
+ this.html(`:${anchor.index}" b-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"`);
5739
+ const near = site.trigger === "visible" ? this.refElement(site, scope) : void 0;
5740
+ if (near !== void 0) {
5741
+ this.html(" b-near=\"");
5742
+ this.code(anchor.scope);
5743
+ this.html(`:${near}"`);
5744
+ }
5745
+ this.html("></template>");
5746
+ }
5747
+ }
5748
+ /** The anchor of the first element of `scope` that a site reads through `ref`. */
5749
+ refElement(site, scope) {
5750
+ for (const read of site.reads) for (const ref of read.declaration.refs) {
5751
+ const index = ref.scope === scope ? this.plan.anchors.get(ref.element) : void 0;
5752
+ if (index !== void 0) return index;
4770
5753
  }
4771
5754
  }
4772
5755
  /** Emits the content of the component, without creating its scope. */
@@ -4865,7 +5848,9 @@ var Emitter = class {
4865
5848
  return;
4866
5849
  case "insert": {
4867
5850
  const anchor = this.anchor(scope, node);
4868
- const at = this.options.mode === "server" ? `, $$ctx, ${this.scopeVar(instanceScope(this.plan, scope))}` : "";
5851
+ const ast = node.expression.ast;
5852
+ const kind = ast.type === "Identifier" ? lookup(scope, ast.name)?.kind : void 0;
5853
+ const at = this.options.mode === "server" || kind === "prop" || kind === "props-rest" ? `, ${this.ctxArgument}, ${this.scopeVar(instanceScope(this.plan, scope))}` : "";
4869
5854
  const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${this.expression(node.expression)})` : this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
4870
5855
  const text = literalText(node.expression.ast);
4871
5856
  const emitValue = () => text === void 0 ? this.code(value) : this.html(text);
@@ -4888,22 +5873,51 @@ var Emitter = class {
4888
5873
  this.emitDynamic(node, scope);
4889
5874
  return;
4890
5875
  case "fragment":
5876
+ if (node.reveal && this.options.mode === "server") {
5877
+ this.line(`$$ctx.revealStart(${JSON.stringify(node.reveal.order)}, ${node.reveal.collapsed});`);
5878
+ this.emitNodes(node.children, scope);
5879
+ this.line("$$ctx.revealEnd();");
5880
+ return;
5881
+ }
4891
5882
  this.emitNodes(node.children, scope);
4892
5883
  return;
4893
5884
  case "listener": {
4894
5885
  const anchor = this.anchor(scope, node);
4895
- const events = node.attributes.map((attribute) => this.eventEntry(attribute.event, attribute.modifiers, attribute.handler));
5886
+ const events = node.attributes.map((attribute) => this.eventEntry(attribute));
4896
5887
  this.html("<template b-b=\"");
4897
5888
  this.code(anchor.scope);
4898
5889
  this.html(`:${anchor.index}" b-listen="${node.target}" b-on="${events.join(" ")}"></template>`);
4899
5890
  return;
4900
5891
  }
4901
- default: this.emitBlock(node, scope);
5892
+ default: if (this.options.mode === "server" && DATA_SHAPED.has(node.kind)) {
5893
+ this.line("$$ctx.enter();");
5894
+ this.emitBlock(node, scope);
5895
+ this.line("$$ctx.leave();");
5896
+ } else this.emitBlock(node, scope);
4902
5897
  }
4903
5898
  }
4904
- eventEntry(event, modifiers, handler) {
5899
+ /**
5900
+ * The `b-on` entry of `value=$bind(name)` or `checked=$bind(name)` on an
5901
+ * element: `input=$bind#<hops>.<slot>`, where `hops` counts the parents
5902
+ * from the scope of the element to the scope of the name. The core writes
5903
+ * the slot from the element without loading any code of the component.
5904
+ */
5905
+ bindEntry(node, attribute, scope) {
5906
+ let value = attribute.value.ast;
5907
+ while (value.type === "ParenthesizedExpression") value = value.expression;
5908
+ const binding = this.plan.graph.model.bindings.find((item) => item.call === value);
5909
+ if (!binding) return;
5910
+ const setter = binding.setter && this.plan.symbols.get(binding.setter);
5911
+ const hops = scopePath(this.plan, "$$s", instanceScope(this.plan, scope), instanceScope(this.plan, binding.declaration.scope)).split(".p").length - 1;
5912
+ const type = node.attributes.find((item) => item.kind === "static" && item.name === "type");
5913
+ const box = type && typeof type.value === "string" && /^(checkbox|radio)$/i.test(type.value);
5914
+ const event = attribute.name === "checked" || box || node.tag.toLowerCase() === "select" ? "change" : "input";
5915
+ if (setter) return `${event}=$set:${this.plan.id}#${setter}`;
5916
+ return `${event}=$bind#${hops}.${slotIndex(this.plan, binding.declaration)}`;
5917
+ }
5918
+ eventEntry({ event, modifiers, handler }) {
4905
5919
  const site = this.sitesByNode.get(handler.ast);
4906
- return `${[event, ...modifiers].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
5920
+ return `${[event, ...[.../* @__PURE__ */ new Set([...modifiers, ...site.modifiers ?? []])]].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
4907
5921
  }
4908
5922
  emitRef(target, attribute, anchor) {
4909
5923
  const declaration = this.refTargets.get(attribute);
@@ -4940,11 +5954,11 @@ var Emitter = class {
4940
5954
  * server function without client code. Returns undefined otherwise.
4941
5955
  */
4942
5956
  formAction(node, name, value, scope) {
4943
- const method = name === "action" ? "method" : name === "formaction" ? "formmethod" : void 0;
5957
+ const method = FORM_METHODS.get(name);
4944
5958
  if (!method || value.ast.type !== "Identifier") return;
4945
5959
  const declaration = lookup(scope, value.ast.name);
4946
- if (declaration?.kind !== "server-function") return;
4947
- const ref = JSON.stringify(serverFunctionId(this.plan, declaration.name));
5960
+ if (declaration?.kind !== "server-function" && declaration?.serverImport === void 0) return;
5961
+ const ref = JSON.stringify(declaration.serverImport ?? serverFunctionId(this.plan, declaration.name));
4948
5962
  const hasMethod = node.attributes.some((attribute) => "name" in attribute && attribute.name === method);
4949
5963
  const methodArgument = hasMethod ? "" : `, ${JSON.stringify(method)}`;
4950
5964
  const result = name === "action" ? this.actionSlot(declaration) : void 0;
@@ -4959,14 +5973,23 @@ var Emitter = class {
4959
5973
  return `\`\${${this.scopeVar(instanceScope(this.plan, declaration.scope))}}:${slot}\``;
4960
5974
  }
4961
5975
  emitElement(node, scope) {
5976
+ const pageTitle = node.tag === "title" && this.headBlocks > 0;
5977
+ if (pageTitle && this.options.mode === "server") this.line(`${this.helper("title")}(${this.titleText(node)}, true);`);
5978
+ let spreadHandlers;
5979
+ if (node.attributes.some((attribute) => attribute.kind === "spread")) {
5980
+ spreadHandlers = this.unique("on");
5981
+ this.line(`const ${spreadHandlers}: string[] = [];`);
5982
+ }
4962
5983
  this.html(`<${node.tag}`);
4963
5984
  if (this.hasScope(node.tag, staticClasses(node.attributes))) this.html(` ${this.plan.styles.attribute}`);
4964
5985
  const ownStyle = this.emitVariables(node);
4965
5986
  const events = [];
4966
5987
  let prefetch;
4967
5988
  const anchor = this.anchor(scope, node);
5989
+ const merged = node.attributes.some((attribute) => attribute.kind === "spread") ? [] : void 0;
4968
5990
  for (const attribute of node.attributes) {
4969
5991
  if (ownStyle && (attribute.kind === "static" || attribute.kind === "value") && attribute.name === "style") continue;
5992
+ if (merged && this.mergedAttribute(node, attribute, scope, merged)) continue;
4970
5993
  switch (attribute.kind) {
4971
5994
  case "static":
4972
5995
  this.html(attribute.value === true ? ` ${attribute.name}` : ` ${attribute.name}="${attribute.value}"`);
@@ -4983,16 +6006,18 @@ var Emitter = class {
4983
6006
  break;
4984
6007
  }
4985
6008
  this.code(`$$b.attribute(${JSON.stringify(attribute.name)}, ${this.expression(attribute.value)})`);
6009
+ const bound = this.bindEntry(node, attribute, scope);
6010
+ if (bound) events.unshift(bound);
4986
6011
  break;
4987
6012
  }
4988
6013
  case "spread":
4989
- this.code(`$$b.spread(${this.expression(attribute.value)})`);
6014
+ this.code(`$$b.spread(${this.expression(attribute.value)}${spreadHandlers ? `, ${spreadHandlers}` : ""})`);
4990
6015
  break;
4991
6016
  case "computed":
4992
6017
  this.code(`$$b.attribute(${this.expression(attribute.name)}, ${attribute.value === true ? "true" : this.expression(attribute.value)})`);
4993
6018
  break;
4994
6019
  case "event":
4995
- events.push(this.eventEntry(attribute.event, attribute.modifiers, attribute.handler));
6020
+ events.push(this.eventEntry(attribute));
4996
6021
  break;
4997
6022
  case "ref":
4998
6023
  if (anchor) this.emitRef(attribute.target, attribute, anchor);
@@ -5000,15 +6025,16 @@ var Emitter = class {
5000
6025
  case "prefetch": prefetch = attribute.strategy;
5001
6026
  }
5002
6027
  }
6028
+ if (merged) this.code(`$$b.spread($$b.mergeAttributes([${merged.join(", ")}])${spreadHandlers ? `, ${spreadHandlers}` : ""})`);
5003
6029
  if (anchor) {
5004
6030
  this.html(" b-b=\"");
5005
6031
  this.code(anchor.scope);
5006
6032
  this.html(`:${anchor.index}"`);
5007
6033
  }
5008
- if (events.length > 0) {
5009
- this.html(` b-on="${events.join(" ")}"`);
5010
- if (prefetch) this.html(` data-prefetch="${prefetch}"`);
5011
- }
6034
+ if (pageTitle) this.html(" b-t");
6035
+ if (spreadHandlers) this.code(`$$b.onAttribute(${spreadHandlers}, ${JSON.stringify(events.join(" "))})`);
6036
+ else if (events.length > 0) this.html(` b-on="${events.join(" ")}"`);
6037
+ if (events.length > 0 && prefetch) this.html(` data-prefetch="${prefetch}"`);
5012
6038
  this.html(">");
5013
6039
  if (VOID_ELEMENTS.has(node.tag)) return;
5014
6040
  this.nesting++;
@@ -5017,6 +6043,42 @@ var Emitter = class {
5017
6043
  this.html(`</${node.tag}>`);
5018
6044
  }
5019
6045
  /**
6046
+ * Adds an attribute of an element with spreads to `parts`, the objects
6047
+ * that its spread merges. Returns false for an attribute that stays apart,
6048
+ * such as a handler or a `ref`.
6049
+ */
6050
+ mergedAttribute(node, attribute, scope, parts) {
6051
+ switch (attribute.kind) {
6052
+ case "static":
6053
+ parts.push(`{ ${JSON.stringify(attribute.name)}: ${attribute.value === true ? "''" : JSON.stringify(decodeAttribute(attribute.value))} }`);
6054
+ return true;
6055
+ case "value":
6056
+ if (this.formAction(node, attribute.name, attribute.value, scope)) return false;
6057
+ parts.push(`{ ${JSON.stringify(attribute.name)}: ${this.expression(attribute.value)} }`);
6058
+ return true;
6059
+ case "computed":
6060
+ parts.push(`{ [${this.expression(attribute.name)}]: ${attribute.value === true ? "true" : this.expression(attribute.value)} }`);
6061
+ return true;
6062
+ case "spread":
6063
+ parts.push(this.expression(attribute.value));
6064
+ return true;
6065
+ default: return false;
6066
+ }
6067
+ }
6068
+ /**
6069
+ * The text of a `<title>`, as code: its one insert, or its text and the
6070
+ * inserts in it joined, such as `Items ({count})`.
6071
+ */
6072
+ titleText(node) {
6073
+ const [only] = node.children;
6074
+ if (only?.kind === "insert" && node.children.length === 1) return this.expression(only.expression);
6075
+ const parts = node.children.flatMap((child) => {
6076
+ if (child.kind === "insert") return [`(${this.expression(child.expression)} ?? '')`];
6077
+ return child.kind === "text" ? [JSON.stringify(decodeText(cleanText(child.value)))] : [];
6078
+ });
6079
+ return parts.length === 0 ? "\"\"" : parts.join(" + ");
6080
+ }
6081
+ /**
5020
6082
  * Renders a literal `class` value as the runtime renders it, without
5021
6083
  * building the value. A class with a condition is added when the condition
5022
6084
  * is truthy. No class leaves the attribute out.
@@ -5060,12 +6122,21 @@ var Emitter = class {
5060
6122
  emitChildren(nodes, scope) {
5061
6123
  if (nodes.length === 0) return;
5062
6124
  const name = this.unique("children");
5063
- this.line(`const ${name} = ${this.wait}(${this.async}() => {`);
6125
+ if (this.options.mode === "server") {
6126
+ this.line(`const ${name} = $$b.children(${this.scopeVar(instanceScope(this.plan, scope))}, async ($$ctx) => {`);
6127
+ this.line(`let $$html = '';`);
6128
+ this.atTopLevel(() => this.emitNodes(nodes, scope));
6129
+ this.flush();
6130
+ this.line("return $$html;");
6131
+ this.close("});");
6132
+ return name;
6133
+ }
6134
+ this.line(`const ${name} = $$b.children(${this.scopeVar(instanceScope(this.plan, scope))}, () => {`);
5064
6135
  this.line(`let $$html = '';`);
5065
6136
  this.atTopLevel(() => this.emitNodes(nodes, scope));
5066
6137
  this.flush();
5067
- this.line("return $$b.raw($$html);");
5068
- this.close("})();");
6138
+ this.line("return $$html;");
6139
+ this.close("});");
5069
6140
  return name;
5070
6141
  }
5071
6142
  props(attributes, scope, extra = []) {
@@ -5138,7 +6209,7 @@ var Emitter = class {
5138
6209
  if (this.hasScope(void 0, staticClasses(node.attributes))) extra.push(`${JSON.stringify(this.plan.styles.attribute)}: true`);
5139
6210
  const anchor = this.anchor(scope, node);
5140
6211
  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)] : []);
6212
+ const events = node.attributes.flatMap((attribute) => attribute.kind === "event" ? [this.eventEntry(attribute)] : []);
5142
6213
  if (events.length > 0) extra.push(`"b-on": ${JSON.stringify(events.join(" "))}`);
5143
6214
  let attributes = node.attributes.filter((attribute) => attribute.kind !== "event");
5144
6215
  const { variables } = this.plan.styles;
@@ -5175,7 +6246,9 @@ var Emitter = class {
5175
6246
  this.html("<!--P");
5176
6247
  this.code(this.scopeVar(body));
5177
6248
  this.html("-->");
6249
+ this.headBlocks += block.kind === "head" ? 1 : 0;
5178
6250
  this.atTopLevel(() => this.emitBody(block.body, false));
6251
+ this.headBlocks -= block.kind === "head" ? 1 : 0;
5179
6252
  this.html("<!--/P-->");
5180
6253
  this.flush();
5181
6254
  this.line("return $$html;");
@@ -5183,26 +6256,85 @@ var Emitter = class {
5183
6256
  this.line(`${this.helper(block.kind === "head" ? "head" : "portal")}(${name});`);
5184
6257
  }
5185
6258
  /**
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.
6259
+ * Renders a `#loading` block. When the memos that its body reads are
6260
+ * ready, and the body waits for nothing else, the body renders in place,
6261
+ * in the ID space of its boundary. Otherwise the fallback renders, and the
6262
+ * body renders after the rest of the page, so data that the body waits
6263
+ * for does not hold up the page. The memos that the body reads with
6264
+ * `await` are ready here, because the render around the block waited for
6265
+ * them.
5188
6266
  */
5189
6267
  emitLoading(block, scope) {
5190
6268
  const boundary = this.unique("boundary");
5191
6269
  const body = this.plan.bodyScopes.get(block.body);
6270
+ const memos = awaitedMemos(this.plan, body, this.blocking).filter((declaration) => !this.inline.has(declaration));
6271
+ const names = memos.map((declaration) => promiseName(declaration.name));
6272
+ const inPlace = !mayWait(this.plan, block.body.children);
6273
+ if (inPlace && memos.length === 0) {
6274
+ this.line("$$ctx.enter();");
6275
+ this.emitBody(block.body);
6276
+ this.line("$$ctx.leave();");
6277
+ return;
6278
+ }
5192
6279
  this.line(`const ${boundary} = $$ctx.boundary();`);
6280
+ if (inPlace) {
6281
+ this.line(`if ($$b.settled([${names.join(", ")}]) && $$ctx.mayShow()) {`);
6282
+ this.line(`$$ctx.enter(${boundary});`);
6283
+ for (const declaration of memos) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
6284
+ this.emitBody(block.body);
6285
+ this.line("$$ctx.leave();");
6286
+ this.close("} else {");
6287
+ }
5193
6288
  this.open(scope, block);
5194
6289
  this.html("<!--l");
5195
6290
  this.code(boundary);
5196
6291
  this.html("-->");
5197
6292
  if (block.fallback) {
6293
+ this.code(`$$ctx.fallbackStart(${boundary})`);
5198
6294
  this.line("{");
5199
6295
  this.emitBody(block.fallback);
5200
6296
  this.close();
6297
+ this.code(`$$ctx.fallbackEnd(${boundary})`);
5201
6298
  }
5202
6299
  this.html("<!--/l-->");
5203
6300
  this.end(block);
5204
6301
  this.line(`$$ctx.defer(${boundary}, async ($$ctx) => {`);
5205
6302
  this.line(`let $$html = '';`);
6303
+ for (const declaration of memos) this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
6304
+ this.emitBody(block.body);
6305
+ this.flush();
6306
+ this.line("return $$html;");
6307
+ this.close("});");
6308
+ if (inPlace) this.close();
6309
+ }
6310
+ /**
6311
+ * Renders the fallback of a `#defer` block between the markers of a
6312
+ * boundary, and a template that the loader starts when the trigger fires.
6313
+ * The body renders only in the request for it, and replaces the fallback
6314
+ * as a `#loading` body does.
6315
+ */
6316
+ emitDefer(block, scope) {
6317
+ const boundary = this.unique("boundary");
6318
+ const anchor = this.anchor(scope, block);
6319
+ const body = this.plan.bodyScopes.get(block.body);
6320
+ this.line(`const ${boundary} = $$ctx.boundary();`);
6321
+ this.html("<template b-b=\"");
6322
+ this.code(anchor.scope);
6323
+ this.html(`:${anchor.index}" b-defer="${block.trigger}:`);
6324
+ this.code(boundary);
6325
+ this.html(":");
6326
+ this.code("$$ctx.base()");
6327
+ this.html("\"></template><!--l");
6328
+ this.code(boundary);
6329
+ this.html("-->");
6330
+ if (block.fallback) {
6331
+ this.line("{");
6332
+ this.emitBody(block.fallback);
6333
+ this.close();
6334
+ }
6335
+ this.html("<!--/l-->");
6336
+ this.line(`$$ctx.deferBlock(${boundary}, ${anchor.scope} + ${JSON.stringify(`:${anchor.index}`)}, async ($$ctx) => {`);
6337
+ this.line(`let $$html = '';`);
5206
6338
  for (const declaration of awaitedMemos(this.plan, body, this.blocking)) {
5207
6339
  if (this.inline.has(declaration)) continue;
5208
6340
  this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
@@ -5298,9 +6430,25 @@ var Emitter = class {
5298
6430
  this.code(anchor.scope);
5299
6431
  this.html(`:${anchor.index}" b-client="${block.trigger}=${this.plan.id}#k${body.id}"></template>`);
5300
6432
  this.open(scope, block);
6433
+ if (block.fallback) {
6434
+ this.line("{");
6435
+ this.emitBody(block.fallback);
6436
+ this.close();
6437
+ }
5301
6438
  this.end(block);
5302
6439
  return;
5303
6440
  }
6441
+ case "defer":
6442
+ if (this.options.mode === "server") this.emitDefer(block, scope);
6443
+ else {
6444
+ this.line(`$$b.deferInBrowser(${JSON.stringify(this.plan.id)});`);
6445
+ if (block.fallback) {
6446
+ this.line("{");
6447
+ this.emitBody(block.fallback);
6448
+ this.close();
6449
+ }
6450
+ }
6451
+ return;
5304
6452
  case "loading":
5305
6453
  if (this.options.mode === "server") {
5306
6454
  this.emitLoading(block, scope);
@@ -5351,9 +6499,15 @@ function staticClasses(attributes) {
5351
6499
  }
5352
6500
  return classes;
5353
6501
  }
6502
+ /** The entities that escape the characters of a class in an attribute. */
6503
+ const CLASS_ESCAPES = {
6504
+ "&": "&amp;",
6505
+ "<": "&lt;",
6506
+ "\"": "&quot;"
6507
+ };
5354
6508
  /** Escapes a class for an attribute, as the runtime does. */
5355
6509
  function escapeClass(name) {
5356
- return name.replace(/[&<"]/g, (char) => char === "&" ? "&amp;" : char === "<" ? "&lt;" : "&quot;");
6510
+ return name.replace(/[&<"]/g, (char) => CLASS_ESCAPES[char]);
5357
6511
  }
5358
6512
  /**
5359
6513
  * The classes of a literal `class` value, such as `{ done: todo.done }` or
@@ -5377,7 +6531,9 @@ function literalClasses(value, slice) {
5377
6531
  for (const property of node.properties) {
5378
6532
  if (property.type !== "Property" || property.kind !== "init" || property.method || property.computed) return false;
5379
6533
  const { key } = property;
5380
- const name = key.type === "Identifier" ? key.name : key.type === "Literal" && typeof key.value === "string" ? key.value : void 0;
6534
+ let name;
6535
+ if (key.type === "Identifier") name = key.name;
6536
+ else if (key.type === "Literal" && typeof key.value === "string") name = key.value;
5381
6537
  if (!name || /^\d+$/.test(name) || name === "__proto__" || names.has(name)) return false;
5382
6538
  names.add(name);
5383
6539
  const constant = property.value;
@@ -5530,6 +6686,8 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
5530
6686
  case "for":
5531
6687
  case "repeat":
5532
6688
  case "loading":
6689
+ case "client":
6690
+ case "defer":
5533
6691
  componentNames(node.body.children, names);
5534
6692
  componentNames(node.fallback?.children ?? [], names);
5535
6693
  break;
@@ -5540,7 +6698,6 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
5540
6698
  case "key":
5541
6699
  case "portal":
5542
6700
  case "head":
5543
- case "client":
5544
6701
  case "offscreen": componentNames(node.body.children, names);
5545
6702
  }
5546
6703
  return names;
@@ -5585,6 +6742,10 @@ function clientModuleScript(file, plan) {
5585
6742
  }
5586
6743
  return result;
5587
6744
  }
6745
+ /** True if the render of the component awaits a promise, outside memos and the code of handlers. */
6746
+ function awaitsPromise(plan) {
6747
+ return plan.graph.model.sites.some((site) => site.awaits && site.kind !== "memo" && site.kind !== "function" && !SKIPPED_SITES.has(site.kind));
6748
+ }
5588
6749
  /**
5589
6750
  * Generates the render module: the component's render function for the
5590
6751
  * client, used when a parent renders it inside a block that changes.
@@ -5626,6 +6787,17 @@ function generateRender(file, plan) {
5626
6787
  });
5627
6788
  const generics = file.generics ? `<${file.generics}>` : "";
5628
6789
  emitter.line(`export default function ${plan.name}${generics}($$props: ${propsType(file)}): string {`);
6790
+ if (awaitsPromise(plan)) {
6791
+ emitter.line(`throw new Error(${JSON.stringify(`${plan.name} awaits a promise in its script or markup, so only the server can render it`)});`);
6792
+ emitter.close();
6793
+ return [
6794
+ ...header,
6795
+ ...moduleBody,
6796
+ "",
6797
+ ...emitter.lines,
6798
+ ""
6799
+ ].join("\n");
6800
+ }
5629
6801
  emitter.line(`let $$html = '';`);
5630
6802
  emitter.line(`const ${emitter.scopeVar(model.component)} = $$b.createScope(${model.component.id}, undefined, ${JSON.stringify(plan.id)});`);
5631
6803
  emitter.emitComponentContent(setup);
@@ -5664,11 +6836,17 @@ var Rewriter = class {
5664
6836
  plan;
5665
6837
  diagnostics;
5666
6838
  shared;
6839
+ /** The sites of `$handler` calls, by call. */
6840
+ handlers = /* @__PURE__ */ new Map();
6841
+ /** The declarations of the names of `$bind` calls, by call. */
6842
+ bindings = /* @__PURE__ */ new Map();
5667
6843
  constructor(file, plan, diagnostics, shared) {
5668
6844
  this.file = file;
5669
6845
  this.plan = plan;
5670
6846
  this.diagnostics = diagnostics;
5671
6847
  this.shared = shared;
6848
+ for (const site of plan.graph.model.sites) if (site.handler) this.handlers.set(site.handler, site);
6849
+ for (const binding of plan.graph.model.bindings) this.bindings.set(binding.call, binding);
5672
6850
  }
5673
6851
  /**
5674
6852
  * The call of the shared code of a site that a module function gave the
@@ -5789,6 +6967,15 @@ var Rewriter = class {
5789
6967
  if (value) patch.replace(node.start, node.end, value);
5790
6968
  return;
5791
6969
  }
6970
+ case "AwaitExpression": {
6971
+ const reference = target(node.argument);
6972
+ if (reference?.await) {
6973
+ const value = this.value(reference.declaration, scopeVar, base);
6974
+ patch.replace(node.start, node.end, value ?? reference.declaration.name);
6975
+ return;
6976
+ }
6977
+ break;
6978
+ }
5792
6979
  case "Property":
5793
6980
  if (node.shorthand && node.value.type === "Identifier") {
5794
6981
  const reference = target(node.value);
@@ -5855,6 +7042,38 @@ var Rewriter = class {
5855
7042
  break;
5856
7043
  }
5857
7044
  case "CallExpression": {
7045
+ const bound = this.bindings.get(node);
7046
+ const [name, setterFn] = node.arguments;
7047
+ if (bound && name) {
7048
+ const { declaration, setter } = bound;
7049
+ const path = scopePath(this.plan, scopeVar, base, declaration.scope);
7050
+ const slot = slotIndex(this.plan, declaration);
7051
+ const symbol = setter && this.plan.symbols.get(setter);
7052
+ patch.replace(node.start, name.start, "$$b.binding((");
7053
+ if (setterFn && setter && symbol) {
7054
+ const ref = JSON.stringify(`${this.plan.id}#${symbol}`);
7055
+ const owner = scopePath(this.plan, scopeVar, base, instanceScope(this.plan, setter.scope));
7056
+ patch.replace(name.end, node.end, `), ${path}, ${slot}, $$b.handlerProp(() => {}, ${ref}, ${owner}))`);
7057
+ } else patch.replace(name.end, node.end, `), ${path}, ${slot})`);
7058
+ visit(name);
7059
+ return;
7060
+ }
7061
+ const handler = this.handlers.get(node);
7062
+ if (handler) {
7063
+ const [fn, ...args] = node.arguments;
7064
+ const symbol = this.plan.symbols.get(handler);
7065
+ const ref = JSON.stringify(`${this.plan.id}#${symbol}`);
7066
+ const owner = scopePath(this.plan, scopeVar, base, instanceScope(this.plan, handler.scope));
7067
+ const modifiers = JSON.stringify(handler.modifiers ?? []);
7068
+ patch.replace(node.start, fn.end, `$$b.handlerProp(() => {}, ${ref}, ${owner}`);
7069
+ if (args.length === 0) patch.replace(fn.end, node.end, `, [], ${modifiers})`);
7070
+ else {
7071
+ patch.replace(fn.end, args[0].start, ", [");
7072
+ patch.replace(args.at(-1).end, node.end, `], ${modifiers})`);
7073
+ }
7074
+ for (const argument of args) visit(argument);
7075
+ return;
7076
+ }
5858
7077
  const fn = target(node.callee)?.declaration;
5859
7078
  if (fn?.kind === "function" && slotIndex(this.plan, fn) === -1) {
5860
7079
  const owner = scopePath(this.plan, scopeVar, base, instanceScope(this.plan, fn.scope));
@@ -5871,7 +7090,10 @@ var Rewriter = class {
5871
7090
  const slot = slotIndex(this.plan, item);
5872
7091
  return slot === -1 ? [] : [`$$b.pending(${path(item)}, ${slot})`];
5873
7092
  });
5874
- const value = checks.length === 0 ? "false" : checks.length === 1 ? checks[0] : `(${checks.join(" || ")})`;
7093
+ let value;
7094
+ if (checks.length === 0) value = "false";
7095
+ else if (checks.length === 1) value = checks[0];
7096
+ else value = `(${checks.join(" || ")})`;
5875
7097
  patch.replace(node.start, node.end, value);
5876
7098
  return;
5877
7099
  }
@@ -5984,8 +7206,8 @@ var ClientGenerator = class {
5984
7206
  lines.push(code);
5985
7207
  }
5986
7208
  generate() {
5987
- this.checkSupport();
5988
7209
  this.collectRenders();
7210
+ this.checkSupport();
5989
7211
  this.placeCode();
5990
7212
  this.emitFunctions();
5991
7213
  this.emitRoots();
@@ -6007,11 +7229,13 @@ var ClientGenerator = class {
6007
7229
  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
7230
  }
6009
7231
  const refresh = this.refreshTable();
7232
+ const tries = this.triesTable();
6010
7233
  const table = [
6011
7234
  `export const id = ${JSON.stringify(this.plan.id)};`,
6012
7235
  `export const props = ${this.propsMap()};`,
6013
7236
  `export const g = ${this.table()};`,
6014
- ...refresh ? [`export const refresh = ${refresh};`] : []
7237
+ ...refresh ? [`export const refresh = ${refresh};`] : [],
7238
+ ...tries ? [`export const t = ${tries};`] : []
6015
7239
  ];
6016
7240
  const clientCode = names.length > 0;
6017
7241
  if (merged || !clientCode) {
@@ -6121,7 +7345,7 @@ var ClientGenerator = class {
6121
7345
  reads(sites) {
6122
7346
  const result = /* @__PURE__ */ new Set();
6123
7347
  for (const site of sites) {
6124
- const shared = this.shared?.find(site.node) !== void 0;
7348
+ const shared = this.rewriter.sharedCall(site, "$$s", instanceScope(this.plan, site.scope)) !== void 0;
6125
7349
  for (const read of site.reads) if (!shared || read.declaration.kind !== "import") result.add(read.declaration);
6126
7350
  }
6127
7351
  return result;
@@ -6187,7 +7411,12 @@ var ClientGenerator = class {
6187
7411
  return lines.join("\n");
6188
7412
  }
6189
7413
  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);
7414
+ const rendered = this.renderedScopes();
7415
+ for (const site of this.model.sites) {
7416
+ const live = this.live.has(site);
7417
+ if (live && site.kind === "tag" && !site.owner?.keyed) this.error("A dynamic tag that changes on the client is not supported yet", site.range);
7418
+ 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);
7419
+ }
6191
7420
  }
6192
7421
  clientReads() {
6193
7422
  const reads = /* @__PURE__ */ new Set();
@@ -6289,7 +7518,7 @@ var ClientGenerator = class {
6289
7518
  const symbol = this.plan.symbols.get(site);
6290
7519
  if (!symbol) continue;
6291
7520
  const base = instanceScope(this.plan, site.scope);
6292
- let code = this.rewriter.rewrite(site, "$$s", base);
7521
+ let code = this.withTemplates(site, this.rewriter.rewrite(site, "$$s", base));
6293
7522
  if (site.node.type === "FunctionExpression" && unmarked(code).trimStart().startsWith("(")) code = `function ${code}`;
6294
7523
  this.part = symbol;
6295
7524
  if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.effect($$s, ${JSON.stringify(symbol)}, ${code});\n}`);
@@ -6341,7 +7570,9 @@ var ClientGenerator = class {
6341
7570
  const slot = slotIndex(this.plan, node.declaration);
6342
7571
  if (slot !== -1) {
6343
7572
  const value = site.awaits ? `(async () => (${expression()}))()` : expression();
6344
- this.emit(`export function ${name("m")}($$s) {\n $$b.memo($$s, ${slot}, () => ${value});\n}`);
7573
+ const timing = node.declaration.timing;
7574
+ const call = timing ? `$$b.timed($$s, ${slot}, ${timing.ms}, ${timing.kind === "throttled"}, () => ${value})` : `$$b.memo($$s, ${slot}, () => ${value})`;
7575
+ this.emit(`export function ${name("m")}($$s) {\n ${call};\n}`);
6345
7576
  }
6346
7577
  break;
6347
7578
  }
@@ -6372,7 +7603,9 @@ var ClientGenerator = class {
6372
7603
  const insert = this.findInsert(site);
6373
7604
  const anchor = insert && this.plan.anchors.get(insert);
6374
7605
  if (anchor !== void 0) {
6375
- const fn = this.plan.textContents.has(insert) ? "writeText" : this.plan.contents.has(insert) ? "content" : "text";
7606
+ let fn = "text";
7607
+ if (this.plan.textContents.has(insert)) fn = "writeText";
7608
+ else if (this.plan.contents.has(insert)) fn = "content";
6376
7609
  this.emit(`export function ${name("u")}($$s) {\n $$b.${fn}($$s, ${anchor}, ${expression()});\n}`);
6377
7610
  }
6378
7611
  return;
@@ -6401,14 +7634,23 @@ var ClientGenerator = class {
6401
7634
  }
6402
7635
  if (owner.kind === "component") {
6403
7636
  if (attribute.kind === "spread") {
6404
- this.error("A spread on a component cannot change on the client yet", site.range);
7637
+ const after = owner.attributes.slice(owner.attributes.indexOf(attribute) + 1).flatMap((item) => item.kind === "static" || item.kind === "value" || item.kind === "event" ? [item.name] : []);
7638
+ this.emit(`export function ${name("u")}($$s) {\n $$b.spreadProps($$s, ${anchor}, ${expression()}, ${JSON.stringify(after)});\n}`);
6405
7639
  return;
6406
7640
  }
6407
7641
  this.emit(`export function ${name("u")}($$s) {\n $$b.prop($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${expression()});\n}`);
6408
7642
  return;
6409
7643
  }
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") {
7644
+ if (attribute.kind === "spread") {
7645
+ const own = owner.attributes.flatMap((item) => item.kind === "static" || item.kind === "value" ? [item.name] : []);
7646
+ if (this.plan.styles.css) own.push(this.plan.styles.attribute, "style");
7647
+ const parts = owner.attributes.flatMap((item) => {
7648
+ if (item === attribute) return [expression()];
7649
+ return item.kind === "static" ? [`{ ${JSON.stringify(item.name)}: ${item.value === true ? "''" : JSON.stringify(decodeAttribute(item.value))} }`] : [];
7650
+ });
7651
+ const value = parts.length > 1 ? `$$b.mergeAttributes([${parts.join(", ")}])` : expression();
7652
+ this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${value}, ${JSON.stringify(own)});\n}`);
7653
+ } else if (attribute.kind === "value") {
6412
7654
  const value = (attribute.name === "class" ? classes(attribute.value.ast) : void 0) ?? expression();
6413
7655
  this.emit(`export function ${name("u")}($$s) {\n $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value});\n}`);
6414
7656
  }
@@ -6449,7 +7691,7 @@ var ClientGenerator = class {
6449
7691
  }
6450
7692
  case "for":
6451
7693
  case "repeat": {
6452
- const items = block.kind === "for" ? `Array.from(${header(0)})` : `Array.from({ length: ${header(0)} }, (_, index) => index)`;
7694
+ const items = block.kind === "for" ? `$$b.listOf(${header(0)})` : `Array.from({ length: ${header(0)} }, (_, index) => index)`;
6453
7695
  const key = this.keyFunction(block, base);
6454
7696
  const fallback = block.fallback ? this.renderName(block.fallback) : "undefined";
6455
7697
  const fallbackKinds = block.fallback ? this.kinds([block.fallback]) : [];
@@ -6519,7 +7761,7 @@ var ClientGenerator = class {
6519
7761
  }
6520
7762
  for (const scope of this.model.scopes) {
6521
7763
  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);
7764
+ 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
7765
  if (scope.kind === "body" && block && clientOnly && scope.body) this.renders.set(scope, {
6524
7766
  body: scope.body,
6525
7767
  block
@@ -6540,7 +7782,9 @@ var ClientGenerator = class {
6540
7782
  });
6541
7783
  const isItem = (block.kind === "for" || block.kind === "repeat") && block.body === body;
6542
7784
  const isCatch = block.kind === "try" && block.fallback === body;
6543
- const params = isItem ? ", $$item, $$index" : isCatch ? ", $$error" : "";
7785
+ let params = "";
7786
+ if (isItem) params = ", $$item, $$index";
7787
+ else if (isCatch) params = ", $$error";
6544
7788
  emitter.line(`export function r${scope.id}($$p${params}) {`);
6545
7789
  emitter.line(`let $$html = '';`);
6546
7790
  if (block.kind === "try" && isCatch) {
@@ -6562,7 +7806,8 @@ var ClientGenerator = class {
6562
7806
  }
6563
7807
  if (block.kind === "client") {
6564
7808
  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}`);
7809
+ const fallback = block.fallback ? `, [${this.kinds([block.fallback]).join(", ")}]` : "";
7810
+ this.emit(`export function k${scope.id}($$s) {\n $$b.fill($$s, ${anchor}, r${scope.id}${fallback});\n}`);
6566
7811
  }
6567
7812
  }
6568
7813
  }
@@ -6573,7 +7818,8 @@ var ClientGenerator = class {
6573
7818
  */
6574
7819
  withTemplates(site, code) {
6575
7820
  const templates = [];
6576
- for (const callee of site.calls) {
7821
+ const used = [...site.calls, ...site.reads.map((read) => read.declaration).filter((item) => item.kind === "template")];
7822
+ for (const callee of used) {
6577
7823
  if (callee.kind !== "template") continue;
6578
7824
  const template = this.model.scopes.find((item) => item.template?.name === callee.name && item.parent === callee.scope);
6579
7825
  for (const item of template ? this.inside(template) : []) if (!templates.includes(item)) templates.push(item);
@@ -6614,6 +7860,24 @@ var ClientGenerator = class {
6614
7860
  * The memos to load again when a server function calls `refresh(fn)`:
6615
7861
  * by the ID of `fn`, the scope kind and the update of each memo.
6616
7862
  */
7863
+ /**
7864
+ * The `#try` blocks that catch errors of client code, by the scope kinds
7865
+ * inside their bodies: the kind of the scope that holds the block, the
7866
+ * anchor of the block, the render functions of the body and the `#catch`
7867
+ * body, and the kinds of both bodies.
7868
+ */
7869
+ triesTable() {
7870
+ const entries = [];
7871
+ for (const scope of this.model.scopes) {
7872
+ const block = scope.block;
7873
+ if (block?.kind !== "try" || scope.body !== block.body || !this.plan.anchors.has(block) || !tryCatchesClient(this.model, block)) continue;
7874
+ const owner = instanceScope(this.plan, scope.parent);
7875
+ const fallback = this.plan.bodyScopes.get(block.fallback);
7876
+ const entry = `[${owner.id}, ${this.plan.anchors.get(block)}, ${JSON.stringify(`r${scope.id}`)}, ${JSON.stringify(`r${fallback.id}`)}, [${this.kinds(blockBodies(block)).join(", ")}]]`;
7877
+ for (const inside of this.model.scopes) if (isWithin(inside, scope)) entries.push(`${inside.id}: ${entry}`);
7878
+ }
7879
+ return entries.length > 0 ? `{ ${entries.join(", ")} }` : void 0;
7880
+ }
6617
7881
  refreshTable() {
6618
7882
  const table = /* @__PURE__ */ new Map();
6619
7883
  for (const node of this.plan.graph.nodes) {
@@ -6826,7 +8090,8 @@ function compile(source, options = {}) {
6826
8090
  for (const declaration of model.declarations) if (declaration.imported && options.serverImport) {
6827
8091
  declaration.serverImport = options.serverImport(declaration.imported.source, declaration.imported.name);
6828
8092
  if (declaration.serverImport !== void 0) {
6829
- declaration.refreshed = true;
8093
+ const name = declaration.imported.name;
8094
+ declaration.refreshed = !options.refreshed || options.refreshed.has("*") || options.refreshed.has(name);
6830
8095
  for (const read of declaration.reads) read.site.calls.add(declaration);
6831
8096
  }
6832
8097
  }
@@ -6841,7 +8106,7 @@ function compile(source, options = {}) {
6841
8106
  const plan = createPlan(file, graph, options.path, options.hideNames);
6842
8107
  const styleErrors = [...plan.styles.diagnostics, ...plan.diagnostics].filter((diagnostic) => diagnostic.severity === "error");
6843
8108
  if (styleErrors.length > 0) fail(styleErrors);
6844
- const captures = checkCaptures(file, plan);
8109
+ const captures = [...checkCaptures(file, plan, options.sendableClasses), ...options.envImport ? checkEnv(file, plan, options.envImport) : []];
6845
8110
  if (captures.length > 0) fail(captures);
6846
8111
  const shared = sharedContext(origin, modules, calls, options.path ?? filename);
6847
8112
  const client = generateClient(file, plan, options.merge, shared);
@@ -6907,6 +8172,18 @@ function siteLabel(source, site) {
6907
8172
  return `${site.label} (${at(source, site.range)})`;
6908
8173
  }
6909
8174
  /** A short name for a scope, such as `body of #for (12:3)`. */
8175
+ /** A short name of an anchor for the devtools: its tag, its block, or `$client`. */
8176
+ function anchorLabel(target) {
8177
+ if ("range" in target) return target.kind === "client" ? "$client" : target.label;
8178
+ switch (target.kind) {
8179
+ case "element": return `<${target.tag}>`;
8180
+ case "component": return `<${target.name}>`;
8181
+ case "dynamic": return "<dynamic tag>";
8182
+ case "listener": return `#${target.target} listener`;
8183
+ case "insert": return "insert";
8184
+ default: return `#${target.kind}`;
8185
+ }
8186
+ }
6910
8187
  function scopeLabel(source, scope) {
6911
8188
  if (scope.kind === "body" && scope.block) return `body of #${scope.block.kind} (${at(source, scope.block)})`;
6912
8189
  if (scope.kind === "template" && scope.template) return `#template ${scope.template.name}`;
@@ -6933,7 +8210,9 @@ function report(source, result, liveProps, parents) {
6933
8210
  }
6934
8211
  };
6935
8212
  visit(site);
6936
- const kind = site.kind === "client" ? `runs when the browser is ${site.trigger === "load" ? "loaded" : site.trigger}` : site.kind === "prop" ? "a function passed to a component" : "runs on the event";
8213
+ let kind = "runs on the event";
8214
+ if (site.kind === "client") kind = `runs when the browser is ${site.trigger === "load" ? "loaded" : site.trigger}`;
8215
+ else if (site.kind === "prop") kind = "a function passed to a component";
6937
8216
  roots.push({
6938
8217
  label: `${symbol}: ${site.label}`,
6939
8218
  at: at(source, site.range),
@@ -7056,6 +8335,6 @@ function inspect(source, options = {}) {
7056
8335
  };
7057
8336
  }
7058
8337
  //#endregion
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 };
8338
+ export { analyzeProject as A, isWithin as B, isReactiveModule as C, unmarked as D, originalPosition as E, parse$1 as F, buildGraph as I, BrumateError as L, forEachNode as M, resolveRelative as N, entryClasses as O, summarize as P, getLocation as R, sharedSites as S, builtin as T, lookup as V, functionId as _, scopeLabel as a, SHARED_QUERY as b, DEFAULT_MERGE as c, generateServer as d, instanceScope as f, createPlan as g, clientState as h, report as i, analyzeProjectProps as j, refreshedNames as k, generateClient as l, blockBodies as m, formatReport as n, CompileError as o, slotIndex as p, inspect as r, compile as s, anchorLabel as t, generateRender as u, getComponentName as v, resolveFromDisk as w, generateShared as x, hash as y, analyze$1 as z };
7060
8339
 
7061
- //# sourceMappingURL=inspect-BPchdWbU.js.map
8340
+ //# sourceMappingURL=inspect-BHpOw1LF.js.map