brumate 0.4.3 → 0.5.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 (63) hide show
  1. package/dist/{boot-D3NjfyUX.d.ts → boot-Difa0qdg.d.ts} +2 -8
  2. package/dist/cli.js +2 -2
  3. package/dist/{client-DNva05jp.d.ts → client-DvsU9qxG.d.ts} +107 -23
  4. package/dist/{client-AXNULmRZ.js → client-glvRglTB.js} +1000 -370
  5. package/dist/client-glvRglTB.js.map +1 -0
  6. package/dist/{defer-D3YMPgkX.js → defer-CNYYG-A5.js} +2 -2
  7. package/dist/{defer-D3YMPgkX.js.map → defer-CNYYG-A5.js.map} +1 -1
  8. package/dist/{devtools-BiP5fDiB.js → devtools-D8EioKXs.js} +4 -4
  9. package/dist/{devtools-BiP5fDiB.js.map → devtools-D8EioKXs.js.map} +1 -1
  10. package/dist/{devtools-panel-EQhLm39H.js → devtools-panel-BKmBqkau.js} +2 -2
  11. package/dist/{devtools-panel-EQhLm39H.js.map → devtools-panel-BKmBqkau.js.map} +1 -1
  12. package/dist/{features-CHY5Ekku.js → features-D5kLyihb.js} +19 -2
  13. package/dist/features-D5kLyihb.js.map +1 -0
  14. package/dist/{files-BUjvEO_o.js → files-ClQJlDcB.js} +2 -2
  15. package/dist/{files-BUjvEO_o.js.map → files-ClQJlDcB.js.map} +1 -1
  16. package/dist/index.d.ts +1 -8
  17. package/dist/index.js +1 -1
  18. package/dist/{inspect-BvPTZs6k.js → inspect-B8i6R3mZ.js} +877 -132
  19. package/dist/inspect-B8i6R3mZ.js.map +1 -0
  20. package/dist/{loader-DgMk6p9M.js → loader-DB0i9MwD.js} +4 -4
  21. package/dist/{loader-DgMk6p9M.js.map → loader-DB0i9MwD.js.map} +1 -1
  22. package/dist/{navigate-CfOr-TRF.js → navigate-BcV1qkkx.js} +2 -2
  23. package/dist/navigate-BcV1qkkx.js.map +1 -0
  24. package/dist/{produce-DS-dQaUX.js → produce-Cq6KKi7b.js} +2 -2
  25. package/dist/{produce-DS-dQaUX.js.map → produce-Cq6KKi7b.js.map} +1 -1
  26. package/dist/{rpc-Bxv7DYGe.js → rpc-BHlxmeWe.js} +5 -5
  27. package/dist/rpc-BHlxmeWe.js.map +1 -0
  28. package/dist/runtime/bundles.d.ts +9 -0
  29. package/dist/runtime/bundles.js +60 -0
  30. package/dist/runtime/bundles.js.map +1 -0
  31. package/dist/runtime/client.d.ts +2 -2
  32. package/dist/runtime/client.js +3 -3
  33. package/dist/runtime/devtools.d.ts +1 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/loader.d.ts +2 -2
  37. package/dist/runtime/loader.js +2 -2
  38. package/dist/runtime/server.d.ts +3 -3
  39. package/dist/runtime/server.js +4 -4
  40. package/dist/runtime/static-loader.d.ts +2 -2
  41. package/dist/runtime/static-loader.js +1 -1
  42. package/dist/runtime/testing.d.ts +2 -2
  43. package/dist/runtime/testing.js +2 -2
  44. package/dist/{server-BXMH3Z9T.d.ts → server-CAwIqrXl.d.ts} +44 -5
  45. package/dist/{server-O_rC-RRL.js → server-Doy5HR7r.js} +106 -17
  46. package/dist/server-Doy5HR7r.js.map +1 -0
  47. package/dist/{static-loader-BiUaZaag.d.ts → static-loader-9Nc1GvF0.d.ts} +2 -2
  48. package/dist/{static-loader-U_x-ctJI.js → static-loader-D0ARlMxM.js} +3 -26
  49. package/dist/static-loader-D0ARlMxM.js.map +1 -0
  50. package/dist/{stream-JGRPr7u5.js → stream-BdhzvPQO.js} +2 -2
  51. package/dist/{stream-JGRPr7u5.js.map → stream-BdhzvPQO.js.map} +1 -1
  52. package/dist/vite.d.ts +1 -1
  53. package/dist/vite.js +129 -51
  54. package/dist/vite.js.map +1 -1
  55. package/package.json +5 -1
  56. package/skills/brumate/references/errors.md +39 -5
  57. package/dist/client-AXNULmRZ.js.map +0 -1
  58. package/dist/features-CHY5Ekku.js.map +0 -1
  59. package/dist/inspect-BvPTZs6k.js.map +0 -1
  60. package/dist/navigate-CfOr-TRF.js.map +0 -1
  61. package/dist/rpc-Bxv7DYGe.js.map +0 -1
  62. package/dist/server-O_rC-RRL.js.map +0 -1
  63. package/dist/static-loader-U_x-ctJI.js.map +0 -1
@@ -292,7 +292,7 @@ const REACTIVE = /* @__PURE__ */ new Set([
292
292
  /** The module of the wrappers of event handlers, which the compiler reads. */
293
293
  const EVENTS_MODULE = "brumate/events";
294
294
  /** The wrappers that `brumate/events` exports. */
295
- const WRAPPERS$1 = /* @__PURE__ */ new Set([
295
+ const WRAPPERS$2 = /* @__PURE__ */ new Set([
296
296
  "prevent",
297
297
  "stop",
298
298
  "once",
@@ -405,6 +405,34 @@ function bindableNames(type, file) {
405
405
  function isBindableType(annotation) {
406
406
  return annotation?.type === "TSTypeReference" && annotation.typeName.type === "Identifier" && annotation.typeName.name === "Bindable";
407
407
  }
408
+ /**
409
+ * True for an expression that the compiler sees gives a promise: `new Promise(…)`, a call of a
410
+ * method of `Promise` or of `fetch`, a call of a server function or of an async function of the
411
+ * file, and a prop typed as a promise.
412
+ */
413
+ function givesPromise(node, scope) {
414
+ switch (node.type) {
415
+ case "ParenthesizedExpression":
416
+ case "TSAsExpression":
417
+ case "TSSatisfiesExpression":
418
+ case "TSNonNullExpression": return givesPromise(node.expression, scope);
419
+ case "NewExpression": return node.callee.type === "Identifier" && node.callee.name === "Promise";
420
+ case "Identifier": return lookup(scope, node.name)?.promise === true;
421
+ case "CallExpression": {
422
+ const callee = node.callee;
423
+ if (callee.type === "MemberExpression") return callee.object.type === "Identifier" && callee.object.name === "Promise";
424
+ if (callee.type !== "Identifier") return false;
425
+ if (callee.name === "fetch") return true;
426
+ const declaration = lookup(scope, callee.name);
427
+ return declaration?.kind === "server-function" || declaration?.serverImport !== void 0 || declaration?.kind === "function" && (declaration.site?.node)?.async === true;
428
+ }
429
+ default: return false;
430
+ }
431
+ }
432
+ /** The message of BRM188, for `code` at `place`. */
433
+ function promiseMessage(code, place) {
434
+ return `"${code}" gives a promise, and ${place} cannot wait for one. Await it in the code that runs, or read its value with $memo`;
435
+ }
408
436
  /** True for `Promise<...>`, or a union that holds one. */
409
437
  function isPromiseType(annotation) {
410
438
  if (annotation?.type === "TSUnionType") {
@@ -483,8 +511,10 @@ var Analyzer = class {
483
511
  this.markPromiseProps();
484
512
  for (const site of this.sites) new Resolver(this, site).run();
485
513
  this.addPendingReads();
514
+ this.checkLoadingHeaders();
486
515
  this.resolveRefs();
487
516
  this.check();
517
+ this.checkPromises();
488
518
  return {
489
519
  module: this.module,
490
520
  component: this.component,
@@ -516,6 +546,57 @@ var Analyzer = class {
516
546
  reference.site.reads.push(read);
517
547
  }
518
548
  }
549
+ /**
550
+ * The header of `#loading (posts) { … }` names memos that markup in the body reads. The block
551
+ * shows its fallback again while one of them, or a memo upstream of it, loads, so the header
552
+ * reads those memos too, as `$isPending(memo)` does.
553
+ */
554
+ checkLoadingHeaders() {
555
+ for (const site of this.sites) {
556
+ const block = site.block;
557
+ if (site.kind !== "block" || block?.kind !== "loading" || !block.on) continue;
558
+ let body;
559
+ for (const scope of this.scopes) if (scope.block === block && scope.body === block.body) body = scope;
560
+ const ast = unwrapTypes(block.on.ast);
561
+ const names = ast.type === "SequenceExpression" ? ast.expressions : [ast];
562
+ const reads = [...site.reads];
563
+ for (const name of names) {
564
+ const node = unwrapTypes(name);
565
+ let read;
566
+ for (const item of reads) if (node.type === "Identifier" && item.range.start === node.start) read = item;
567
+ const declaration = read?.declaration;
568
+ if (!declaration || declaration.kind !== "memo" && declaration.kind !== "async-memo" || !body || !this.markupReads(declaration, body)) {
569
+ this.report("error", `"${this.file.source.slice(name.start, name.end)}" in the #loading header is not a memo that markup in the body reads. Name a $memo of the component or of a block script around the block`, name);
570
+ continue;
571
+ }
572
+ const upstream = upstreamMemos(declaration);
573
+ for (const item of [declaration, ...upstream]) if (item.timing) {
574
+ this.report("warning", `#loading (${declaration.name}) shows its fallback while the $${item.timing.kind} memo "${item.name}" waits, at each change of its value`, name);
575
+ break;
576
+ }
577
+ for (const item of upstream) {
578
+ const added = {
579
+ ...read,
580
+ declaration: item,
581
+ range: {
582
+ start: name.end,
583
+ end: name.end
584
+ }
585
+ };
586
+ item.reads.push(added);
587
+ site.reads.push(added);
588
+ }
589
+ }
590
+ }
591
+ }
592
+ /** True when markup or a memo inside `body` reads `declaration`, so it renders from it. */
593
+ markupReads(declaration, body) {
594
+ for (const read of declaration.reads) {
595
+ const kind = read.site.kind;
596
+ if (read.range.start !== read.range.end && kind !== "function" && kind !== "server-function" && kind !== "event" && kind !== "effect" && kind !== "client" && isWithin(read.site.scope, body)) return true;
597
+ }
598
+ return false;
599
+ }
519
600
  /** Marks the props that the type of `$props<T>()` writes as `Promise<...>`. */
520
601
  markPromiseProps() {
521
602
  const names = /* @__PURE__ */ new Set();
@@ -626,7 +707,7 @@ var Analyzer = class {
626
707
  node = node.arguments[0];
627
708
  continue;
628
709
  }
629
- if (name === void 0 || !WRAPPERS$1.has(name)) break;
710
+ if (name === void 0 || !WRAPPERS$2.has(name)) break;
630
711
  const [handler, ...rest] = node.arguments;
631
712
  if (!handler || name !== "prevent" && rest.length > 0) {
632
713
  this.report("error", `${name} takes a handler`, node);
@@ -995,7 +1076,7 @@ var Analyzer = class {
995
1076
  node = handler;
996
1077
  continue;
997
1078
  }
998
- if (name === void 0 || !WRAPPERS$1.has(name) || !handler) break;
1079
+ if (name === void 0 || !WRAPPERS$2.has(name) || !handler) break;
999
1080
  const names = [];
1000
1081
  let unnamed = false;
1001
1082
  for (const key of keys) {
@@ -1198,10 +1279,7 @@ var Analyzer = class {
1198
1279
  });
1199
1280
  break;
1200
1281
  case "loading":
1201
- if (block.on) {
1202
- this.report("error", "#loading does not take a header yet. Write #loading { … }, since the header would be dropped", block.on);
1203
- this.header(block, scope, block.on, "loading");
1204
- }
1282
+ if (block.on) this.header(block, scope, block.on, "loading");
1205
1283
  this.visitBody(block.body, scope, block);
1206
1284
  if (block.fallback) this.visitBody(block.fallback, scope, block);
1207
1285
  break;
@@ -1236,6 +1314,20 @@ var Analyzer = class {
1236
1314
  else declaration.refs.push(ref);
1237
1315
  }
1238
1316
  }
1317
+ /**
1318
+ * Reports a promise where markup cannot wait for it: an event handler, the key of a `#for`, and
1319
+ * the name that `ref` or `$bind` binds. Markup waits for a promise in text and attributes only.
1320
+ */
1321
+ checkPromises() {
1322
+ for (const site of this.sites) {
1323
+ let place;
1324
+ if (site.kind === "event" || site.handlerProp) place = "an event handler";
1325
+ else if (site.kind === "block" && site.label === "for key") place = "the key of a #for";
1326
+ if (place && givesPromise(site.node, site.scope)) this.report("error", promiseMessage(this.file.source.slice(site.node.start, site.node.end), place), site.range);
1327
+ }
1328
+ for (const binding of this.bindings) if (binding.declaration.promise) this.report("error", promiseMessage(binding.declaration.name, "a binding"), binding.call);
1329
+ for (const declaration of this.declarations) if (declaration.promise) for (const ref of declaration.refs) this.report("error", promiseMessage(declaration.name, "a ref"), ref.attribute);
1330
+ }
1239
1331
  check() {
1240
1332
  for (const declaration of this.declarations) if (declaration.kind === "action") {
1241
1333
  if (lookup(declaration.scope, declaration.action)?.kind !== "server-function") this.report("error", `$action needs a server function of this file, and ${declaration.action} is not one`, declaration.range);
@@ -1794,11 +1886,13 @@ const SYNTAX = [
1794
1886
  entry("BRM021", "Expected an attribute name", "A tag has a character where an attribute name belongs.", "<input disabled>"),
1795
1887
  entry("BRM022", "Unknown event modifier \":{modifier}\"", "The modifier after an event name is not one of the known ones.", "<form onSubmit=(prevent(send))></form>"),
1796
1888
  entry("BRM180", "\"{name}\" is not an event name. Write \"{camel}\"", "An event of more than one word is written in camel case. The lower-case form is an error.", "<input onKeyDown=(handle) onFocusOut=(handle) />"),
1797
- entry("BRM181", "#loading does not take a header yet. Write #loading { … }, since the header would be dropped", "A `#loading` block has a header in parentheses. The compiler reads no meaning from it.", "#loading (data) {\n <p>{data.name}</p>\n} #else {\n <p>Loading</p>\n}"),
1889
+ entry("BRM186", "\"{name}\" in the #loading header is not a memo that markup in the body reads. Name a $memo of the component or of a block script around the block", "The header of `#loading (…)` names something other than a memo, or a memo that no markup in the body reads, so its loads would not show the fallback for that body.", "const posts = $memo(loadPosts(id));\n#loading (posts) {\n <p>{posts.length} posts</p>\n} #else {\n <p>Loading</p>\n}"),
1798
1890
  entry("BRM182", "The handler reads \"{name}\", a memo that can lack a value. Wait for it with await $resolve({name}), or check $isPending({name}) first", "A handler, a handler prop or a `$client` callback reads an async memo that may still be loading, with no `$isPending` check or `await $resolve` before the read.", "<script>\n const user = $memo(getUser(id));\n async function save() {\n await $resolve(user);\n send(user.name);\n }\n<\/script>"),
1799
1891
  entry("BRM183", "$resolve needs a $memo and, as an option, a timeout or a signal", "`$resolve` takes the name of a memo, and one object of options at most.", "async function save() {\n const profile = await $resolve(user, { timeout: 5000 });\n}"),
1800
1892
  entry("BRM184", "$resolve cannot run where a memo computes or markup renders. Call it in a handler, an effect or a $client callback", "`$resolve` waits, so it is called where an event starts the code, not where a memo computes or markup renders.", "async function save() {\n await $resolve(user);\n}"),
1801
1893
  entry("BRM185", "<{tag}> cannot be inside <{parent}>: the HTML parser closes or moves it before the page runs. Move it out of the <{parent}>, or use a <span> or as=\"span\"", "The HTML parser does not keep this nesting. A `<p>` ends at a block element such as `<div>`, an `<a>` or a `<form>` inside the same tag starts again, and a table keeps only table parts. The browser builds a page that differs from the markup, and the start and end markers of a block can land in different parents.", "<p>Total: <span>{total}</span></p>\n<div>\n <p>Total</p>\n</div>"),
1894
+ entry("BRM187", "The {kind} {name} of {component} did not settle: it writes a value that it reads, and runs again without end. Wrap the read or the write in $untrack, or write only when the value changes", "In the browser, an effect or an update writes a value that it reads, so each run schedules the next. Past 1000 rounds of effects, or 10000 rounds of updates, in one change, the page stops the loop and sends this error to the nearest `#try` in place of hanging the tab. A production build sends the short form `Update loop {scope}:{name} [BRM187]`.", "<script>\n import { $effect, $signal, $untrack } from 'brumate/signals';\n\n let query = $signal('');\n let saves = $signal(0);\n\n $effect(() => {\n void query;\n $untrack(saves++);\n });\n<\/script>"),
1895
+ entry("BRM188", "\"{name}\" gives a promise, and {place} cannot wait for one. Await it in the code that runs, or read its value with $memo", "Markup waits for a promise in text and in attribute values only. An event handler, the key of a `#for`, a `ref` and a `$bind` need the value at once, and the compiler sees that this expression gives a promise: `new Promise(…)`, a call of a server function or of an async function, or a prop typed as a promise.", "<button onClick=(() => save(draft))>Save</button>\n#for (user of users by user.id) {\n <p>{user.name}</p>\n}"),
1802
1896
  entry("BRM023", "Modifiers apply to elements. Put \":{modifier}\" on the element that the component renders", "An event modifier is on a component, which only passes the handler on.", "<form onSubmit=(prevent(send))></form>"),
1803
1897
  entry("BRM024", "Expected an event handler", "An event attribute has no `=` and no value.", "<button onClick=(() => count++)>Add</button>"),
1804
1898
  entry("BRM025", "An event handler must be an expression, not a string", "The value of an event attribute is a quoted string.", "<button onClick=(() => count++)>Add</button>"),
@@ -4115,7 +4209,7 @@ const SENDABLE = /* @__PURE__ */ new Set([
4115
4209
  "Boolean"
4116
4210
  ]);
4117
4211
  /** Compile-time functions whose argument is the value, such as `$signal(new Foo())`. */
4118
- const WRAPPERS = /* @__PURE__ */ new Set([
4212
+ const WRAPPERS$1 = /* @__PURE__ */ new Set([
4119
4213
  "$signal",
4120
4214
  "$memo",
4121
4215
  "$debounced",
@@ -4127,7 +4221,7 @@ function initializers(file) {
4127
4221
  function visit(node) {
4128
4222
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
4129
4223
  let init = node.init;
4130
- if (init.type === "CallExpression" && init.callee.type === "Identifier" && WRAPPERS.has(init.callee.name) && init.arguments[0]) init = init.arguments[0];
4224
+ if (init.type === "CallExpression" && init.callee.type === "Identifier" && WRAPPERS$1.has(init.callee.name) && init.arguments[0]) init = init.arguments[0];
4131
4225
  result.set(node.id.start, init);
4132
4226
  }
4133
4227
  for (const [, child] of children(node)) visit(child);
@@ -5466,7 +5560,7 @@ function isAsync(declaration) {
5466
5560
  /** The starts of the memo names in `$isPending(…)` and `$resolve(…)` calls of the file. */
5467
5561
  let checkedStarts = /* @__PURE__ */ new Set();
5468
5562
  /** The sites that render markup, which the server waits for outside `#loading`. */
5469
- const MARKUP_SITES = /* @__PURE__ */ new Set([
5563
+ const MARKUP_SITES$1 = /* @__PURE__ */ new Set([
5470
5564
  "insert",
5471
5565
  "attribute",
5472
5566
  "tag",
@@ -5492,7 +5586,7 @@ function waitedFor(declaration, seen = /* @__PURE__ */ new Set()) {
5492
5586
  if (read.range.start === read.range.end || checkedStarts.has(read.range.start)) continue;
5493
5587
  const site = read.site;
5494
5588
  const isHandlerProp = site.kind === "prop" && (site.handlerProp === true || site.node.type === "ArrowFunctionExpression" || site.node.type === "FunctionExpression");
5495
- if (MARKUP_SITES.has(site.kind) && !isHandlerProp && !inStreamedBody(site)) return true;
5589
+ if (MARKUP_SITES$1.has(site.kind) && !isHandlerProp && !inStreamedBody(site)) return true;
5496
5590
  if (site.kind === "memo" && site.declaration && waitedFor(site.declaration, seen)) return true;
5497
5591
  }
5498
5592
  return false;
@@ -6286,7 +6380,7 @@ function createPlan(file, graph, path, hideNames = false) {
6286
6380
  }
6287
6381
  }
6288
6382
  if (block.kind === "try" && tryCatchesClient(model, block)) scopes.get(bodyScopes.get(block.body)).needsId = true;
6289
- if (live && block.kind === "offscreen") scopes.get(bodyScopes.get(block.body)).needsId = true;
6383
+ if (live && (block.kind === "offscreen" || block.kind === "loading")) scopes.get(bodyScopes.get(block.body)).needsId = true;
6290
6384
  if (block.kind === "portal" || block.kind === "head") scopes.get(bodyScopes.get(block.body)).needsId = true;
6291
6385
  const inner = block.kind === "portal" || block.kind === "head" ? void 0 : outer;
6292
6386
  for (const body of blockBodies(block)) {
@@ -6665,13 +6759,19 @@ function clonedTemplate(parts) {
6665
6759
  kind: "attribute",
6666
6760
  name: attribute[1],
6667
6761
  value: attribute[2],
6668
- settled: part.settled
6762
+ settled: part.settled,
6763
+ promise: part.promise
6669
6764
  });
6670
6765
  continue;
6671
6766
  }
6672
6767
  const spread = SPREAD.exec(code);
6673
6768
  if (spread && reader.inTag) {
6674
- add({
6769
+ if (spread[1] === "spread" && part.promise) add({
6770
+ kind: "call",
6771
+ call: `$$b.fillSpread($$q, $$m, ${spread[2]})`,
6772
+ promise: part.promise
6773
+ });
6774
+ else add({
6675
6775
  kind: "call",
6676
6776
  call: `$$b.${spread[1] === "spread" ? "setSpread" : "setOn"}($$m, ${spread[2]})`
6677
6777
  });
@@ -6685,7 +6785,8 @@ function clonedTemplate(parts) {
6685
6785
  kind: "content",
6686
6786
  value: insert[1],
6687
6787
  at: insert[2],
6688
- settled: part.settled
6788
+ settled: part.settled,
6789
+ promise: part.promise
6689
6790
  });
6690
6791
  continue;
6691
6792
  }
@@ -6703,7 +6804,8 @@ function clonedTemplate(parts) {
6703
6804
  scope: code,
6704
6805
  anchor: Number(textEnd[1]),
6705
6806
  value: textInsert[1],
6706
- at: textInsert[2]
6807
+ at: textInsert[2],
6808
+ promise: value.promise
6707
6809
  }, parent);
6708
6810
  list[index + 3] = { static: rest };
6709
6811
  index += 2;
@@ -6715,7 +6817,8 @@ function clonedTemplate(parts) {
6715
6817
  scope: code,
6716
6818
  anchor: Number(textEnd[1]),
6717
6819
  value: textInsert[1],
6718
- at: textInsert[2]
6820
+ at: textInsert[2],
6821
+ promise: value.promise
6719
6822
  }]);
6720
6823
  reader.append(`<!--x${mark}-->`);
6721
6824
  list[index + 3] = { static: close.static.slice(9) };
@@ -6869,7 +6972,8 @@ function clonedTemplate(parts) {
6869
6972
  kind: "put",
6870
6973
  value: insert[1],
6871
6974
  at: insert[2],
6872
- settled: part.settled
6975
+ settled: part.settled,
6976
+ promise: part.promise
6873
6977
  }]);
6874
6978
  reader.append(`<!--x${mark}-->`);
6875
6979
  continue;
@@ -6898,6 +7002,13 @@ function clonedTemplate(parts) {
6898
7002
  };
6899
7003
  }
6900
7004
  /**
7005
+ * A write of cloned markup, as a statement. With `scope`, its value can be a promise, which
7006
+ * `fillValue` waits for, with `key` naming its place among the places of the scope.
7007
+ */
7008
+ function promised(scope, key, value, write) {
7009
+ return scope ? `$$b.fillValue(${scope}, ${key}, ${value}, ($$v) => ${write("$$v")});` : `${write(value)};`;
7010
+ }
7011
+ /**
6901
7012
  * Replaces the `$$html +=` lines of a render with a clone of a template, and the writes on the
6902
7013
  * elements that it marks. `hoist` makes a constant of the module. Returns false when the markup
6903
7014
  * needs HTML, such as markup in a branch or a loop of the render.
@@ -6989,19 +7100,26 @@ function cloneLines(emitter, hoist, fn = 0) {
6989
7100
  for (const write of writes) if (write.kind === "call") ordered.push(write);
6990
7101
  for (const write of writes) if (write.kind !== "call") ordered.push(write);
6991
7102
  for (const write of ordered) if (write.kind === "anchor") lines.push(`${indent}$$b.keep(${write.scope}, ${write.anchor}, $$e[${index}]${write.named ? ", true" : ""});`);
7103
+ else if (write.kind === "last" && write.promise) lines.push(`${indent}$$b.keepValue(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}, ${write.at ?? "undefined"}, true);`);
6992
7104
  else if (write.kind === "last") lines.push(`${indent}$$b.appendText(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`);
6993
- else if (write.kind === "text") lines.push(`${indent}$$b.keepText(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`);
6994
- else if (write.kind === "attribute") addLine(`$$b.setAttr($$e[${index}], ${write.name}, ${write.value});`, write.settled);
6995
- else if (write.kind === "component") addLine(`$$b.place($$e[${index}], ${write.call});`, write.settled);
7105
+ else if (write.kind === "text") {
7106
+ const helper = write.promise ? "keepValue" : "keepText";
7107
+ lines.push(`${indent}$$b.${helper}(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`);
7108
+ } else if (write.kind === "attribute") {
7109
+ const key = anchored?.kind === "anchor" ? `${anchored.anchor} ${JSON.parse(write.name)}` : `x${index} ${JSON.parse(write.name)}`;
7110
+ addLine(promised(write.promise && (anchored?.kind === "anchor" ? anchored.scope : write.promise), JSON.stringify(key), write.value, (value) => `$$b.setAttr($$e[${index}], ${write.name}, ${value})`), write.settled);
7111
+ } else if (write.kind === "component") addLine(`$$b.place($$e[${index}], ${write.call});`, write.settled);
6996
7112
  else if (write.kind === "comment") lines.push(`${indent}$$b.nameComment($$e[${index}], ${write.data});`);
6997
- else if (write.kind === "put") addLine(`$$b.putText($$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`, write.settled);
6998
- else if (write.kind === "call") lines.push(`${indent}${write.call.replace("$$m", () => `$$e[${index}]`)};`);
6999
- else if (write.kind === "marker") lines.push(`${indent}$$b.markBlock($$e[${index}], ${write.scope}, ${write.anchor}, ${JSON.stringify(write.suffix)});`);
7113
+ else if (write.kind === "put") addLine(promised(write.promise, JSON.stringify(`x${index}`), write.value, (value) => `$$b.putText($$e[${index}], ${value}${write.at ? `, ${write.at}` : ""})`), write.settled);
7114
+ else if (write.kind === "call") {
7115
+ const place = anchored?.kind === "anchor" ? `${anchored.scope}, ${anchored.anchor}` : `${write.promise}, ${JSON.stringify(`x${index}`)}`;
7116
+ lines.push(`${indent}${write.call.replace("$$q", () => place).replace("$$m", () => `$$e[${index}]`)};`);
7117
+ } else if (write.kind === "marker") lines.push(`${indent}$$b.markBlock($$e[${index}], ${write.scope}, ${write.anchor}, ${JSON.stringify(write.suffix)});`);
7000
7118
  else if (write.kind === "block") {
7001
7119
  const call = emitter.fills.get(`${write.scope}:${write.anchor}`);
7002
7120
  if (call === void 0) missing = true;
7003
7121
  else fills.push(`${indent}${call.replace("$$m", () => `$$e[${index}]`)};`);
7004
- } else addLine(`$$b.setContent($$e[${index}], ${write.value}${write.at ? `, ${write.at}` : at});`, write.settled);
7122
+ } else addLine(promised(write.promise && (anchored?.kind === "anchor" ? anchored.scope : write.promise), anchored?.kind === "anchor" ? String(anchored.anchor) : JSON.stringify(`x${index}`), write.value, (value) => `$$b.setContent($$e[${index}], ${value}${write.at ? `, ${write.at}` : at})`), write.settled);
7005
7123
  }
7006
7124
  for (const group of settled.values()) {
7007
7125
  const names = group.names.join(", ");
@@ -7051,6 +7169,172 @@ function cloneLines(emitter, hoist, fn = 0) {
7051
7169
  return true;
7052
7170
  }
7053
7171
  //#endregion
7172
+ //#region src/codegen/starts.ts
7173
+ /**
7174
+ * Finds, for each statement of awaited memos (`loads`), the last statement
7175
+ * before it that its loads must run after. The memos of a statement read
7176
+ * names: those of their expressions, and those that the local functions
7177
+ * and memos they call or read read and write, followed through.
7178
+ *
7179
+ * A statement holds the load when it declares one of those names (or the
7180
+ * load would throw a TDZ `ReferenceError`), or can change one: a write such
7181
+ * as `q = x`, a call such as `params.set(…)`, an argument of a call, or a
7182
+ * mention of a local function that mentions it. A plain read does not hold
7183
+ * it. A function declaration does not hold
7184
+ * it, since it runs nothing where it is written. `runs` is false for the
7185
+ * statements that run nothing where they are written, such as `$effect` on
7186
+ * the server, which do not hold it either.
7187
+ *
7188
+ * An awaited memo of another load is not followed: the load reads it as a
7189
+ * memo, so it waits for it on its own. It is listed in `memos`, as its
7190
+ * memo must exist before the load starts.
7191
+ */
7192
+ function findLoadStarts(statements, scope, loads, runs) {
7193
+ const awaited = /* @__PURE__ */ new Set();
7194
+ for (const declarations of loads.values()) for (const declaration of declarations) awaited.add(declaration);
7195
+ const touched = [];
7196
+ const declares = [];
7197
+ const changing = /* @__PURE__ */ new Set();
7198
+ for (const statement of statements) {
7199
+ touched.push(/* @__PURE__ */ new Set());
7200
+ declares.push(/* @__PURE__ */ new Set());
7201
+ if (statement.type !== "FunctionDeclaration") addChanging(changing, statement, false);
7202
+ }
7203
+ for (let current = scope; current; current = current.parent) for (const declaration of current.declarations.values()) {
7204
+ const at = findStatement(statements, declaration.range.start);
7205
+ if (at !== -1 && statements[at].type !== "FunctionDeclaration") declares[at].add(declaration);
7206
+ const isFunction = declaration.kind === "function" || declaration.kind === "server-function";
7207
+ for (const reference of [...declaration.reads, ...declaration.writes]) {
7208
+ const index = findStatement(statements, reference.range.start);
7209
+ const changes = isFunction || changing.has(reference.range.start) || declaration.writes.includes(reference);
7210
+ if (index !== -1 && changes) addMentions(touched[index], declaration, awaited);
7211
+ }
7212
+ }
7213
+ const result = /* @__PURE__ */ new Map();
7214
+ for (const [index, statement] of statements.entries()) {
7215
+ const declarations = loads.get(statement);
7216
+ if (!declarations) continue;
7217
+ const names = /* @__PURE__ */ new Set();
7218
+ const memos = [];
7219
+ for (const declaration of declarations) if (declaration.site) addSiteNames(names, memos, declaration.site, awaited, /* @__PURE__ */ new Set());
7220
+ let after = -1;
7221
+ for (let before = index - 1; before >= 0; before--) {
7222
+ const other = statements[before];
7223
+ if (loads.has(other) || !runs(other) || other.type === "FunctionDeclaration" || !(overlaps(touched[before], names) || overlaps(declares[before], names))) continue;
7224
+ after = before;
7225
+ break;
7226
+ }
7227
+ result.set(statement, {
7228
+ after,
7229
+ memos
7230
+ });
7231
+ }
7232
+ return result;
7233
+ }
7234
+ const WRAPPERS = /* @__PURE__ */ new Set([
7235
+ "ParenthesizedExpression",
7236
+ "ChainExpression",
7237
+ "TSAsExpression",
7238
+ "TSSatisfiesExpression",
7239
+ "TSNonNullExpression",
7240
+ "TSTypeAssertion"
7241
+ ]);
7242
+ /**
7243
+ * Adds the positions of the names that code can change: the root of the
7244
+ * target of a write, of a callee and of an argument, such as `q` in `q = x`,
7245
+ * `params` in `params.set(…)`, and every name in an argument, such as
7246
+ * `list` in `fill({ list })`. `root` is true
7247
+ * when the node is in such a place.
7248
+ */
7249
+ function addChanging(into, node, root) {
7250
+ switch (node.type) {
7251
+ case "Identifier":
7252
+ if (root) into.add(node.start);
7253
+ return;
7254
+ case "MemberExpression":
7255
+ addChanging(into, node.object, root);
7256
+ if (node.computed) addChanging(into, node.property, false);
7257
+ return;
7258
+ case "AssignmentExpression":
7259
+ addChanging(into, node.left, true);
7260
+ addChanging(into, node.right, false);
7261
+ return;
7262
+ case "UpdateExpression":
7263
+ addChanging(into, node.argument, true);
7264
+ return;
7265
+ case "UnaryExpression":
7266
+ addChanging(into, node.argument, node.operator === "delete");
7267
+ return;
7268
+ case "CallExpression":
7269
+ case "NewExpression":
7270
+ addChanging(into, node.callee, true);
7271
+ for (const argument of node.arguments) addEvery(into, argument);
7272
+ return;
7273
+ case "TaggedTemplateExpression":
7274
+ addChanging(into, node.tag, true);
7275
+ for (const expression of node.quasi.expressions) addEvery(into, expression);
7276
+ return;
7277
+ }
7278
+ const keep = root && (WRAPPERS.has(node.type) || node.type.endsWith("Pattern") || node.type === "SpreadElement" || node.type === "Property" || node.type === "RestElement");
7279
+ for (const [key, child] of children(node)) {
7280
+ if (node.type === "Property" && key === "key" && !node.computed) continue;
7281
+ addChanging(into, child, keep);
7282
+ }
7283
+ }
7284
+ /** Adds the position of every name in an argument, which the callee can change through it. */
7285
+ function addEvery(into, node) {
7286
+ if (node.type === "Identifier") {
7287
+ into.add(node.start);
7288
+ return;
7289
+ }
7290
+ for (const [, child] of children(node)) addEvery(into, child);
7291
+ }
7292
+ /** The index of the statement that holds a position, or -1. */
7293
+ function findStatement(statements, position) {
7294
+ for (const [index, statement] of statements.entries()) if (position >= statement.start && position < statement.end) return index;
7295
+ return -1;
7296
+ }
7297
+ /** Adds a name that a statement mentions, and the names that a local function it mentions mentions. */
7298
+ function addMentions(into, declaration, awaited) {
7299
+ if (into.has(declaration)) return;
7300
+ into.add(declaration);
7301
+ const site = declaration.site;
7302
+ if (site && (declaration.kind === "function" || declaration.kind === "server-function")) {
7303
+ for (const reference of [...site.reads, ...site.writes]) if (!awaited.has(reference.declaration)) addMentions(into, reference.declaration, awaited);
7304
+ }
7305
+ }
7306
+ /** Adds the names that a site reads and writes, and those of the functions and memos it reads. */
7307
+ function addSiteNames(names, memos, site, awaited, seen) {
7308
+ if (seen.has(site)) return;
7309
+ seen.add(site);
7310
+ for (const reference of [...site.reads, ...site.writes]) {
7311
+ const declaration = reference.declaration;
7312
+ if (awaited.has(declaration)) {
7313
+ if (declaration.site !== site && !memos.includes(declaration)) memos.push(declaration);
7314
+ continue;
7315
+ }
7316
+ names.add(declaration);
7317
+ if (declaration.site && declaration.kind !== "import") addSiteNames(names, memos, declaration.site, awaited, seen);
7318
+ }
7319
+ }
7320
+ /** True when two sets share a value. */
7321
+ function overlaps(left, right) {
7322
+ for (const value of left) if (right.has(value)) return true;
7323
+ return false;
7324
+ }
7325
+ const FUNCTIONS = /* @__PURE__ */ new Set([
7326
+ "FunctionDeclaration",
7327
+ "FunctionExpression",
7328
+ "ArrowFunctionExpression"
7329
+ ]);
7330
+ /** True when code waits where it runs: an `await` or a `for await` outside the functions it declares. */
7331
+ function hasAwait(node) {
7332
+ if (node.type === "AwaitExpression" || node.type === "ForOfStatement" && node.await) return true;
7333
+ if (FUNCTIONS.has(node.type)) return false;
7334
+ for (const [, child] of children(node)) if (hasAwait(child)) return true;
7335
+ return false;
7336
+ }
7337
+ //#endregion
7054
7338
  //#region src/codegen/scopes.ts
7055
7339
  /** Returns the nearest scope, from `scope` outwards, that gets an ID at render time. */
7056
7340
  function instanceScope(plan, scope) {
@@ -7100,6 +7384,13 @@ function isMemo(declaration) {
7100
7384
  return declaration.kind === "memo" || declaration.kind === "async-memo";
7101
7385
  }
7102
7386
  /**
7387
+ * True for the header of `#loading (memo)`, which reads whether its memos are pending, not their
7388
+ * values, so the render does not wait for them.
7389
+ */
7390
+ function isLoadingHeader(site) {
7391
+ return site.kind === "block" && site.block?.kind === "loading";
7392
+ }
7393
+ /**
7103
7394
  * The scope whose render waits for a read. A read with `await` inside a
7104
7395
  * `#loading` body makes the render around the block wait, so it counts as
7105
7396
  * a read in the scope that holds the block. Inside a `#defer` body, the
@@ -7127,7 +7418,7 @@ function blockingMemos(plan) {
7127
7418
  continue;
7128
7419
  }
7129
7420
  for (const read of declaration.reads) {
7130
- if (read.range.start === read.range.end) continue;
7421
+ if (read.range.start === read.range.end || isLoadingHeader(read.site)) continue;
7131
7422
  const site = read.site;
7132
7423
  if (DEFERRED_SITES$1.has(site.kind) || site.kind === "memo") continue;
7133
7424
  let template = false;
@@ -7174,7 +7465,7 @@ function awaitedMemos(plan, body, blocking) {
7174
7465
  for (const site of plan.graph.model.sites) {
7175
7466
  if (DEFERRED_SITES$1.has(site.kind)) continue;
7176
7467
  for (const read of site.reads) {
7177
- if (read.range.start === read.range.end || loadingBody(readScope(read)) !== body) continue;
7468
+ if (read.range.start === read.range.end || isLoadingHeader(site) || loadingBody(readScope(read)) !== body) continue;
7178
7469
  if (isMemo(read.declaration) && !blocking.has(read.declaration)) result.add(read.declaration);
7179
7470
  }
7180
7471
  }
@@ -7186,17 +7477,88 @@ function awaitedMemos(plan, body, blocking) {
7186
7477
  function findSite(plan, node) {
7187
7478
  for (const item of plan.graph.model.sites) if (item.node === node) return item;
7188
7479
  }
7480
+ /** Global functions whose result is never a promise. */
7481
+ const PLAIN_FUNCTIONS = /* @__PURE__ */ new Set([
7482
+ "Boolean",
7483
+ "Number",
7484
+ "String",
7485
+ "decodeURIComponent",
7486
+ "encodeURIComponent",
7487
+ "parseFloat",
7488
+ "parseInt"
7489
+ ]);
7490
+ /** Methods of strings, numbers and arrays whose result is never a promise. */
7491
+ const PLAIN_METHODS = /* @__PURE__ */ new Set([
7492
+ "concat",
7493
+ "endsWith",
7494
+ "filter",
7495
+ "includes",
7496
+ "indexOf",
7497
+ "join",
7498
+ "map",
7499
+ "padEnd",
7500
+ "padStart",
7501
+ "repeat",
7502
+ "replace",
7503
+ "replaceAll",
7504
+ "slice",
7505
+ "split",
7506
+ "startsWith",
7507
+ "toFixed",
7508
+ "toLocaleString",
7509
+ "toLowerCase",
7510
+ "toString",
7511
+ "toUpperCase",
7512
+ "trim",
7513
+ "trimEnd",
7514
+ "trimStart"
7515
+ ]);
7516
+ /**
7517
+ * True if a value of markup can be a promise, which the browser writes once it settles: a call,
7518
+ * such as `{load(id)}` or `title=getTitle()`, or a read of a prop typed as a promise. A call of a
7519
+ * macro of brumate, such as `$isPending`, of `String` or of a method of strings and arrays, such
7520
+ * as `name.toUpperCase()`, gives no promise, nor does a string, a number or a property. An
7521
+ * object can hold one, for a spread.
7522
+ */
7523
+ function mayBePromise(node, site) {
7524
+ switch (node.type) {
7525
+ case "ParenthesizedExpression":
7526
+ case "TSAsExpression":
7527
+ case "TSSatisfiesExpression":
7528
+ case "TSNonNullExpression": return mayBePromise(node.expression, site);
7529
+ case "ConditionalExpression": return mayBePromise(node.consequent, site) || mayBePromise(node.alternate, site);
7530
+ case "LogicalExpression": return mayBePromise(node.left, site) || mayBePromise(node.right, site);
7531
+ case "SequenceExpression": return mayBePromise(node.expressions.at(-1), site);
7532
+ case "NewExpression": return node.callee.type === "Identifier" && node.callee.name === "Promise";
7533
+ case "TaggedTemplateExpression":
7534
+ case "ImportExpression": return true;
7535
+ case "ObjectExpression":
7536
+ for (const property of node.properties) if (mayBePromise(property.type === "SpreadElement" ? property.argument : property.value, site)) return true;
7537
+ return false;
7538
+ case "CallExpression": {
7539
+ const callee = node.callee;
7540
+ if (callee.type === "Identifier") return !callee.name.startsWith("$") && !PLAIN_FUNCTIONS.has(callee.name);
7541
+ return !(callee.type === "MemberExpression" && callee.property.type === "Identifier" && PLAIN_METHODS.has(callee.property.name));
7542
+ }
7543
+ case "Identifier":
7544
+ for (const reference of site?.reads ?? []) if (reference.declaration.promise === true && reference.range.start === node.start) return true;
7545
+ return false;
7546
+ default: return false;
7547
+ }
7548
+ }
7189
7549
  /**
7190
7550
  * True if the markup of a `#loading` body may wait for something other than
7191
7551
  * the memos it reads, so the body cannot render in place when those memos
7192
- * are ready: a child component, a dynamic tag, a template, or an insert of
7193
- * a prop, which can be a promise or the children of a parent. Bodies that
7194
- * render later, such as those of a `#loading` or a `#defer` inside it, wait
7195
- * on their own.
7552
+ * are ready: a child component, a dynamic tag, a template, an insert of
7553
+ * a prop, which can be a promise or the children of a parent, or an insert or
7554
+ * attribute whose value can be a promise, such as a call. Bodies that render
7555
+ * later, such as those of a `#loading` or a `#defer` inside it, wait on their
7556
+ * own.
7196
7557
  */
7197
7558
  function mayWait(plan, nodes) {
7198
7559
  function insertWaits(node) {
7199
7560
  const site = findSite(plan, node.expression.ast);
7561
+ if (mayBePromise(node.expression.ast, site)) return true;
7200
7562
  if (!site) return false;
7201
7563
  for (const read of site.reads) {
7202
7564
  const kind = read.declaration.kind;
@@ -7204,6 +7566,13 @@ function mayWait(plan, nodes) {
7204
7566
  }
7205
7567
  return false;
7206
7568
  }
7569
+ function attributesWait(node) {
7570
+ for (const attribute of node.attributes) {
7571
+ const value = attribute.kind === "value" || attribute.kind === "spread" || attribute.kind === "computed" ? attribute.value : true;
7572
+ if (value !== true && mayBePromise(value.ast, findSite(plan, value.ast))) return true;
7573
+ }
7574
+ return false;
7575
+ }
7207
7576
  for (const node of nodes) switch (node.kind) {
7208
7577
  case "component":
7209
7578
  case "dynamic": return true;
@@ -7211,6 +7580,8 @@ function mayWait(plan, nodes) {
7211
7580
  if (insertWaits(node)) return true;
7212
7581
  break;
7213
7582
  case "element":
7583
+ if (attributesWait(node) || mayWait(plan, node.children)) return true;
7584
+ break;
7214
7585
  case "fragment":
7215
7586
  if (mayWait(plan, node.children)) return true;
7216
7587
  break;
@@ -7374,10 +7745,38 @@ const NEVER_PROMISE = /* @__PURE__ */ new Set([
7374
7745
  * a function. A memo with `await` inside is an async function, so its value is a promise whatever
7375
7746
  * its expression gives, as in ``$memo(`Hi ${(await load()).name}`)`` or `$memo([await load()])`.
7376
7747
  */
7748
+ /** The sites of markup, whose `await` of a memo the browser waits for at the start of the markup. */
7749
+ const MARKUP_SITES = /* @__PURE__ */ new Set([
7750
+ "insert",
7751
+ "attribute",
7752
+ "tag",
7753
+ "spread",
7754
+ "style",
7755
+ "block",
7756
+ "prop"
7757
+ ]);
7377
7758
  function isNeverPromise(declaration) {
7378
7759
  const node = declaration.site?.node;
7379
7760
  return declaration.kind === "memo" && node !== void 0 && (isPrimitive(node) || NEVER_PROMISE.has(node.type));
7380
7761
  }
7762
+ /**
7763
+ * True for a memo that can hold a promise in the browser: an `await` in it makes one, and others
7764
+ * give one unless they always give a primitive, an array or a function.
7765
+ */
7766
+ function mayLoad(declaration) {
7767
+ return (declaration.kind === "memo" || declaration.kind === "async-memo") && !isNeverPromise(declaration);
7768
+ }
7769
+ /**
7770
+ * True if markup can render a `#loading` block: one of its own, or one in a component, or in
7771
+ * children or a template that an insert renders.
7772
+ */
7773
+ function mayReveal(nodes) {
7774
+ let found = false;
7775
+ forEachNode(nodes, (node) => {
7776
+ found ||= node.kind === "loading" || node.kind === "component" || node.kind === "dynamic" || node.kind === "insert";
7777
+ });
7778
+ return found;
7779
+ }
7381
7780
  /** The static or value attribute named `style`. */
7382
7781
  function findStyleAttribute(attributes) {
7383
7782
  for (const attribute of attributes) if ((attribute.kind === "static" || attribute.kind === "value") && attribute.name === "style") return attribute;
@@ -7516,6 +7915,23 @@ var Emitter = class {
7516
7915
  /** The kinds of the `{` that are open: of a function, a branch or loop, or a plain block. */
7517
7916
  braces = [];
7518
7917
  fnCount = 0;
7918
+ /** The number of `$$b.wait` calls that the render opened, which its end closes. */
7919
+ waits = 0;
7920
+ /** Declarations that the rest of a render after `await` can assign: `let` before the split. */
7921
+ reassignable = /* @__PURE__ */ new Set();
7922
+ /**
7923
+ * The scope whose script the function that is being written splits at `await $memo`: the
7924
+ * component in the render module, or the body of a render function of a block.
7925
+ */
7926
+ splitScope;
7927
+ /** The awaited memos that a split waits for, so markup after it reads their values. */
7928
+ splitMemos = /* @__PURE__ */ new Set();
7929
+ /** In the browser, the awaited memos whose loads start before their `await`, in `$$w_<name>`. */
7930
+ startedMemos = /* @__PURE__ */ new Set();
7931
+ /** The memos that hold a primitive on the server, for the start points of loads in the browser. */
7932
+ serverInline;
7933
+ /** In the browser, the awaited memos of other loads that the load of a statement reads. */
7934
+ loadMemos = /* @__PURE__ */ new Map();
7519
7935
  /**
7520
7936
  * The calls that fill the nested blocks of a clone, by the scope and the anchor of each block.
7521
7937
  * `$$m` in a call is the start comment of the block.
@@ -7558,6 +7974,7 @@ var Emitter = class {
7558
7974
  this.ctxArgument = options.mode === "server" ? "$$ctx" : "undefined";
7559
7975
  this.inParagraph = options.mode === "server" && !plan.hideNames ? paragraphComponents(file) : /* @__PURE__ */ new Set();
7560
7976
  this.blocking = blockingMemos(plan);
7977
+ this.splitScope = options.waits ? plan.graph.model.component : void 0;
7561
7978
  this.inline = options.mode === "server" ? plainValues(plan, this.blocking) : /* @__PURE__ */ new Set();
7562
7979
  for (const site of plan.graph.model.sites) this.sitesByNode.set(site.node, site);
7563
7980
  for (const node of plan.graph.nodes) if (node.kind !== "source" && plan.graph.live.has(node)) this.liveSites.add(node.site);
@@ -7636,6 +8053,34 @@ var Emitter = class {
7636
8053
  else this.braces.push({ kind: "control" });
7637
8054
  }
7638
8055
  }
8056
+ /** Opens the rest of a render after `await`, which stays in the function that holds it. */
8057
+ openRest(code) {
8058
+ this.flush();
8059
+ const fn = this.currentFn;
8060
+ this.push(`${" ".repeat(this.depth)}${code}`);
8061
+ this.depth++;
8062
+ this.braces.push({
8063
+ kind: "fn",
8064
+ fn
8065
+ });
8066
+ this.waits++;
8067
+ }
8068
+ /**
8069
+ * Writes the body of a render function whose script `await $memo` splits: `content` writes
8070
+ * the body of `scope`, and the rests that it opened close after `end`, the return line.
8071
+ */
8072
+ splitBody(scope, content, end) {
8073
+ const outer = this.splitScope;
8074
+ const waits = this.waits;
8075
+ const memos = [...this.splitMemos];
8076
+ this.splitScope = scope;
8077
+ content();
8078
+ this.splitScope = outer;
8079
+ end();
8080
+ this.splitMemos.clear();
8081
+ for (const memo of memos) this.splitMemos.add(memo);
8082
+ for (; this.waits > waits; this.waits--) this.close("});");
8083
+ }
7639
8084
  close(code = "}") {
7640
8085
  this.flush();
7641
8086
  this.depth--;
@@ -7700,11 +8145,21 @@ var Emitter = class {
7700
8145
  if (last && "static" in last) last.static += text;
7701
8146
  else this.parts.push({ static: text });
7702
8147
  }
7703
- code(code, settled) {
7704
- this.parts.push(settled ? {
8148
+ code(code, settled, promise) {
8149
+ const part = settled ? {
7705
8150
  code,
7706
8151
  settled
7707
- } : { code });
8152
+ } : { code };
8153
+ if (promise) part.promise = promise;
8154
+ this.parts.push(part);
8155
+ }
8156
+ /**
8157
+ * In the browser, the scope of a value of markup that can be a promise: one that calls code,
8158
+ * such as `{load(id)}`, or reads a prop typed as a promise. The clone writes its value once it
8159
+ * settles, and a `#loading` around it shows its fallback until then.
8160
+ */
8161
+ promiseScope(expression, scope) {
8162
+ return this.options.mode === "client" && mayBePromise(expression.ast, this.sitesByNode.get(expression.ast)) ? this.scopeVar(instanceScope(this.plan, scope)) : void 0;
7708
8163
  }
7709
8164
  /**
7710
8165
  * In the browser, the memos that values of the markup read that never change and can be a
@@ -7719,7 +8174,7 @@ var Emitter = class {
7719
8174
  if (!site || this.liveSites.has(site)) return;
7720
8175
  for (const reference of site.reads) {
7721
8176
  const declaration = reference.declaration;
7722
- if (isMemo(declaration) && !isNeverPromise(declaration) && !names.includes(declaration.name)) names.push(declaration.name);
8177
+ if (isMemo(declaration) && !isNeverPromise(declaration) && !this.splitMemos.has(declaration) && !names.includes(declaration.name)) names.push(declaration.name);
7723
8178
  }
7724
8179
  }
7725
8180
  return names.length > 0 ? {
@@ -7811,6 +8266,11 @@ var Emitter = class {
7811
8266
  const names = this.options.mode === "server" ? `, ${JSON.stringify(slotNames)}` : "";
7812
8267
  this.line(`${this.helper("slots")}(${this.scopeVar(scope)}, [${values.join(", ")}]${names});`);
7813
8268
  }
8269
+ if (this.options.mode === "client") {
8270
+ const loads = [];
8271
+ for (const declaration of scope.declarations.values()) if (this.blocking.has(declaration) && mayLoad(declaration)) loads.push(declaration.name);
8272
+ if (loads.length > 0) this.line(`$$b.countLoads(${this.scopeVar(instanceScope(this.plan, scope))}, [${loads.join(", ")}]);`);
8273
+ }
7814
8274
  if (scope.kind === "component") {
7815
8275
  const bindable = this.bindableProps(scope);
7816
8276
  if (bindable.length > 0) this.line(`${this.helper("bindings")}(${this.scopeVar(scope)}, $$props, { ${bindable.join(", ")} });`);
@@ -7835,8 +8295,9 @@ var Emitter = class {
7835
8295
  * markup makes the page wait for, without the keyword, is awaited on its
7836
8296
  * own, as the code reads.
7837
8297
  */
7838
- blockingDeclarations(statement) {
7839
- if (this.options.mode !== "server" || statement.type !== "VariableDeclaration") return;
8298
+ blockingDeclarations(statement, server = this.options.mode === "server") {
8299
+ if (!server || statement.type !== "VariableDeclaration") return;
8300
+ const inline = this.options.mode === "server" ? this.inline : this.serverInline ??= plainValues(this.plan, this.blocking);
7840
8301
  const declarations = [];
7841
8302
  let awaited = true;
7842
8303
  for (const declarator of statement.declarations) {
@@ -7849,7 +8310,7 @@ var Emitter = class {
7849
8310
  continue;
7850
8311
  }
7851
8312
  awaited &&= declaration.awaited === true;
7852
- if (!this.inline.has(declaration)) declarations.push(declaration);
8313
+ if (!inline.has(declaration)) declarations.push(declaration);
7853
8314
  }
7854
8315
  return declarations.length === 0 ? void 0 : {
7855
8316
  declarations,
@@ -7877,6 +8338,117 @@ var Emitter = class {
7877
8338
  this.line(`if (($$t = $$b.waitAll([${names.join(", ")}])) !== undefined) await $$t;`);
7878
8339
  for (const declaration of run) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
7879
8340
  }
8341
+ /**
8342
+ * True for a statement that runs nothing where it is written on the server,
8343
+ * such as `$effect`, an import or a type. It does not end a run of awaits.
8344
+ */
8345
+ isQuiet(statement) {
8346
+ if (statement.type === "ImportDeclaration" || TYPE_DECLARATIONS.has(statement.type)) return true;
8347
+ if (statement.type !== "ExpressionStatement") return false;
8348
+ const expression = statement.expression;
8349
+ return expression.type === "CallExpression" && expression.callee.type === "Identifier" && (expression.callee.name === "$effect" || expression.callee.name === "$client");
8350
+ }
8351
+ /**
8352
+ * The awaited memos whose loads start before statements that do not hold
8353
+ * them, by the index of the statement that they start after (-1 for the
8354
+ * top). Each `await` still waits where it is written. The browser, where
8355
+ * the script splits at each `await`, places them as the server does. A
8356
+ * load there reads the values of the memos whose loads it waits for as
8357
+ * parameters, so one that reads such a memo through a function or another
8358
+ * memo starts after that memo's `await`.
8359
+ */
8360
+ earlyLoads(statements, scope, splits) {
8361
+ const moved = /* @__PURE__ */ new Map();
8362
+ const server = this.options.mode === "server";
8363
+ if (!server && !splits) return moved;
8364
+ const loads = /* @__PURE__ */ new Map();
8365
+ const declaredAt = /* @__PURE__ */ new Map();
8366
+ for (const [index, statement] of statements.entries()) {
8367
+ const blocking = this.blockingDeclarations(statement, true);
8368
+ if (blocking?.awaited && statement.type === "VariableDeclaration" && blocking.declarations.length === statement.declarations.length && (server || this.awaitedMemos(statement, scope)?.every(Boolean))) {
8369
+ loads.set(statement, blocking.declarations);
8370
+ for (const declaration of blocking.declarations) declaredAt.set(declaration, index);
8371
+ }
8372
+ }
8373
+ if (loads.size === 0) return moved;
8374
+ const starts = findLoadStarts(statements, scope, loads, (statement) => !this.isQuiet(statement));
8375
+ const runs = /* @__PURE__ */ new Map();
8376
+ if (!server) {
8377
+ let members = [];
8378
+ const endRun = () => {
8379
+ if (members.length > 1) for (const member of members) runs.set(member, members[0]);
8380
+ members = [];
8381
+ };
8382
+ for (const [index, statement] of statements.entries()) if (this.blockingDeclarations(statement, true)?.awaited) members.push(index);
8383
+ else if (!this.isQuiet(statement)) endRun();
8384
+ endRun();
8385
+ }
8386
+ const placed = /* @__PURE__ */ new Map();
8387
+ for (const [index, statement] of statements.entries()) {
8388
+ const start = starts.get(statement);
8389
+ if (!start) continue;
8390
+ let after = start.after;
8391
+ for (const memo of start.memos) after = Math.max(after, placed.get(memo) ?? index - 1);
8392
+ if (!server) {
8393
+ const reads = /* @__PURE__ */ new Set();
8394
+ for (const declaration of loads.get(statement)) for (const reference of declaration.site?.reads ?? []) reads.add(reference.declaration);
8395
+ for (const memo of start.memos) {
8396
+ const at = declaredAt.get(memo) ?? -1;
8397
+ if (at > after && !reads.has(memo)) after = at;
8398
+ }
8399
+ this.loadMemos.set(statement, start.memos);
8400
+ }
8401
+ let ends = false;
8402
+ let inRun = false;
8403
+ for (let between = after + 1; between < index && !ends; between++) {
8404
+ const other = statements[between];
8405
+ const blocking = this.blockingDeclarations(other, true);
8406
+ if (blocking?.awaited) inRun = true;
8407
+ else if (!this.isQuiet(other)) ends = inRun || blocking !== void 0 || hasAwait(other);
8408
+ }
8409
+ const first = runs.get(index);
8410
+ if (!ends && first !== void 0) {
8411
+ after = Math.max(after, first - 1);
8412
+ ends = true;
8413
+ }
8414
+ const at = ends ? after : index;
8415
+ for (const declaration of loads.get(statement)) placed.set(declaration, at);
8416
+ if (ends) {
8417
+ const list = moved.get(after) ?? [];
8418
+ list.push(statement);
8419
+ moved.set(after, list);
8420
+ }
8421
+ }
8422
+ return moved;
8423
+ }
8424
+ /**
8425
+ * Declares the memos of a load that starts early, and starts them. In the browser, the load
8426
+ * goes in `$$w_<name>`, which its `await` waits for, and it waits for the loads of the memos
8427
+ * that it reads which have not reached their `await`.
8428
+ */
8429
+ startLoads(statements) {
8430
+ for (const statement of statements ?? []) {
8431
+ if (this.options.mode === "client") {
8432
+ const declarations = statement.type === "VariableDeclaration" ? statement.declarations : [];
8433
+ for (const declarator of declarations) {
8434
+ const declaration = this.awaitedMemos(statement, this.splitScope)[declarations.indexOf(declarator)];
8435
+ const load = this.source(declarator.init);
8436
+ const waits = [];
8437
+ const names = [];
8438
+ for (const memo of this.loadMemos.get(statement) ?? []) if (this.startedMemos.has(memo) && !this.splitMemos.has(memo)) {
8439
+ waits.push(`$$w_${memo.name}`);
8440
+ names.push(memo.name);
8441
+ }
8442
+ const value = waits.length > 0 ? `$$b.after([${waits.join(", ")}], (${names.join(", ")}) => ${load})` : `$$b.started(() => ${load})`;
8443
+ this.line(`const $$w_${declaration.name} = ${value};`);
8444
+ this.startedMemos.add(declaration);
8445
+ }
8446
+ continue;
8447
+ }
8448
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
8449
+ for (const declaration of this.blockingDeclarations(statement).declarations) this.line(`$$b.start(${promiseName(declaration.name)});`);
8450
+ }
8451
+ }
7880
8452
  emitStatements(statements, scope) {
7881
8453
  let run = [];
7882
8454
  const endRun = () => {
@@ -7885,13 +8457,30 @@ var Emitter = class {
7885
8457
  run = [];
7886
8458
  }
7887
8459
  };
7888
- for (const statement of statements) {
8460
+ const splits = this.options.mode === "client" && scope === this.splitScope;
8461
+ const early = this.earlyLoads(statements, scope, splits);
8462
+ const started = /* @__PURE__ */ new Set();
8463
+ for (const list of early.values()) for (const statement of list) started.add(statement);
8464
+ this.startLoads(early.get(-1));
8465
+ let lastAwait = -1;
8466
+ for (const [index, statement] of statements.entries()) if (splits && this.awaitedMemos(statement, scope)) lastAwait = index;
8467
+ if (splits) {
8468
+ for (const declaration of this.markupAwaits(scope)) if (declaration.scope === scope) lastAwait = statements.length;
8469
+ }
8470
+ for (const [index, statement] of statements.entries()) {
8471
+ if (index > 0) this.startLoads(early.get(index - 1));
8472
+ const awaited = splits ? this.awaitedMemos(statement, scope) : void 0;
8473
+ if (awaited) {
8474
+ this.splitAtAwait(statement, awaited, scope);
8475
+ continue;
8476
+ }
7889
8477
  const blocking = this.blockingDeclarations(statement);
7890
8478
  if (blocking?.awaited) {
7891
- this.raw(this.patch.slice(statement.start, statement.end), statement.start);
8479
+ if (!started.has(statement)) this.raw(this.patch.slice(statement.start, statement.end), statement.start);
7892
8480
  run.push(...blocking.declarations);
7893
8481
  continue;
7894
8482
  }
8483
+ if (this.options.mode === "server" && this.isQuiet(statement)) continue;
7895
8484
  endRun();
7896
8485
  if (blocking) {
7897
8486
  this.raw(this.patch.slice(statement.start, statement.end), statement.start);
@@ -7921,12 +8510,126 @@ var Emitter = class {
7921
8510
  if (this.isServerStatement(statement)) continue;
7922
8511
  if (!this.options.functions && this.isFunctionStatement(statement)) continue;
7923
8512
  }
7924
- this.raw(this.patch.slice(statement.start, statement.end), statement.start);
7925
- if (this.options.mode === "client" && statement.type === "VariableDeclaration") this.watchUnreadMemos(statement, scope);
8513
+ let code = this.patch.slice(statement.start, statement.end);
8514
+ if (index < lastAwait && statement.type === "VariableDeclaration") {
8515
+ if (statement.kind === "const") code = `let${this.patch.slice(statement.start + 5, statement.end)}`;
8516
+ for (const declaration of scope.declarations.values()) if (declaration.range.start >= statement.start && declaration.range.end <= statement.end) this.reassignable.add(declaration);
8517
+ }
8518
+ this.raw(code, statement.start);
8519
+ if (this.options.mode === "client" && statement.type === "VariableDeclaration") this.watchUnreadMemos(statement, scope, splits);
7926
8520
  }
7927
8521
  endRun();
7928
8522
  }
7929
8523
  /**
8524
+ * Emits a body that renders inline, in the function of the markup around it. In the browser,
8525
+ * a body that waits at `await` renders through a function of its own, which can split.
8526
+ */
8527
+ emitInlineBody(body) {
8528
+ const own = this.plan.bodyScopes.get(body);
8529
+ if (this.options.mode !== "client" || !this.options.hoist || !this.splitsScript(body, own, own)) {
8530
+ this.emitBody(body);
8531
+ return;
8532
+ }
8533
+ const fn = this.bodyFunction("", () => this.emitBody(body), own);
8534
+ this.code(`$$b.nodes($$b.branchNodes(undefined, undefined, 0, [${fn}]))`);
8535
+ }
8536
+ /** True when the script of a body splits its render function at `await $memo`. */
8537
+ splitsScript(body, scope, splitScope = this.splitScope) {
8538
+ if (this.options.mode !== "client" || scope !== splitScope) return false;
8539
+ for (const statement of body.script?.program.body ?? []) if (this.awaitedMemos(statement, scope)) return true;
8540
+ return this.markupAwaits(scope).length > 0;
8541
+ }
8542
+ /** The memos that the markup of a scope awaits, which no split before it waited for. */
8543
+ markupAwaits(scope) {
8544
+ const result = [];
8545
+ for (const site of this.plan.graph.model.sites) {
8546
+ if (site.scope !== scope || !MARKUP_SITES.has(site.kind)) continue;
8547
+ for (const read of site.reads) {
8548
+ const declaration = read.declaration;
8549
+ if (read.await && isMemo(declaration) && !this.splitMemos.has(declaration) && !result.includes(declaration)) result.push(declaration);
8550
+ }
8551
+ }
8552
+ return result;
8553
+ }
8554
+ /**
8555
+ * In the browser, markup that reads a memo with `await` waits for it at the start of the
8556
+ * markup, after the script, as the server waits for the memos that a `#loading` body reads at
8557
+ * its start. A memo of the scope is assigned its value. One of a scope around it is a constant
8558
+ * of the rest, with the value, since the scope that waits holds it after its slots.
8559
+ */
8560
+ awaitMarkup(scope, end) {
8561
+ if (this.options.mode !== "client" || scope !== this.splitScope) return;
8562
+ const slots = this.plan.scopes.get(scope)?.slots ?? [];
8563
+ for (const declaration of this.markupAwaits(scope)) {
8564
+ const own = declaration.scope === scope;
8565
+ let at = own ? slots.indexOf(declaration) : -1;
8566
+ if (at === -1) at = slots.length;
8567
+ const values = [];
8568
+ const names = [];
8569
+ for (const [slot, declared] of slots.entries()) {
8570
+ const before = declared.range.start < end;
8571
+ values[slot] = before ? declared.name : "";
8572
+ names[slot] = before && this.reassignable.has(declared) ? declared.name : "";
8573
+ }
8574
+ values[at] = declaration.name;
8575
+ names[at] = own ? declaration.name : "";
8576
+ while (values.at(-1) === "") values.pop();
8577
+ while (names.at(-1) === "") names.pop();
8578
+ this.openRest(`return $$b.wait(${this.scopeVar(scope)}, [${values.join(", ")}], ${at}, ($$v) => {`);
8579
+ if (names.length > 0) this.line(`[${names.join(", ")}] = $$v;`);
8580
+ if (!own) this.line(`const [${",".repeat(at)}${declaration.name}] = $$v;`);
8581
+ this.splitMemos.add(declaration);
8582
+ }
8583
+ }
8584
+ /** The awaited memos that the declarators of a statement declare, by declarator. */
8585
+ awaitedMemos(statement, scope) {
8586
+ if (statement.type !== "VariableDeclaration") return;
8587
+ const awaited = [];
8588
+ let any = false;
8589
+ for (const declarator of statement.declarations) {
8590
+ const declaration = declarator.init?.type === "AwaitExpression" && declarator.id.type === "Identifier" ? scope.declarations.get(declarator.id.name) : void 0;
8591
+ const found = declaration && isMemo(declaration) && declaration.awaited ? declaration : void 0;
8592
+ awaited.push(found);
8593
+ any ||= found !== void 0;
8594
+ }
8595
+ return any ? awaited : void 0;
8596
+ }
8597
+ /**
8598
+ * In the render module, a declaration of `await $memo(...)` ends the code that runs now: the
8599
+ * rest of the render goes in `$$b.wait`, which gets the slots that the code so far set, with
8600
+ * the load at the slot of the memo. The memo is a `let` before the call, so a function
8601
+ * declared before the `await` reads it, and the rest assigns it and the slots that can change
8602
+ * during the wait, such as props.
8603
+ */
8604
+ splitAtAwait(statement, awaited, scope) {
8605
+ const slots = this.plan.scopes.get(scope)?.slots ?? [];
8606
+ for (const [index, declarator] of statement.declarations.entries()) {
8607
+ const declaration = awaited[index];
8608
+ if (!declaration) {
8609
+ this.line(`${statement.kind} ${this.source(declarator)};`);
8610
+ continue;
8611
+ }
8612
+ let at = slots.indexOf(declaration);
8613
+ if (at === -1) at = slots.length;
8614
+ const values = [];
8615
+ const names = [];
8616
+ for (const [slot, declared] of slots.entries()) {
8617
+ const before = declared.range.start < declarator.start;
8618
+ values[slot] = before ? declared.name : "";
8619
+ names[slot] = before && this.reassignable.has(declared) ? declared.name : "";
8620
+ }
8621
+ values[at] = this.startedMemos.has(declaration) ? `$$w_${declaration.name}` : this.source(declarator.init);
8622
+ names[at] = declaration.name;
8623
+ while (values.at(-1) === "") values.pop();
8624
+ while (names.at(-1) === "") names.pop();
8625
+ this.line(`let ${declaration.name};`);
8626
+ this.openRest(`return $$b.wait(${this.scopeVar(scope)}, [${values.join(", ")}], ${at}, ($$v) => {`);
8627
+ this.line(`[${names.join(", ")}] = $$v;`);
8628
+ this.reassignable.add(declaration);
8629
+ this.splitMemos.add(declaration);
8630
+ }
8631
+ }
8632
+ /**
7930
8633
  * In the browser, a memo that nothing reads has no slot, so no load takes its promise. Its
7931
8634
  * rejection goes to the nearest `#try`, which is where a memo that throws sends its error. A
7932
8635
  * memo that always gives a primitive, such as `count * 2`, is never a promise, unless it has
@@ -7934,10 +8637,11 @@ var Emitter = class {
7934
8637
  * the read is the whole value of another memo, as in `$memo(await memo)`, which then holds the
7935
8638
  * same promise.
7936
8639
  */
7937
- watchUnreadMemos(statement, scope) {
8640
+ watchUnreadMemos(statement, scope, splits) {
8641
+ const awaited = splits ? this.markupAwaits(scope) : [];
7938
8642
  for (const declarator of statement.declarations) {
7939
8643
  const declaration = declarator.id.type === "Identifier" ? scope.declarations.get(declarator.id.name) : void 0;
7940
- if (declaration && (declaration.kind === "memo" || declaration.kind === "async-memo") && declaration.reads.every((read) => read.await && (read.site.kind !== "memo" || read.site.node.start !== read.await.start || read.site.node.end !== read.await.end)) && slotIndex(this.plan, declaration) === -1 && !isNeverPromise(declaration)) {
8644
+ if (declaration && !awaited.includes(declaration) && (declaration.kind === "memo" || declaration.kind === "async-memo") && declaration.reads.every((read) => read.await && (read.site.kind !== "memo" || read.site.node.start !== read.await.start || read.site.node.end !== read.await.end)) && slotIndex(this.plan, declaration) === -1 && !isNeverPromise(declaration)) {
7941
8645
  const target = this.scopeVar(instanceScope(this.plan, scope));
7942
8646
  this.line(`$$b.unreadMemo(${target}, ${declaration.name});`);
7943
8647
  }
@@ -8050,6 +8754,7 @@ var Emitter = class {
8050
8754
  else this.code(`${this.helper("style")}(${JSON.stringify(this.plan.id)}, $$css)`);
8051
8755
  }
8052
8756
  this.emitStatements(setup, component);
8757
+ this.awaitMarkup(component, this.file.instanceScript?.program.end ?? 0);
8053
8758
  this.emitBound(component);
8054
8759
  for (const template of this.file.templates) this.emitTemplate(template);
8055
8760
  this.emitClientAnchors(component);
@@ -8057,11 +8762,16 @@ var Emitter = class {
8057
8762
  this.emitSlots(component);
8058
8763
  this.flush();
8059
8764
  }
8060
- /** Emits a body: its scope, script, templates, markup and slots. */
8061
- emitBody(body, createScope = true) {
8765
+ /**
8766
+ * Emits a body: its scope, script, templates, markup and slots. `markup` writes what goes
8767
+ * before the markup, after the script.
8768
+ */
8769
+ emitBody(body, createScope = true, markup) {
8062
8770
  const scope = this.plan.bodyScopes.get(body);
8063
- if (this.plan.scopes.get(scope).needsId && createScope) this.createScope(scope);
8771
+ if ((this.plan.scopes.get(scope).needsId || this.splitsScript(body, scope)) && createScope) this.createScope(scope);
8064
8772
  if (body.script) this.emitStatements(body.script.program.body, scope);
8773
+ this.awaitMarkup(scope, body.script?.program.end ?? body.start);
8774
+ markup?.();
8065
8775
  for (const template of body.templates) this.emitTemplate(template);
8066
8776
  this.emitClientAnchors(scope);
8067
8777
  this.emitNodes(body.children, scope);
@@ -8099,17 +8809,21 @@ var Emitter = class {
8099
8809
  const anchored = this.plan.anchors.has(block) && !this.plan.elementItems.has(block);
8100
8810
  if (block.kind === "for") this.line(`const ${copy(this.file.source, block.item.start, block.item.end)} = ${item};`);
8101
8811
  if (block.index) this.line(`const ${block.index.name} = ${index};`);
8102
- if (this.plan.scopes.get(scope).needsId) this.createScope(scope);
8103
- if (anchored) {
8104
- this.html("<!--i");
8105
- this.code(this.scopeVar(scope));
8106
- this.html("-->");
8107
- }
8108
- this.emitBody(block.body, false);
8109
- if (this.plan.anchors.has(block)) {
8110
- const from = source ? `, ${source}` : "";
8111
- this.line(`${this.helper("item")}(${this.scopeVar(scope)}, ${item}${from});`);
8112
- }
8812
+ const splits = this.splitsScript(block.body, scope);
8813
+ if (this.plan.scopes.get(scope).needsId || splits) this.createScope(scope);
8814
+ const from = source ? `, ${source}` : "";
8815
+ const setItem = `${this.helper("item")}(${this.scopeVar(scope)}, ${item}${from});`;
8816
+ if (splits && this.plan.anchors.has(block)) this.line(setItem);
8817
+ const open = () => {
8818
+ if (anchored) {
8819
+ this.html("<!--i");
8820
+ this.code(this.scopeVar(scope));
8821
+ this.html("-->");
8822
+ }
8823
+ };
8824
+ if (!splits) open();
8825
+ this.emitBody(block.body, false, splits ? open : void 0);
8826
+ if (this.plan.anchors.has(block) && !splits) this.line(setItem);
8113
8827
  if (anchored) this.html("<!--/i-->");
8114
8828
  }
8115
8829
  emitTemplate(template) {
@@ -8154,7 +8868,8 @@ var Emitter = class {
8154
8868
  const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${this.expression(node.expression)})` : this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
8155
8869
  const text = literalText(node.expression.ast);
8156
8870
  const settled = this.settledMemos([node.expression], scope);
8157
- const emitValue = () => text === void 0 ? this.code(value, settled) : this.html(text);
8871
+ const promise = this.promiseScope(node.expression, scope);
8872
+ const emitValue = () => text === void 0 ? this.code(value, settled, promise) : this.html(text);
8158
8873
  if (anchor && !this.plan.contents.has(node)) {
8159
8874
  this.html("<!--t");
8160
8875
  this.code(anchor.scope);
@@ -8180,6 +8895,11 @@ var Emitter = class {
8180
8895
  this.line("$$ctx.revealEnd();");
8181
8896
  return;
8182
8897
  }
8898
+ if (node.reveal && this.options.mode === "client" && mayReveal(node.children)) {
8899
+ const body = this.bodyFunction("", () => this.emitNodes(node.children, scope));
8900
+ this.code(`$$b.nodes($$b.reveal(${JSON.stringify(node.reveal.order)}, ${node.reveal.collapsed}, ${body}))`);
8901
+ return;
8902
+ }
8183
8903
  this.emitNodes(node.children, scope);
8184
8904
  return;
8185
8905
  case "listener": {
@@ -8369,16 +9089,17 @@ var Emitter = class {
8369
9089
  this.emitClasses(classes);
8370
9090
  break;
8371
9091
  }
8372
- this.code(`$$b.attribute(${JSON.stringify(attribute.name)}, ${this.expression(attribute.value)})`, this.settledMemos([attribute.value], scope));
9092
+ const call = `$$b.attribute(${JSON.stringify(attribute.name)}, ${this.expression(attribute.value)})`;
9093
+ this.code(isPrimitive(attribute.value.ast) ? call : this.ready(call), this.settledMemos([attribute.value], scope), this.promiseScope(attribute.value, scope));
8373
9094
  const bound = this.bindEntry(node, attribute, scope);
8374
9095
  if (bound) events.unshift(bound);
8375
9096
  break;
8376
9097
  }
8377
9098
  case "spread":
8378
- this.code(`$$b.spread(${this.expression(attribute.value)}${spreadArguments(spreadHandlers)})`);
9099
+ this.code(this.ready(`$$b.spread(${this.expression(attribute.value)}${spreadArguments(spreadHandlers)})`), void 0, this.promiseScope(attribute.value, scope));
8379
9100
  break;
8380
9101
  case "computed":
8381
- this.code(`$$b.attribute(${this.expression(attribute.name)}, ${attribute.value === true ? "true" : this.expression(attribute.value)})`);
9102
+ this.code(this.ready(`$$b.attribute(${this.expression(attribute.name)}, ${attribute.value === true ? "true" : this.expression(attribute.value)})`));
8382
9103
  break;
8383
9104
  case "event":
8384
9105
  events.push(this.eventEntry(attribute));
@@ -8389,7 +9110,9 @@ var Emitter = class {
8389
9110
  if (merged) {
8390
9111
  const forwards = anchor !== void 0 && this.spreadsRest(node.attributes);
8391
9112
  const attributes = `$$b.mergeAttributes([${merged.join(", ")}]${variables ? `, ${variables}` : ""})`;
8392
- this.code(`$$b.spread(${forwards ? `${this.helper("restRef")}(${attributes}, ${anchor.scope}, ${anchor.index})` : attributes}${spreadArguments(spreadHandlers)})`);
9113
+ let promise;
9114
+ for (const attribute of node.attributes) if (attribute.kind === "value" || attribute.kind === "spread") promise ??= this.promiseScope(attribute.value, scope);
9115
+ this.code(this.ready(`$$b.spread(${forwards ? `${this.helper("restRef")}(${attributes}, ${anchor.scope}, ${anchor.index})` : attributes}${spreadArguments(spreadHandlers)})`), void 0, promise);
8393
9116
  }
8394
9117
  if (anchor && !spreadHandlers) {
8395
9118
  this.html(" b-b=\"");
@@ -8752,7 +9475,7 @@ var Emitter = class {
8752
9475
  const inPlace = !mayWait(this.plan, block.body.children);
8753
9476
  if (inPlace && memos.length === 0) {
8754
9477
  this.line("$$ctx.enter();");
8755
- this.emitBody(block.body);
9478
+ this.emitLoadingBody(block, scope);
8756
9479
  this.line("$$ctx.leave();");
8757
9480
  return;
8758
9481
  }
@@ -8761,11 +9484,10 @@ var Emitter = class {
8761
9484
  this.line(`if ($$b.settled([${names.join(", ")}]) && $$ctx.mayShow()) {`);
8762
9485
  this.line(`$$ctx.enter(${boundary});`);
8763
9486
  for (const declaration of memos) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
8764
- this.emitBody(block.body);
9487
+ this.emitLoadingBody(block, scope);
8765
9488
  this.line("$$ctx.leave();");
8766
9489
  this.close("} else {");
8767
9490
  }
8768
- this.open(scope, block);
8769
9491
  this.html("<!--l");
8770
9492
  this.code(boundary);
8771
9493
  this.html("-->");
@@ -8777,17 +9499,43 @@ var Emitter = class {
8777
9499
  this.code(`$$ctx.fallbackEnd(${boundary})`);
8778
9500
  }
8779
9501
  this.html("<!--/l-->");
8780
- this.end(block);
8781
9502
  this.line(`$$ctx.defer(${boundary}, async ($$ctx) => {`);
8782
9503
  this.line(`let $$html = '';`);
8783
9504
  for (const declaration of memos) this.awaitHeld(declaration);
8784
- this.emitBody(block.body);
9505
+ this.emitLoadingBody(block, scope);
8785
9506
  this.flush();
8786
9507
  this.line("return $$html;");
8787
9508
  this.close("});");
8788
9509
  if (inPlace) this.close();
8789
9510
  }
8790
9511
  /**
9512
+ * In the browser, a `#loading` block renders as a streamed one shows: `$$b.loading` renders the
9513
+ * body in a boundary, and the fallback while a wait of the body has not ended. The body counts
9514
+ * the memos that it reads from outside, which the server waits for in the block. The block
9515
+ * joins the `#reveal` block whose body renders it.
9516
+ */
9517
+ emitClientLoading(block, scope) {
9518
+ const body = this.plan.bodyScopes.get(block.body);
9519
+ const reads = [];
9520
+ for (const declaration of awaitedMemos(this.plan, body, this.blocking)) if (mayLoad(declaration)) reads.push(declaration.name);
9521
+ const args = [this.bodyFunction("", () => {
9522
+ if (reads.length > 0) this.line(`$$b.countLoads(${this.scopeVar(instanceScope(this.plan, scope))}, [${reads.join(", ")}]);`);
9523
+ this.emitLoadingBody(block, scope);
9524
+ }, body)];
9525
+ const fallback = block.fallback;
9526
+ if (fallback) args.push(this.bodyFunction("", () => this.emitBody(fallback), this.plan.bodyScopes.get(fallback)));
9527
+ this.code(`$$b.nodes($$b.loading(${args.join(", ")}))`);
9528
+ }
9529
+ /**
9530
+ * The body of a `#loading` block. With a header, its markers carry the scope and the anchor of
9531
+ * the block, so the browser finds the body to hide while a memo of the header loads.
9532
+ */
9533
+ emitLoadingBody(block, scope) {
9534
+ this.open(scope, block, "1");
9535
+ this.emitBody(block.body);
9536
+ this.end(block);
9537
+ }
9538
+ /**
8791
9539
  * Registers the `#catch` body of a `#try` on the server, and returns the name of the function
8792
9540
  * that ends the registration. The body renders again here for an error that comes after the
8793
9541
  * page is sent, in a context of its own.
@@ -8869,15 +9617,16 @@ var Emitter = class {
8869
9617
  * Emits a function that renders a body, as a constant, and returns its name. The function
8870
9618
  * clones its markup when it can, and gives its HTML otherwise.
8871
9619
  */
8872
- bodyFunction(params, content) {
9620
+ bodyFunction(params, content, scope) {
8873
9621
  const name = this.unique("body");
8874
9622
  this.line(`const ${name} = (${params}) => {`);
8875
9623
  const fn = this.currentFn;
8876
9624
  this.line(`let $$html = '';`);
8877
- content();
8878
- this.flush();
8879
- const cloned = cloneLines(this, this.options.hoist, fn);
8880
- this.line(this.returnLine(fn, cloned));
9625
+ this.splitBody(scope, content, () => {
9626
+ this.flush();
9627
+ const cloned = this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn);
9628
+ this.line(this.returnLine(fn, cloned));
9629
+ });
8881
9630
  this.close("};");
8882
9631
  return name;
8883
9632
  }
@@ -8893,9 +9642,9 @@ var Emitter = class {
8893
9642
  if (block.kind === "if" || block.kind === "switch") {
8894
9643
  const branches = block.kind === "if" ? block.branches : block.cases;
8895
9644
  const bodies = [];
8896
- for (const branch of branches) bodies.push(this.bodyFunction("", () => this.emitBody(branch.body)));
9645
+ for (const branch of branches) bodies.push(this.bodyFunction("", () => this.emitBody(branch.body), this.plan.bodyScopes.get(branch.body)));
8897
9646
  const fallback = block.fallback;
8898
- const other = fallback && this.bodyFunction("", () => this.emitBody(fallback));
9647
+ const other = fallback && this.bodyFunction("", () => this.emitBody(fallback), this.plan.bodyScopes.get(fallback));
8899
9648
  let index = other ? String(branches.length) : "-1";
8900
9649
  for (let at = branches.length - 1; at >= 0; at--) index = `${this.expression(branches[at].condition)} ? ${at} : ${index}`;
8901
9650
  const names = `[${[...bodies, ...other ? [other] : []].join(", ")}]`;
@@ -8907,9 +9656,9 @@ var Emitter = class {
8907
9656
  if (block.kind === "for" || block.kind === "repeat") {
8908
9657
  const item = this.unique("item");
8909
9658
  const index = this.unique("index");
8910
- const body = this.bodyFunction(`${item}, ${index}`, () => this.emitItem(block, item, index));
9659
+ const body = this.bodyFunction(`${item}, ${index}`, () => this.emitItem(block, item, index), this.plan.bodyScopes.get(block.body));
8911
9660
  const fallback = block.fallback;
8912
- const other = fallback && this.bodyFunction("", () => this.emitBody(fallback));
9661
+ const other = fallback && this.bodyFunction("", () => this.emitBody(fallback), this.plan.bodyScopes.get(fallback));
8913
9662
  const items = block.kind === "for" ? `$$b.toList(${this.expression(block.list)})` : `Array.from({ length: ${this.expression(block.count)} }, (_, index) => index)`;
8914
9663
  this.code(`$$b.nodes($$b.listNodes(${marks}, ${items}, ${body}, ${other ?? "undefined"}))`, this.settledMemos([block.kind === "for" ? block.list : block.count], scope));
8915
9664
  return true;
@@ -9026,7 +9775,10 @@ var Emitter = class {
9026
9775
  if (mark) this.line(`const ${mark} = $$ctx.mark();`);
9027
9776
  const end = server ? this.emitCatcher(block, scope) : void 0;
9028
9777
  this.line("try {");
9029
- this.emitBody(block.body);
9778
+ if (!server && this.options.hoist && this.plan.anchors.has(block) && tryCatchesClient(this.plan.graph.model, block)) {
9779
+ const fn = this.bodyFunction("", () => this.emitBody(block.body), this.plan.bodyScopes.get(block.body));
9780
+ this.code(`$$b.nodes($$b.attempt(${fn}))`);
9781
+ } else this.emitInlineBody(block.body);
9030
9782
  this.close(`} catch (${error}) {`);
9031
9783
  this.line(`$$html = ${before};`);
9032
9784
  if (mark) this.line(`$$ctx.restore(${mark});`);
@@ -9072,11 +9824,7 @@ var Emitter = class {
9072
9824
  this.emitLoading(block, scope);
9073
9825
  return;
9074
9826
  }
9075
- this.open(scope, block);
9076
- this.line("{");
9077
- this.emitBody(block.body);
9078
- this.close();
9079
- this.end(block);
9827
+ this.emitClientLoading(block, scope);
9080
9828
  return;
9081
9829
  case "portal":
9082
9830
  case "head":
@@ -9095,7 +9843,7 @@ var Emitter = class {
9095
9843
  default:
9096
9844
  this.open(scope, block);
9097
9845
  this.line("{");
9098
- this.emitBody(block.body);
9846
+ this.emitInlineBody(block.body);
9099
9847
  this.close();
9100
9848
  this.end(block);
9101
9849
  }
@@ -9498,7 +10246,8 @@ function generateRender(file, plan, getFill) {
9498
10246
  mode: "client",
9499
10247
  functions: true,
9500
10248
  fills: fill ? fills : void 0,
9501
- hoist
10249
+ hoist,
10250
+ waits: true
9502
10251
  });
9503
10252
  emitter.line(signature);
9504
10253
  emitter.line(`let $$html = '';`);
@@ -9507,6 +10256,7 @@ function generateRender(file, plan, getFill) {
9507
10256
  emitter.flush();
9508
10257
  const cloned = cloneLines(emitter, hoist);
9509
10258
  emitter.line(emitter.returnLine(0, cloned));
10259
+ for (let wait = 0; wait < emitter.waits; wait++) emitter.close("});");
9510
10260
  emitter.close();
9511
10261
  return {
9512
10262
  emitter,
@@ -9895,19 +10645,6 @@ const BROWSER_ONLY_SITES = /* @__PURE__ */ new Set([
9895
10645
  "effect",
9896
10646
  "client"
9897
10647
  ]);
9898
- /** Declarations that a handler reads or writes that can reach other components. */
9899
- const OUTER = /* @__PURE__ */ new Set([
9900
- "import",
9901
- "module",
9902
- "prop",
9903
- "props-rest",
9904
- "context",
9905
- "template",
9906
- "template-param",
9907
- "action",
9908
- "error",
9909
- "reset"
9910
- ]);
9911
10648
  const DEFERRED_SITES = /* @__PURE__ */ new Set([
9912
10649
  "function",
9913
10650
  "server-function",
@@ -9950,8 +10687,6 @@ var ClientGenerator = class {
9950
10687
  live = /* @__PURE__ */ new Map();
9951
10688
  /** The export that updates each live node. */
9952
10689
  updates = /* @__PURE__ */ new Map();
9953
- /** The handlers that can write a slot of another component. */
9954
- wide = [];
9955
10690
  /** Bodies that the client renders, by scope. */
9956
10691
  renders = /* @__PURE__ */ new Map();
9957
10692
  merge;
@@ -10045,7 +10780,6 @@ var ClientGenerator = class {
10045
10780
  `export const id = ${JSON.stringify(this.plan.id)};`,
10046
10781
  `export const props = ${this.propsMap()};`,
10047
10782
  `export const g = ${this.table()};`,
10048
- ...this.wide.length > 0 ? [`export const w = ${JSON.stringify(this.wide)};`] : [],
10049
10783
  ...refresh ? [`export const refresh = ${refresh};`] : [],
10050
10784
  ...tries ? [`export const t = ${tries};`] : []
10051
10785
  ];
@@ -10061,8 +10795,6 @@ var ClientGenerator = class {
10061
10795
  if (merged || names.length === 0) {
10062
10796
  const code = parts.all ?? "";
10063
10797
  delete parts.all;
10064
- const empty = {};
10065
- for (const name of names) empty[name] = [];
10066
10798
  return {
10067
10799
  code: [
10068
10800
  code,
@@ -10072,14 +10804,11 @@ var ClientGenerator = class {
10072
10804
  ].join("\n"),
10073
10805
  table: table.join("\n"),
10074
10806
  parts,
10075
- loaders: empty,
10076
10807
  clientCode,
10077
10808
  fillOf: (block) => this.createFill(block),
10078
10809
  diagnostics: this.diagnostics
10079
10810
  };
10080
10811
  }
10081
- const loaders = {};
10082
- for (const name of names) loaders[name] = [name];
10083
10812
  const reexports = [];
10084
10813
  for (const name of names) reexports.push(`export * from ${JSON.stringify(this.partPath(name))};`);
10085
10814
  return {
@@ -10091,7 +10820,6 @@ var ClientGenerator = class {
10091
10820
  ].join("\n"),
10092
10821
  table: table.join("\n"),
10093
10822
  parts,
10094
- loaders,
10095
10823
  clientCode,
10096
10824
  fillOf: (block) => this.createFill(block),
10097
10825
  diagnostics: this.diagnostics
@@ -10429,26 +11157,12 @@ var ClientGenerator = class {
10429
11157
  let code = this.withTemplates(site, this.rewriter.rewrite(site, "$$s", base));
10430
11158
  if (site.node.type === "FunctionExpression" && unmarked(code).trimStart().startsWith("(")) code = `function ${code}`;
10431
11159
  this.part = symbol;
10432
- if (site.kind !== "client" && !symbol.startsWith("t") && !this.writesOwn(site)) this.wide.push(symbol);
10433
11160
  if (symbol.startsWith("t")) this.emitTemplateArgs(site, symbol);
10434
11161
  if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.effect($$s, ${JSON.stringify(symbol)}, ${code}, 1);\n}`);
10435
11162
  else this.emit(this.handlerExport(site, symbol, code, base));
10436
11163
  }
10437
11164
  }
10438
11165
  /**
10439
- * True when a handler can write only the slots of its own component, so it waits for the
10440
- * update code of that component and not for the code of the components above it. The others
10441
- * are listed in `w`. A prop, a context, an import or a template can reach another component.
10442
- */
10443
- writesOwn(site, seen = /* @__PURE__ */ new Set()) {
10444
- if (seen.has(site)) return true;
10445
- seen.add(site);
10446
- for (let scope = site.scope; scope; scope = scope.parent) if (scope.kind === "template") return false;
10447
- for (const { declaration } of [...site.reads, ...site.writes]) if (OUTER.has(declaration.kind) && declaration.imported?.source !== "brumate/events") return false;
10448
- for (const callee of site.calls) if (!callee.site || !this.writesOwn(callee.site, seen)) return false;
10449
- return true;
10450
- }
10451
- /**
10452
11166
  * The export of a handler, which the core calls with the scope and the
10453
11167
  * arguments. A local function already takes them, so it is exported as it
10454
11168
  * is. An arrow function gets the scope as its first parameter.
@@ -10536,7 +11250,8 @@ var ClientGenerator = class {
10536
11250
  let fn = "text";
10537
11251
  if (this.plan.textContents.has(insert)) fn = "writeText";
10538
11252
  else if (this.plan.contents.has(insert)) fn = "content";
10539
- this.emit(`export function ${name("u")}($$s) {\n $$b.${fn}($$s, ${anchor}, ${expression()});\n}`);
11253
+ const write = fn !== "writeText" && mayBePromise(site.node, site) ? `$$b.fillValue($$s, ${anchor}, ${expression()}, ($$v) => $$b.${fn}($$s, ${anchor}, $$v))` : `$$b.${fn}($$s, ${anchor}, ${expression()})`;
11254
+ this.emit(`export function ${name("u")}($$s) {\n ${write};\n}`);
10540
11255
  }
10541
11256
  return;
10542
11257
  }
@@ -10603,7 +11318,8 @@ var ClientGenerator = class {
10603
11318
  const events = owner.kind === "dynamic" ? this.ownEvents(owner) : [];
10604
11319
  if (events.length > 0) parts.push(`{ "b-on": $$b.internal(${events.join(" + \" \" + ")}) }`);
10605
11320
  const value = parts.length > 1 ? `$$b.mergeAttributes([${parts.join(", ")}])` : parts[0] ?? "{}";
10606
- this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${value}, ${JSON.stringify(own)});\n}`);
11321
+ const helper = mayBePromise(site.node, site) ? "fillAttrs" : "attrs";
11322
+ this.emit(`export function ${name("u")}($$s) {\n $$b.${helper}($$s, ${anchor}, ${value}, ${JSON.stringify(own)});\n}`);
10607
11323
  } else if (attribute.kind === "value") {
10608
11324
  let value = (attribute.name === "class" ? classes(attribute.value.ast) : void 0) ?? expression();
10609
11325
  if (attribute.name === "class") {
@@ -10614,7 +11330,8 @@ var ClientGenerator = class {
10614
11330
  value = `[${classed.join(", ")}]`;
10615
11331
  }
10616
11332
  }
10617
- this.emit(`export function ${name("u")}($$s) {\n $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value});\n}`);
11333
+ const write = mayBePromise(attribute.value.ast, site) ? `$$b.fillValue($$s, ${JSON.stringify(`${anchor} ${attribute.name}`)}, ${value}, ($$v) => $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, $$v))` : `$$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value})`;
11334
+ this.emit(`export function ${name("u")}($$s) {\n ${write};\n}`);
10618
11335
  }
10619
11336
  }
10620
11337
  /** The `b-on` entries of the handlers of a dynamic tag, each as code that adds the scope ID. */
@@ -10777,6 +11494,23 @@ var ClientGenerator = class {
10777
11494
  case "offscreen":
10778
11495
  this.emit(`export function ${fn}($$s) {\n $$b.offscreen($$s, ${anchor}, ${header(0)}, ${this.renderName(block.body)}, ${this.plan.bodyScopes.get(block.body).id}${held});\n}`);
10779
11496
  return;
11497
+ case "loading": {
11498
+ const checks = [];
11499
+ const seen = /* @__PURE__ */ new Set();
11500
+ for (const read of headers[0]?.reads ?? []) {
11501
+ const slot = slotIndex(this.plan, read.declaration);
11502
+ if (slot !== -1 && !seen.has(read.declaration)) {
11503
+ seen.add(read.declaration);
11504
+ checks.push(`$$b.pending(${scopePath(this.plan, "$$s", base, read.declaration.scope)}, ${slot})`);
11505
+ }
11506
+ }
11507
+ if (checks.length === 0) return;
11508
+ const fallback = block.fallback;
11509
+ const render = fallback ? this.renderName(fallback) : "undefined";
11510
+ const kinds = this.hoist(`[${fallback ? this.kinds([fallback]).join(", ") : ""}]`);
11511
+ this.emit(`export function ${fn}($$s) {\n $$b.held($$s, ${anchor}, ${checks.join(" || ")}, ${this.plan.bodyScopes.get(block.body).id}, ${render}, ${kinds}${held});\n}`);
11512
+ return;
11513
+ }
10780
11514
  case "key": {
10781
11515
  const [inner] = block.body.children;
10782
11516
  const helper = inner?.kind === "dynamic" && inner.keyed ? "retag" : "rekey";
@@ -10820,6 +11554,14 @@ var ClientGenerator = class {
10820
11554
  collectRenders() {
10821
11555
  for (const node of this.plan.graph.nodes) {
10822
11556
  if (node.kind !== "block" || !this.plan.graph.live.has(node) || node.site.label === "for key") continue;
11557
+ if (node.block.kind === "loading") {
11558
+ const fallback = node.block.fallback;
11559
+ if (fallback) this.renders.set(this.plan.bodyScopes.get(fallback), {
11560
+ body: fallback,
11561
+ block: node.block
11562
+ });
11563
+ continue;
11564
+ }
10823
11565
  if (![
10824
11566
  "if",
10825
11567
  "switch",
@@ -10879,12 +11621,16 @@ var ClientGenerator = class {
10879
11621
  }
10880
11622
  for (const line of this.prologue(inside, base)) emitter.line(line);
10881
11623
  for (const template of this.declared(inside).slice(1)) emitter.emitTemplate(template.template);
10882
- if (isItem) emitter.emitItem(block, "$$item", "$$index");
10883
- else emitter.emitBody(body);
10884
- emitter.flush();
10885
- const cloned = block.kind === "if" || block.kind === "for" ? this.cloneRender(emitter) : false;
11624
+ let cloned = false;
11625
+ emitter.splitBody(scope, () => {
11626
+ if (isItem) emitter.emitItem(block, "$$item", "$$index");
11627
+ else emitter.emitBody(body);
11628
+ }, () => {
11629
+ emitter.flush();
11630
+ cloned = block.kind === "if" || block.kind === "for" || block.kind === "loading" ? this.cloneRender(emitter) : false;
11631
+ emitter.line(emitter.returnLine(0, cloned));
11632
+ });
10886
11633
  if (fill && !cloned) return;
10887
- emitter.line(emitter.returnLine(0, cloned));
10888
11634
  emitter.close();
10889
11635
  return emitter.lines.join("\n");
10890
11636
  }
@@ -11425,7 +12171,6 @@ function compile(source, options = {}) {
11425
12171
  server: server.code,
11426
12172
  client: entry.code,
11427
12173
  parts: partCodes,
11428
- loaders: client.loaders,
11429
12174
  table: client.table,
11430
12175
  clientCode: client.clientCode,
11431
12176
  render: render.code,
@@ -11642,4 +12387,4 @@ function inspect(source, options = {}) {
11642
12387
  //#endregion
11643
12388
  export { analyzeProject as A, getLocation as B, isReactiveModule as C, unmarked as D, originalPosition as E, summarize as F, isWithin as G, findError as H, parse$1 as I, walk as J, lookup as K, buildGraph as L, importSource as M, importedComponents as N, entryClasses as O, resolveRelative as P, forEachNode as R, sharedSites as S, builtin as T, analyze$1 as U, errorLink as V, getPatternNames as W, 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, resolveMacros as q, inspect as r, compile as s, anchorLabel as t, generateRender as u, getComponentName as v, resolveFromDisk as w, generateShared as x, hash as y, BrumateError as z };
11644
12389
 
11645
- //# sourceMappingURL=inspect-BvPTZs6k.js.map
12390
+ //# sourceMappingURL=inspect-B8i6R3mZ.js.map