brumate 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/{boot-Difa0qdg.d.ts → boot-DkbcqdUz.d.ts} +2 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/{client-De-7aGlO.js → client-C3vRNuLi.js} +353 -103
  4. package/dist/client-C3vRNuLi.js.map +1 -0
  5. package/dist/{client-DvsU9qxG.d.ts → client-CqGDbWd_.d.ts} +45 -8
  6. package/dist/{defer-DlFYiAuK.js → defer-M18UKyfG.js} +2 -2
  7. package/dist/{defer-DlFYiAuK.js.map → defer-M18UKyfG.js.map} +1 -1
  8. package/dist/{devtools-Di_dI9tS.js → devtools-YnvrZ6D8.js} +4 -4
  9. package/dist/{devtools-Di_dI9tS.js.map → devtools-YnvrZ6D8.js.map} +1 -1
  10. package/dist/{devtools-panel-BvIKX1LY.js → devtools-panel-DRcKclEG.js} +2 -2
  11. package/dist/{devtools-panel-BvIKX1LY.js.map → devtools-panel-DRcKclEG.js.map} +1 -1
  12. package/dist/{features-D5kLyihb.js → features-CbgII-o7.js} +4 -2
  13. package/dist/features-CbgII-o7.js.map +1 -0
  14. package/dist/{files-s4wmjcZV.js → files-HzPDUyTY.js} +2 -2
  15. package/dist/{files-s4wmjcZV.js.map → files-HzPDUyTY.js.map} +1 -1
  16. package/dist/index.d.ts +8 -4
  17. package/dist/index.js +2 -7
  18. package/dist/index.js.map +1 -1
  19. package/dist/{inspect-BLPt-dZZ.js → inspect-Q5W0A66e.js} +476 -122
  20. package/dist/inspect-Q5W0A66e.js.map +1 -0
  21. package/dist/{loader-krRrJuIv.js → loader-C-S3yzep.js} +13 -5
  22. package/dist/loader-C-S3yzep.js.map +1 -0
  23. package/dist/{navigate-BcV1qkkx.js → navigate-r23FFR6e.js} +5 -2
  24. package/dist/{navigate-BcV1qkkx.js.map → navigate-r23FFR6e.js.map} +1 -1
  25. package/dist/routes-D21FQyGF.js +51 -0
  26. package/dist/routes-D21FQyGF.js.map +1 -0
  27. package/dist/{rpc-BYYAj1vV.js → rpc-C_znDZ_w.js} +3 -3
  28. package/dist/{rpc-BYYAj1vV.js.map → rpc-C_znDZ_w.js.map} +1 -1
  29. package/dist/runtime/bundles.d.ts +1 -1
  30. package/dist/runtime/client.d.ts +2 -2
  31. package/dist/runtime/client.js +3 -3
  32. package/dist/runtime/devtools.d.ts +1 -1
  33. package/dist/runtime/devtools.js +1 -1
  34. package/dist/runtime/hot.d.ts +1 -1
  35. package/dist/runtime/loader.d.ts +2 -2
  36. package/dist/runtime/loader.js +2 -2
  37. package/dist/runtime/routes.js +1 -51
  38. package/dist/runtime/server.d.ts +2 -2
  39. package/dist/runtime/server.js +3 -3
  40. package/dist/runtime/signals.d.ts +2 -140
  41. package/dist/runtime/signals.js +4 -1
  42. package/dist/runtime/signals.js.map +1 -1
  43. package/dist/runtime/static-loader.d.ts +2 -2
  44. package/dist/runtime/static-loader.js +1 -1
  45. package/dist/runtime/testing.d.ts +24 -4
  46. package/dist/runtime/testing.js +66 -2
  47. package/dist/runtime/testing.js.map +1 -1
  48. package/dist/{produce-Cq6KKi7b.js → search-params-CM1RWR2P.js} +25 -3
  49. package/dist/search-params-CM1RWR2P.js.map +1 -0
  50. package/dist/{server-Doy5HR7r.js → server-BcT9icQ4.js} +107 -40
  51. package/dist/server-BcT9icQ4.js.map +1 -0
  52. package/dist/{server-CAwIqrXl.d.ts → server-dP_ucRiJ.d.ts} +42 -3
  53. package/dist/signals-BwD4u22K.d.ts +165 -0
  54. package/dist/{static-loader-DoHWsf9t.js → static-loader-Bt2WDkY1.js} +3 -3
  55. package/dist/{static-loader-DoHWsf9t.js.map → static-loader-Bt2WDkY1.js.map} +1 -1
  56. package/dist/{static-loader-9Nc1GvF0.d.ts → static-loader-DysAET-w.d.ts} +2 -2
  57. package/dist/{stream-BdhzvPQO.js → stream-DRjx0keF.js} +2 -2
  58. package/dist/{stream-BdhzvPQO.js.map → stream-DRjx0keF.js.map} +1 -1
  59. package/dist/vite.d.ts +1 -1
  60. package/dist/vite.js +18 -13
  61. package/dist/vite.js.map +1 -1
  62. package/elements.d.ts +239 -37
  63. package/package.json +6 -1
  64. package/skills/brumate/references/errors.md +46 -12
  65. package/skills/brumate/references/signals.md +27 -25
  66. package/skills/brumate/references/syntax.md +1 -1
  67. package/dist/client-De-7aGlO.js.map +0 -1
  68. package/dist/features-D5kLyihb.js.map +0 -1
  69. package/dist/inspect-BLPt-dZZ.js.map +0 -1
  70. package/dist/loader-krRrJuIv.js.map +0 -1
  71. package/dist/produce-Cq6KKi7b.js.map +0 -1
  72. package/dist/runtime/routes.js.map +0 -1
  73. package/dist/server-Doy5HR7r.js.map +0 -1
@@ -26,6 +26,7 @@ const MACROS = /* @__PURE__ */ new Set([
26
26
  "$setContext",
27
27
  "$getContext",
28
28
  "$route",
29
+ "$searchParam",
29
30
  "$navigation",
30
31
  "$id",
31
32
  "$title",
@@ -292,7 +293,7 @@ const REACTIVE = /* @__PURE__ */ new Set([
292
293
  /** The module of the wrappers of event handlers, which the compiler reads. */
293
294
  const EVENTS_MODULE = "brumate/events";
294
295
  /** The wrappers that `brumate/events` exports. */
295
- const WRAPPERS$2 = /* @__PURE__ */ new Set([
296
+ const WRAPPERS$3 = /* @__PURE__ */ new Set([
296
297
  "prevent",
297
298
  "stop",
298
299
  "once",
@@ -511,6 +512,7 @@ var Analyzer = class {
511
512
  this.markPromiseProps();
512
513
  for (const site of this.sites) new Resolver(this, site).run();
513
514
  this.addPendingReads();
515
+ this.addSearchParamReads();
514
516
  this.checkLoadingHeaders();
515
517
  this.resolveRefs();
516
518
  this.check();
@@ -526,6 +528,29 @@ var Analyzer = class {
526
528
  pendingCalls: this.pendingCalls
527
529
  };
528
530
  }
531
+ /**
532
+ * The effect of a `$searchParam` reads its signal, so it runs again when the signal changes.
533
+ * The range is empty, so no identifier starts there.
534
+ */
535
+ addSearchParamReads() {
536
+ for (const declaration of this.declarations) {
537
+ if (!declaration.searchParam) continue;
538
+ for (const site of this.sites) if (site.node === declaration.searchParam && site.kind === "effect") {
539
+ const read = {
540
+ range: {
541
+ start: site.node.end,
542
+ end: site.node.end
543
+ },
544
+ declaration,
545
+ site,
546
+ tracked: true,
547
+ inFunction: false
548
+ };
549
+ declaration.reads.push(read);
550
+ site.reads.push(read);
551
+ }
552
+ }
553
+ }
529
554
  /** `$isPending(memo)` calls, which also read the memos that the memo reads. */
530
555
  pendingCalls = [];
531
556
  /**
@@ -688,14 +713,9 @@ var Analyzer = class {
688
713
  /**
689
714
  * Reads the wrappers of `brumate/events` around a handler, such as
690
715
  * `prevent(move, 'Enter')`, into the modifiers that `b-on` holds, so the
691
- * loader applies them before the handler's code loads. A modifier in the
692
- * attribute name, such as `onSubmit:prevent`, still works, with a warning.
716
+ * loader applies them before the handler's code loads.
693
717
  */
694
718
  readWrappers(site, attribute, scope) {
695
- if (attribute.modifiers.length > 0) {
696
- const [first] = attribute.modifiers;
697
- this.report("warning", `${attribute.name}:${first} is replaced by ${attribute.name}=(${first === "passive" ? "handler" : `${first}(handler)`}) from brumate/events${first === "passive" ? ", since listeners are passive unless a handler prevents" : ""}`, attribute);
698
- }
699
719
  const modifiers = [];
700
720
  let node = attribute.handler.ast;
701
721
  for (;;) {
@@ -707,7 +727,7 @@ var Analyzer = class {
707
727
  node = node.arguments[0];
708
728
  continue;
709
729
  }
710
- if (name === void 0 || !WRAPPERS$2.has(name)) break;
730
+ if (name === void 0 || !WRAPPERS$3.has(name)) break;
711
731
  const [handler, ...rest] = node.arguments;
712
732
  if (!handler || name !== "prevent" && rest.length > 0) {
713
733
  this.report("error", `${name} takes a handler`, node);
@@ -890,6 +910,31 @@ var Analyzer = class {
890
910
  declaration.passedKey = prop.propKey;
891
911
  return;
892
912
  }
913
+ if (name === "$searchParam") {
914
+ const expected = "let";
915
+ if (kind !== expected) this.report("error", `Declare ${name} with ${expected}`, declarator);
916
+ if (id.type !== "Identifier") {
917
+ this.report("error", `${name} cannot be destructured`, id);
918
+ return;
919
+ }
920
+ const [first, options] = call.arguments;
921
+ if (first?.type !== "Literal" || typeof first.value !== "string" || call.arguments.length > 2 || options && options.type !== "ObjectExpression") {
922
+ this.report("error", `${name} needs a value`, call);
923
+ return;
924
+ }
925
+ for (const other of this.declarations) {
926
+ const [earlier] = other.searchParam?.arguments ?? [];
927
+ if (other.scope === scope && earlier?.type === "Literal" && earlier.value === first.value) {
928
+ this.report("error", `"${id.name}" is already declared`, id);
929
+ return;
930
+ }
931
+ }
932
+ const declaration = this.addDeclaration(scope, id.name, "signal", id);
933
+ declaration.searchParam = call;
934
+ this.createSite("effect", scope, call, "search param");
935
+ this.createSite("client", scope, call, "search param", { trigger: "load" });
936
+ return;
937
+ }
893
938
  if (name === "$route" || name === "$navigation") {
894
939
  if (kind !== "const" || id.type !== "Identifier") {
895
940
  this.report("error", MISPLACED[name], declarator);
@@ -1076,7 +1121,7 @@ var Analyzer = class {
1076
1121
  node = handler;
1077
1122
  continue;
1078
1123
  }
1079
- if (name === void 0 || !WRAPPERS$2.has(name) || !handler) break;
1124
+ if (name === void 0 || !WRAPPERS$3.has(name) || !handler) break;
1080
1125
  const names = [];
1081
1126
  let unnamed = false;
1082
1127
  for (const key of keys) {
@@ -1677,6 +1722,10 @@ var Resolver = class {
1677
1722
  for (const argument of recipe ? [recipe, ...rest] : rest) this.visit(argument);
1678
1723
  return;
1679
1724
  }
1725
+ if (name === "$searchParam" && this.site.node === node) {
1726
+ for (const argument of node.arguments) this.visit(argument);
1727
+ return;
1728
+ }
1680
1729
  if (name === "$bind") {
1681
1730
  this.declareBinding(node);
1682
1731
  for (const argument of node.arguments) this.visit(argument);
@@ -1884,8 +1933,9 @@ const SYNTAX = [
1884
1933
  entry("BRM019", "Only event handlers are allowed here", "`<window>` and `<document>` take event handlers and nothing else.", "<document onKeyDown=(handler) />"),
1885
1934
  entry("BRM020", "Expected a spread or a shorthand attribute", "A `{` in a tag holds something other than `...rest` or a name.", "<a {href} {...rest}>Open</a>"),
1886
1935
  entry("BRM021", "Expected an attribute name", "A tag has a character where an attribute name belongs.", "<input disabled>"),
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>"),
1936
+ entry("BRM022", "Event modifiers in the attribute name were removed. Write {fix}", "A modifier follows the event name, as in `onSubmit:prevent=send`. Wrappers of `brumate/events` write modifiers now, and `:passive` is the default, since listeners are passive unless a handler prevents.", "import { prevent } from 'brumate/events';\n\n<form onSubmit=(prevent(send))></form>"),
1888
1937
  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) />"),
1938
+ entry("BRM201", "\"{name}\" cannot be a handler. {fix}", "The event has capitals in its name, or the browser fires another name for it, and a handler name is lower-cased to the event. `onDOMContentLoaded` would listen to `domcontentloaded`, which the browser never fires, and page code loads after the HTML, mostly after `DOMContentLoaded`. Use the event that the message names, or `$client(fn, 'load')` to run code at load.", "<script>\n $client(() => {\n start();\n }, 'load');\n<\/script>"),
1889
1939
  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}"),
1890
1940
  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>"),
1891
1941
  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}"),
@@ -1893,7 +1943,6 @@ const SYNTAX = [
1893
1943
  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
1944
  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
1945
  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}"),
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>"),
1897
1946
  entry("BRM024", "Expected an event handler", "An event attribute has no `=` and no value.", "<button onClick=(() => count++)>Add</button>"),
1898
1947
  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>"),
1899
1948
  entry("BRM026", "An attribute name can have one \":\" namespace", "An attribute name has two or more `:`.", "<svg xlink:href=\"#icon\"></svg>"),
@@ -1909,6 +1958,8 @@ const SYNTAX = [
1909
1958
  entry("BRM036", "A file can have one <script module>", "A file has two module scripts.", "<script module>\n export const MAX = 10;\n export const MIN = 1;\n<\/script>"),
1910
1959
  entry("BRM037", "A file can have one <script>", "A file has two instance scripts.", "<script>\n let a = $signal(1);\n let b = $signal(2);\n<\/script>"),
1911
1960
  entry("BRM038", "lang must be \"css\", \"scss\" or \"less\"", "A `<style>` names another language.", "<style lang=\"scss\">\n p {\n a {\n color: red;\n }\n }\n</style>"),
1961
+ entry("BRM189", "Unknown <style> attribute \"{name}\"", "A `<style>` has an attribute other than `lang` and `global`.", "<style scoped>\n p {\n color: red;\n }\n</style>"),
1962
+ entry("BRM190", "global takes no value, as in <style global>", "A `<style global>` gives `global` a value.", "<style global=\"true\">\n p {\n color: red;\n }\n</style>"),
1912
1963
  entry("BRM039", "#reveal takes an order, 'sequential', 'backwards', 'together' or 'natural', and collapsed, such as #reveal ('sequential', collapsed)", "`#reveal` has an option that it does not know.", "#reveal ('sequential', collapsed) {\n …\n}"),
1913
1964
  entry("BRM040", "collapsed shows the fallback of the next body to show, so it needs the order 'sequential', not '{order}'", "`collapsed` goes with `sequential` only.", "#reveal ('sequential', collapsed) {\n …\n}"),
1914
1965
  entry("BRM041", "#reveal has no script of its own", "A `#reveal` body starts with a `<script>`.", "<script>\n let open = $signal(false);\n<\/script>\n#reveal {\n …\n}"),
@@ -2206,6 +2257,38 @@ const SOURCE_KINDS = /* @__PURE__ */ new Set([
2206
2257
  "error",
2207
2258
  "template-param"
2208
2259
  ]);
2260
+ /** True if the read is inside the compute of one of the memos; a read in its inner function counts. */
2261
+ function isReadIn(read, memos) {
2262
+ const site = read.site;
2263
+ return site.kind === "memo" && site.declaration !== void 0 && memos.has(site.declaration);
2264
+ }
2265
+ /**
2266
+ * Finds the memos that no browser code reads: no read at all, or reads only in the compute of
2267
+ * other such memos. The server computes a memo when something reads it, so the browser does not
2268
+ * compute these either. A memo that is awaited where it is declared, a debounced or throttled
2269
+ * value, an optimistic value, a search parameter, a bound value and a ref target stay.
2270
+ */
2271
+ function findUnread(model) {
2272
+ const unread = /* @__PURE__ */ new Set();
2273
+ const candidates = [];
2274
+ for (const declaration of model.declarations) if (isMemoKind(declaration.kind) && declaration.site?.kind === "memo" && !declaration.awaited && !declaration.timing && !declaration.optimistic && !declaration.writable && !declaration.searchParam && !declaration.bound && declaration.refs.length === 0 && declaration.writes.length === 0) candidates.push(declaration);
2275
+ for (let changed = true; changed;) {
2276
+ changed = false;
2277
+ for (const declaration of candidates) {
2278
+ if (unread.has(declaration)) continue;
2279
+ let read = false;
2280
+ for (const item of declaration.reads) if (!isReadIn(item, unread)) {
2281
+ read = true;
2282
+ break;
2283
+ }
2284
+ if (!read) {
2285
+ unread.add(declaration);
2286
+ changed = true;
2287
+ }
2288
+ }
2289
+ }
2290
+ return unread;
2291
+ }
2209
2292
  /** True if a prop or the rest of the props can change on the client. */
2210
2293
  function isLiveProp(declaration, liveProps) {
2211
2294
  if (!liveProps || liveProps.has("*")) return true;
@@ -2233,6 +2316,18 @@ function callsRefreshed(declaration) {
2233
2316
  for (const callee of declaration.site?.calls ?? []) if (callee.refreshed) return true;
2234
2317
  return false;
2235
2318
  }
2319
+ /**
2320
+ * True for a `$searchParam` that the browser can change without a request: the URL is the source
2321
+ * when the page loads, and the history writes it. One with `server: true` navigates instead. A spread in the options may hold `server`, and
2322
+ * such a signal stays live, which costs a slot and breaks nothing.
2323
+ */
2324
+ function followsUrl(declaration) {
2325
+ const options = declaration.searchParam?.arguments[1];
2326
+ if (!declaration.searchParam) return false;
2327
+ if (options?.type !== "ObjectExpression") return true;
2328
+ for (const property of options.properties) if (property.type === "Property" && property.key.type === "Identifier" && property.key.name === "server") return false;
2329
+ return true;
2330
+ }
2236
2331
  /** True if the declaration is referenced from one of the scopes. */
2237
2332
  function hasRefIn(declaration, scopes) {
2238
2333
  for (const ref of declaration.refs) if (scopes.has(ref.scope)) return true;
@@ -2455,6 +2550,7 @@ function buildGraph(model, options = {}) {
2455
2550
  const live = /* @__PURE__ */ new Set();
2456
2551
  const reached = /* @__PURE__ */ new Set();
2457
2552
  const created = /* @__PURE__ */ new Set();
2553
+ const unread = findUnread(model);
2458
2554
  function reach(site) {
2459
2555
  if (reached.has(site)) return;
2460
2556
  reached.add(site);
@@ -2471,10 +2567,10 @@ function buildGraph(model, options = {}) {
2471
2567
  const templateUsed = scope.kind === "template" && templateCallChanges(scope);
2472
2568
  if (parentCreated || blockLive || templateUsed) created.add(scope);
2473
2569
  }
2474
- for (const site of model.sites) if (site.kind === "event" || site.kind === "client" || site.kind === "prop" && isFunctionValue(site) || site.kind === "block" && site.block?.kind === "for" && site.block.window !== void 0 || site.kind === "effect" && live.has(siteNodes.get(site)) || created.has(site.scope)) reach(site);
2570
+ for (const site of model.sites) if ((site.kind === "event" || site.kind === "client" || site.kind === "prop" && isFunctionValue(site) || site.kind === "block" && site.block?.kind === "for" && site.block.window !== void 0 || site.kind === "effect" && live.has(siteNodes.get(site)) || created.has(site.scope)) && !(site.kind === "memo" && unread.has(site.declaration))) reach(site);
2475
2571
  for (const [declaration, node] of declarationNodes) {
2476
2572
  if (live.has(node)) continue;
2477
- if ((declaration.kind === "prop" || declaration.kind === "props-rest") && isLiveProp(declaration, options.liveProps) || declaration.kind === "prop" && declaration.writable === true && anyReached(declaration.writes, reached) || declaration.kind === "context" || declaration.kind === "action" || isMemoKind(declaration.kind) && callsRefreshed(declaration) || declaration.kind === "memo" && isPropValue(declaration.site) || declaration.optimistic !== void 0 && anyReached(declaration.writes, reached) || declaration.kind === "signal" && (anyReached(declaration.writes, reached) || hasRefIn(declaration, created)) || declaration.kind === "error" && declaration.block?.kind === "try" && tryChanges(declaration.block) || declaration.bound === true || declaration.kind === "template-param" && templateCallChanges(declaration.scope)) live.add(node);
2573
+ if ((declaration.kind === "prop" || declaration.kind === "props-rest") && isLiveProp(declaration, options.liveProps) || declaration.kind === "prop" && declaration.writable === true && anyReached(declaration.writes, reached) || declaration.kind === "context" || declaration.kind === "action" || isMemoKind(declaration.kind) && callsRefreshed(declaration) || declaration.kind === "memo" && isPropValue(declaration.site) || declaration.optimistic !== void 0 && anyReached(declaration.writes, reached) || declaration.kind === "signal" && (anyReached(declaration.writes, reached) || hasRefIn(declaration, created) || followsUrl(declaration)) || declaration.kind === "error" && declaration.block?.kind === "try" && tryChanges(declaration.block) || declaration.bound === true || declaration.kind === "template-param" && templateCallChanges(declaration.scope)) live.add(node);
2478
2574
  }
2479
2575
  for (let propagated = true; propagated;) {
2480
2576
  propagated = false;
@@ -2483,6 +2579,7 @@ function buildGraph(model, options = {}) {
2483
2579
  propagated = true;
2484
2580
  }
2485
2581
  }
2582
+ for (const declaration of unread) live.delete(declarationNodes.get(declaration));
2486
2583
  if (live.size + reached.size + created.size !== before) changed = true;
2487
2584
  }
2488
2585
  function templateCallChanges(scope) {
@@ -2531,6 +2628,7 @@ function buildGraph(model, options = {}) {
2531
2628
  live,
2532
2629
  reached,
2533
2630
  created,
2631
+ unread,
2534
2632
  diagnostics
2535
2633
  };
2536
2634
  }
@@ -2637,6 +2735,31 @@ function camelEventName(attribute) {
2637
2735
  const camel = BY_LOWER.get(attribute.toLowerCase());
2638
2736
  return camel === attribute ? void 0 : camel;
2639
2737
  }
2738
+ const NO_HANDLER = /* @__PURE__ */ new Map([
2739
+ ["domcontentloaded", "The page code loads after the HTML, mostly after this event, and a client navigation never fires it. Run code at load with $client(fn, 'load')"],
2740
+ ["domactivate", "The event is deprecated. Write onClick"],
2741
+ ["domfocusin", "The event is deprecated. Write onFocusIn"],
2742
+ ["domfocusout", "The event is deprecated. Write onFocusOut"],
2743
+ ["dommousescroll", "The event is not standard. Write onWheel"],
2744
+ ["mozmousepixelscroll", "The event is not standard. Write onWheel"],
2745
+ ["webkitanimationstart", "The browser fires the prefixed name only. Write onAnimationStart"],
2746
+ ["webkitanimationiteration", "The browser fires the prefixed name only. Write onAnimationIteration"],
2747
+ ["webkitanimationend", "The browser fires the prefixed name only. Write onAnimationEnd"],
2748
+ ["webkittransitionend", "The browser fires the prefixed name only. Write onTransitionEnd"]
2749
+ ]);
2750
+ for (const mutation of [
2751
+ "DOMAttrModified",
2752
+ "DOMCharacterDataModified",
2753
+ "DOMNodeInserted",
2754
+ "DOMNodeInsertedIntoDocument",
2755
+ "DOMNodeRemoved",
2756
+ "DOMNodeRemovedFromDocument",
2757
+ "DOMSubtreeModified"
2758
+ ]) NO_HANDLER.set(mutation.toLowerCase(), "The event is removed. Observe the DOM with a MutationObserver");
2759
+ /** What to write instead of a handler for an event that has none, such as `onDOMContentLoaded`. */
2760
+ function noHandlerFix(attribute) {
2761
+ return NO_HANDLER.get(attribute.slice(2).toLowerCase());
2762
+ }
2640
2763
  //#endregion
2641
2764
  //#region src/scan.ts
2642
2765
  function isWhitespace(char) {
@@ -2812,6 +2935,12 @@ function findTopLevel(code, word, fail) {
2812
2935
  }
2813
2936
  //#endregion
2814
2937
  //#region src/parser.ts
2938
+ const WRAPPERS$2 = /* @__PURE__ */ new Set([
2939
+ "prevent",
2940
+ "stop",
2941
+ "once",
2942
+ "capture"
2943
+ ]);
2815
2944
  const VOID_ELEMENTS$1 = /* @__PURE__ */ new Set([
2816
2945
  "area",
2817
2946
  "base",
@@ -2851,13 +2980,6 @@ const BRANCH_KEYWORDS = /* @__PURE__ */ new Set([
2851
2980
  "case",
2852
2981
  "default"
2853
2982
  ]);
2854
- const MODIFIERS = /* @__PURE__ */ new Set([
2855
- "prevent",
2856
- "stop",
2857
- "passive",
2858
- "once",
2859
- "capture"
2860
- ]);
2861
2983
  const CLIENT_TRIGGERS = /* @__PURE__ */ new Set([
2862
2984
  "visible",
2863
2985
  "idle",
@@ -3138,8 +3260,11 @@ var Parser = class {
3138
3260
  }
3139
3261
  /** A handler of an element is written in camel case: `onKeyDown`, not `onKeydown`. */
3140
3262
  checkEventName(name, owner, start) {
3141
- const camel = owner === "component" || owner === "dynamic" ? void 0 : camelEventName(name);
3263
+ if (owner === "component" || owner === "dynamic") return;
3264
+ const camel = camelEventName(name);
3142
3265
  if (camel) this.fail(`"${name}" is not an event name. Write "${camel}"`, start);
3266
+ const fix = noHandlerFix(name);
3267
+ if (fix) this.fail(`"${name}" cannot be a handler. ${fix}`, start);
3143
3268
  }
3144
3269
  parseAttribute(owner) {
3145
3270
  const start = this.pos;
@@ -3162,7 +3287,6 @@ var Parser = class {
3162
3287
  end: this.pos,
3163
3288
  name,
3164
3289
  event: name.slice(2).toLowerCase(),
3165
- modifiers: [],
3166
3290
  handler: this.expression(inner.start, inner.end)
3167
3291
  };
3168
3292
  }
@@ -3198,10 +3322,23 @@ var Parser = class {
3198
3322
  const parts = fullName.split(":");
3199
3323
  if (/^on[A-Z]/.test(fullName)) {
3200
3324
  const name = parts[0];
3201
- const modifiers = parts.slice(1);
3202
3325
  this.checkEventName(name, owner, start);
3203
- for (const modifier of modifiers) if (!MODIFIERS.has(modifier)) this.fail(`Unknown event modifier ":${modifier}"`, start);
3204
- if (owner === "component" && modifiers.length > 0) this.fail(`Modifiers apply to elements. Put ":${modifiers[0]}" on the element that the component renders`, start);
3326
+ if (parts.length > 1) {
3327
+ const rest = parts.slice(1);
3328
+ const wrappers = [];
3329
+ let unknown;
3330
+ for (const modifier of rest) if (WRAPPERS$2.has(modifier)) wrappers.push(modifier);
3331
+ else if (modifier !== "passive") unknown ??= modifier;
3332
+ let fix;
3333
+ if (unknown !== void 0) fix = `${name}=(handler) with the wrappers of brumate/events, since ":${unknown}" is not a modifier`;
3334
+ else if (wrappers.length === 0) fix = `${name}=(handler), since listeners are passive unless a handler prevents`;
3335
+ else {
3336
+ let call = "handler";
3337
+ for (const wrapper of wrappers.toReversed()) call = `${wrapper}(${call})`;
3338
+ fix = `${name}=(${call}) with ${wrappers.join(" and ")} from brumate/events`;
3339
+ }
3340
+ this.fail(`Event modifiers in the attribute name were removed. Write ${fix}`, start);
3341
+ }
3205
3342
  if (this.peek() !== "=") this.fail("Expected an event handler", this.pos);
3206
3343
  this.pos++;
3207
3344
  const value = this.parseValue();
@@ -3212,7 +3349,6 @@ var Parser = class {
3212
3349
  end: this.pos,
3213
3350
  name,
3214
3351
  event: name.slice(2).toLowerCase(),
3215
- modifiers,
3216
3352
  handler: value
3217
3353
  };
3218
3354
  }
@@ -3372,6 +3508,8 @@ var Parser = class {
3372
3508
  const start = this.pos;
3373
3509
  const { attributes, contentStart } = this.parseBlockTag("style");
3374
3510
  const { contentEnd } = this.readBlockContent("style", contentStart);
3511
+ for (const name of Object.keys(attributes)) if (name !== "lang" && name !== "global") this.fail(`Unknown <style> attribute "${name}"`, start);
3512
+ if (attributes.global !== void 0 && attributes.global !== true) this.fail("global takes no value, as in <style global>", start);
3375
3513
  const lang = attributes.lang ?? "css";
3376
3514
  if (lang !== "css" && lang !== "scss" && lang !== "less") return this.fail("lang must be \"css\", \"scss\" or \"less\"", start);
3377
3515
  const variables = [];
@@ -3389,6 +3527,7 @@ var Parser = class {
3389
3527
  start,
3390
3528
  end: this.pos,
3391
3529
  lang,
3530
+ global: attributes.global === true,
3392
3531
  content: this.source.slice(contentStart, contentEnd),
3393
3532
  variables
3394
3533
  };
@@ -5123,6 +5262,38 @@ function expandModules(file, path, resolve) {
5123
5262
  };
5124
5263
  }
5125
5264
  //#endregion
5265
+ //#region src/codegen/primitive.ts
5266
+ /**
5267
+ * True if an expression always gives a primitive, so it is never a promise
5268
+ * or an async iterable. A name is a primitive when `plain` says that it reads
5269
+ * a declaration that holds one.
5270
+ */
5271
+ function isPrimitive(node, plain = () => false) {
5272
+ switch (node.type) {
5273
+ case "Identifier": return plain(node);
5274
+ case "Literal": return !("regex" in node && node.regex);
5275
+ case "TemplateLiteral":
5276
+ case "BinaryExpression":
5277
+ case "UnaryExpression": return true;
5278
+ case "LogicalExpression": return isPrimitive(node.left, plain) && isPrimitive(node.right, plain);
5279
+ case "ConditionalExpression": return isPrimitive(node.consequent, plain) && isPrimitive(node.alternate, plain);
5280
+ case "TSAsExpression":
5281
+ case "TSSatisfiesExpression":
5282
+ case "TSNonNullExpression": return isPrimitive(node.expression, plain);
5283
+ default: return false;
5284
+ }
5285
+ }
5286
+ /** Expressions whose value is never a promise, as the memo of a list or a function. */
5287
+ const NEVER_PROMISE = /* @__PURE__ */ new Set([
5288
+ "ArrayExpression",
5289
+ "ArrowFunctionExpression",
5290
+ "FunctionExpression"
5291
+ ]);
5292
+ /** True for an expression that gives a primitive, an array or a function, never a promise. */
5293
+ function neverPromise(node) {
5294
+ return isPrimitive(node) || NEVER_PROMISE.has(node.type);
5295
+ }
5296
+ //#endregion
5126
5297
  //#region src/codegen/patch.ts
5127
5298
  /** Rewrites ranges of the source with edits that do not overlap. */
5128
5299
  var Patch = class {
@@ -5170,6 +5341,16 @@ const MEMOS = /* @__PURE__ */ new Set([
5170
5341
  "$debounced",
5171
5342
  "$throttled"
5172
5343
  ]);
5344
+ /**
5345
+ * The code of an arrow function body, given the source offset where the user's expression starts.
5346
+ * An expression that starts with `{` is wrapped in parentheses, or the arrow reads it as a block.
5347
+ * This covers an object literal under `as`, `satisfies`, `!` and a `<T>` cast, and a sequence or
5348
+ * member access that starts with one. The source is checked, not the code, because the code can
5349
+ * start with a marker of the compiler.
5350
+ */
5351
+ function arrowBody(code, source, start) {
5352
+ return source[start] === "{" ? `(${code})` : code;
5353
+ }
5173
5354
  function promiseName(name) {
5174
5355
  return `$$p_${name}`;
5175
5356
  }
@@ -5241,11 +5422,18 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
5241
5422
  for (const read of site.reads) if (read.range.start !== read.range.end && read.range.start >= node.start && read.range.end <= node.end && !targets.has(read.range.start) && !isFolded(read) && read.declaration !== own && !inline.has(read.declaration) && (!only || only.has(read.declaration)) && !replaced.has(read) && !replacedAt.has((read.await ?? read.range).start) && (read.declaration.kind === "memo" || read.declaration.kind === "async-memo")) {
5242
5423
  const range = read.await ?? read.range;
5243
5424
  const key = shorthands.has(range.start) ? `${read.declaration.name}: ` : "";
5244
- patch.replace(range.start, range.end, `${key}$$b.read(${promiseName(read.declaration.name)})`);
5425
+ patch.replace(range.start, range.end, mode === "render" ? `${key}$$b.readMemo(${read.declaration.name})` : `${key}$$b.read(${promiseName(read.declaration.name)})`);
5245
5426
  replaced.add(read);
5246
5427
  replacedAt.add(range.start);
5247
5428
  }
5248
5429
  }
5430
+ if (mode === "render") {
5431
+ const held = /* @__PURE__ */ new Set();
5432
+ for (const site of sites) if (site.kind === "memo" && site.declaration && !inline.has(site.declaration)) {
5433
+ if (site.awaits || !neverPromise(site.node)) held.add(site.declaration);
5434
+ }
5435
+ for (const site of sites) readMemos(site, site.node, site.declaration, held);
5436
+ }
5249
5437
  if (mode === "server") {
5250
5438
  for (const site of sites) if (site.kind === "function") readMemos(site, site.node);
5251
5439
  if (lazy.size > 0) {
@@ -5285,6 +5473,11 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
5285
5473
  patch.replace(node.start, node.end, mode === "server" && argument?.type === "Identifier" ? `$$b.actionResult($$ctx, ${argument.name})` : "undefined");
5286
5474
  return;
5287
5475
  }
5476
+ if (name === "$searchParam" && argument) {
5477
+ patch.replace(node.start, argument.start, mode === "server" ? "$$b.searchParam($$ctx, " : "$$b.searchParam(");
5478
+ for (const rest of node.arguments) visit(rest);
5479
+ return;
5480
+ }
5288
5481
  if (name === "$isBound") {
5289
5482
  patch.replace(node.start, node.end, "false");
5290
5483
  return;
@@ -5317,6 +5510,9 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
5317
5510
  readMemos(site, argument, declaration);
5318
5511
  patch.replace(node.start, argument.start, site.awaits ? "$$b.memo(async () => (" : "$$b.memo(() => (");
5319
5512
  patch.replace(argument.end, node.end, `), $$ctx, ${JSON.stringify(declaration.name)})`);
5513
+ } else if (mode === "render" && declaration && (site.awaits || !neverPromise(argument))) {
5514
+ patch.replace(node.start, argument.start, site.awaits ? "$$b.renderMemo(async () => (" : "$$b.renderMemo(() => (");
5515
+ patch.replace(argument.end, node.end, "))");
5320
5516
  } else if (site?.awaits) {
5321
5517
  patch.replace(node.start, argument.start, "(async () => (");
5322
5518
  patch.replace(argument.end, node.end, "))()");
@@ -5787,9 +5983,10 @@ function scopeTarget(compound) {
5787
5983
  }
5788
5984
  /**
5789
5985
  * Adds the scope attribute to every compound selector, except inside
5790
- * `:global(…)`. Each scoped compound goes into `targets`.
5986
+ * `:global(…)`. Each scoped compound goes into `targets`. With `unscoped`, no
5987
+ * compound is scoped, and `:global(…)` is only unwrapped.
5791
5988
  */
5792
- function scopeSelector(attribute, targets) {
5989
+ function scopeSelector(attribute, targets, unscoped) {
5793
5990
  return selectorParser((selectors) => {
5794
5991
  for (let index = 0; index < selectors.nodes.length; index++) {
5795
5992
  const selector = selectors.nodes[index];
@@ -5833,7 +6030,7 @@ function scopeSelector(attribute, targets) {
5833
6030
  global.replaceWith(...clones);
5834
6031
  continue;
5835
6032
  }
5836
- if (compound.length === 0) continue;
6033
+ if (compound.length === 0 || unscoped) continue;
5837
6034
  targets.push(scopeTarget(compound));
5838
6035
  let last;
5839
6036
  for (let at = compound.length - 1; at >= 0; at--) {
@@ -5854,8 +6051,8 @@ function scopeSelector(attribute, targets) {
5854
6051
  });
5855
6052
  });
5856
6053
  }
5857
- function scopeRules(root, attribute, targets) {
5858
- const processor = scopeSelector(attribute, targets);
6054
+ function scopeRules(root, attribute, targets, unscoped) {
6055
+ const processor = scopeSelector(attribute, targets, unscoped);
5859
6056
  root.walkRules((rule) => {
5860
6057
  if (rule.parent?.type === "atrule" && /keyframes$/i.test(rule.parent.name)) return;
5861
6058
  rule.selector = processor.processSync(rule.selector);
@@ -5982,7 +6179,7 @@ function compileStyles(file, scope, filePath) {
5982
6179
  content += style.content.slice(position);
5983
6180
  try {
5984
6181
  const root = parse(style.lang === "css" ? content : preprocess(style.lang, content, filePath, dependencies));
5985
- scopeRules(root, attribute, targets);
6182
+ scopeRules(root, attribute, targets, style.global);
5986
6183
  parts.push(root.toString().trim());
5987
6184
  } catch (error) {
5988
6185
  diagnostics.push({
@@ -6536,11 +6733,56 @@ function holderArguments(plan, block) {
6536
6733
  }
6537
6734
  //#endregion
6538
6735
  //#region src/codegen/template.ts
6736
+ const contexts = /* @__PURE__ */ new WeakMap();
6737
+ /**
6738
+ * `svg` or `math` when the elements around a body, or around the children of a component, put
6739
+ * its markup in SVG or MathML, which HTML that the browser parses there would find at run time.
6740
+ * `owner` is the body, or the component or dynamic tag that the children belong to.
6741
+ */
6742
+ function foreignContext(file, owner) {
6743
+ if (!owner) return;
6744
+ let found = contexts.get(file);
6745
+ if (!found) {
6746
+ found = /* @__PURE__ */ new Map();
6747
+ contexts.set(file, found);
6748
+ const map = found;
6749
+ const walk = (nodes, around) => {
6750
+ for (const node of nodes) switch (node.kind) {
6751
+ case "element": {
6752
+ const tag = node.tag.toLowerCase();
6753
+ let inside = around;
6754
+ if (tag === "svg" || tag === "math") inside = tag;
6755
+ else if (tag === "foreignobject") inside = void 0;
6756
+ walk(node.children, inside);
6757
+ break;
6758
+ }
6759
+ case "component":
6760
+ case "dynamic":
6761
+ map.set(node, around);
6762
+ walk(node.children, around);
6763
+ break;
6764
+ case "fragment":
6765
+ walk(node.children, around);
6766
+ break;
6767
+ case "text":
6768
+ case "insert":
6769
+ case "listener": break;
6770
+ default: for (const body of blockBodies(node)) {
6771
+ map.set(body, around);
6772
+ walk(body.children, around);
6773
+ }
6774
+ }
6775
+ };
6776
+ walk(file.children, void 0);
6777
+ }
6778
+ return found.get(owner);
6779
+ }
6539
6780
  const ATTRIBUTE = /^\$\$b\.attribute\(("(?:[^"\\]|\\.)*"), ([\s\S]*)\)$/;
6540
6781
  const CLASS_TOKEN = /^\(\(([\s\S]*)\) \? " ([^"\\&<>]+)" : ""\)$/;
6541
6782
  /**
6542
6783
  * The static classes of a `class` with code in its quotes, and the calls that add the classes
6543
- * that conditions add, when each piece of code is such a condition. `parts` are the parts of
6784
+ * that conditions add, when each piece of code is such a condition and no static class follows
6785
+ * one, so the classes keep their order. `parts` are the parts of
6544
6786
  * the value after its static `prefix`, up to its closing quote.
6545
6787
  */
6546
6788
  function classTokens(parts, prefix) {
@@ -6548,6 +6790,7 @@ function classTokens(parts, prefix) {
6548
6790
  const calls = [];
6549
6791
  for (const part of parts) {
6550
6792
  if ("static" in part) {
6793
+ if (calls.length > 0 && part.static.trim() !== "") return;
6551
6794
  text += part.static;
6552
6795
  continue;
6553
6796
  }
@@ -6728,8 +6971,9 @@ var Reader = class {
6728
6971
  }
6729
6972
  };
6730
6973
  /** The template of a render's parts, or undefined when its markup needs HTML. */
6731
- function clonedTemplate(parts) {
6974
+ function clonedTemplate(parts, filled, around) {
6732
6975
  const reader = new Reader();
6976
+ reader.foreign = around;
6733
6977
  const writes = [];
6734
6978
  /** The index of each marked element, by its number in the order of the markup. */
6735
6979
  const marks = /* @__PURE__ */ new Map();
@@ -6858,7 +7102,7 @@ function clonedTemplate(parts) {
6858
7102
  continue;
6859
7103
  }
6860
7104
  const blockEnd = nextStatic === void 0 ? null : BLOCK_END.exec(nextStatic);
6861
- if (SCOPE.test(code) && reader.html.endsWith(BLOCK_START) && blockEnd) {
7105
+ if (SCOPE.test(code) && reader.html.endsWith(BLOCK_START) && blockEnd && (!filled || filled(code, Number(blockEnd[1])))) {
6862
7106
  reader.takeBack(BLOCK_START, "text");
6863
7107
  const mark = writes.length;
6864
7108
  writes.push([{
@@ -6980,7 +7224,7 @@ function clonedTemplate(parts) {
6980
7224
  }
6981
7225
  return;
6982
7226
  }
6983
- if (reader.html.replace(/<!--x\d+-->|<!--\/[biP]-->/g, "").includes("<!--") || /<template\b/i.test(reader.html)) return;
7227
+ const indexed = reader.html.replace(/<!--x\d+-->|<!--\/[biP]-->/g, "").includes("<!--") || /<template\b/i.test(reader.html) || void 0;
6984
7228
  function getAnchor(element) {
6985
7229
  for (const write of writes[marks.get(element) ?? -1] ?? []) if (write.kind === "anchor") return write;
6986
7230
  }
@@ -6998,7 +7242,8 @@ function clonedTemplate(parts) {
6998
7242
  return {
6999
7243
  html: reader.html,
7000
7244
  writes,
7001
- foreign: reader.foreign
7245
+ foreign: reader.foreign,
7246
+ indexed
7002
7247
  };
7003
7248
  }
7004
7249
  /**
@@ -7016,7 +7261,7 @@ function promised(scope, key, value, write) {
7016
7261
  * The lines between the first and the last `$$html +=` can only declare the values of the
7017
7262
  * writes, which run after them. Plain `{` blocks around them go, so the writes see them.
7018
7263
  */
7019
- function cloneLines(emitter, hoist, fn = 0) {
7264
+ function cloneLines(emitter, hoist, fn = 0, owner) {
7020
7265
  const { lines: source, levels } = emitter;
7021
7266
  function isTop(at) {
7022
7267
  return levels[at].fn === fn && !levels[at].control;
@@ -7063,12 +7308,13 @@ function cloneLines(emitter, hoist, fn = 0) {
7063
7308
  if (previous && "static" in previous && "static" in part) parts[parts.length - 1] = { static: previous.static + part.static };
7064
7309
  else parts.push({ ...part });
7065
7310
  }
7066
- const found = clonedTemplate(parts);
7311
+ const found = clonedTemplate(parts, (scope, anchor) => emitter.fills?.has(`${scope}:${anchor}`) ?? false, emitter.foreignAround(owner));
7067
7312
  if (!found) return false;
7068
7313
  const flush = tops[0];
7069
7314
  const indent = /^ */.exec(emitter.lines[flush.line])[0];
7070
- const foreign = found.foreign ? `, ${JSON.stringify(found.foreign)}` : "";
7071
- const lines = [`${indent}const $$e = $$b.clone(${hoist(`$$b.template(${JSON.stringify(found.html)}, ${found.writes.length}${foreign})`)}), $$f = $$e[${found.writes.length}];`];
7315
+ let options = found.foreign ? `, ${JSON.stringify(found.foreign)}` : "";
7316
+ if (found.indexed) options += `${found.foreign ? "" : ", undefined"}, 1`;
7317
+ const lines = [`${indent}const $$e = $$b.clone(${hoist(`$$b.template(${JSON.stringify(found.html)}, ${found.writes.length}${options})`)}), $$f = $$e[${found.writes.length}];`];
7072
7318
  const fills = [];
7073
7319
  const settled = /* @__PURE__ */ new Map();
7074
7320
  function addLine(line, memos) {
@@ -7357,6 +7603,50 @@ function scopePath(plan, base, from, target) {
7357
7603
  }
7358
7604
  return expression;
7359
7605
  }
7606
+ /**
7607
+ * The parameters of a template of the file, and the `[slot, value]` pairs of its arguments, so a
7608
+ * call that comes again writes its new arguments into the scope that it rendered. `params` are
7609
+ * the parameters as written, `exported` have no default values (the call passes the values with
7610
+ * them), and `names` are the arguments when each parameter is a name and one has a default.
7611
+ * Nothing if the template has no scope of its own, or a destructured parameter has a default
7612
+ * value: it then renders again. An argument that no slot holds is never read in the browser.
7613
+ */
7614
+ function templateArgs(plan, source, scope) {
7615
+ const template = scope.template;
7616
+ if (!template || !plan.scopes.get(scope)?.needsId) return;
7617
+ const first = template.params[0];
7618
+ const last = template.params.at(-1);
7619
+ const params = first && last ? copy(source, first.start, last.end) : "";
7620
+ const exported = [];
7621
+ const names = [];
7622
+ let simple = true;
7623
+ let defaults = false;
7624
+ for (const param of template.params) {
7625
+ const target = param.type === "AssignmentPattern" ? param.left : param;
7626
+ defaults ||= target !== param;
7627
+ if (target.type === "Identifier") names.push(target.name);
7628
+ else simple = false;
7629
+ if (target.type !== "Identifier" && hasDefault(target)) return;
7630
+ exported.push(copy(source, target.start, target.end));
7631
+ }
7632
+ const pairs = [];
7633
+ for (const declaration of scope.declarations.values()) {
7634
+ if (declaration.kind !== "template-param") continue;
7635
+ const slot = slotIndex(plan, declaration);
7636
+ if (slot !== -1) pairs.push(`[${slot}, ${declaration.name}]`);
7637
+ }
7638
+ return {
7639
+ params,
7640
+ exported: exported.join(", "),
7641
+ names: simple && defaults ? names : void 0,
7642
+ pairs
7643
+ };
7644
+ }
7645
+ function hasDefault(node) {
7646
+ if (node.type === "AssignmentPattern") return true;
7647
+ for (const [, child] of children(node)) if (hasDefault(child)) return true;
7648
+ return false;
7649
+ }
7360
7650
  /** Returns the slot index of a declaration, or -1. */
7361
7651
  function slotIndex(plan, declaration) {
7362
7652
  return plan.scopes.get(declaration.scope)?.slots.indexOf(declaration) ?? -1;
@@ -7610,26 +7900,6 @@ const UNSAFE_NODES = /* @__PURE__ */ new Set([
7610
7900
  "ArrowFunctionExpression",
7611
7901
  "ClassExpression"
7612
7902
  ]);
7613
- /**
7614
- * True if an expression always gives a primitive, so it is never a promise
7615
- * or an async iterable. A name is a primitive when `plain` says that it reads
7616
- * a declaration that holds one.
7617
- */
7618
- function isPrimitive(node, plain = () => false) {
7619
- switch (node.type) {
7620
- case "Identifier": return plain(node);
7621
- case "Literal": return !("regex" in node && node.regex);
7622
- case "TemplateLiteral":
7623
- case "BinaryExpression":
7624
- case "UnaryExpression": return true;
7625
- case "LogicalExpression": return isPrimitive(node.left, plain) && isPrimitive(node.right, plain);
7626
- case "ConditionalExpression": return isPrimitive(node.consequent, plain) && isPrimitive(node.alternate, plain);
7627
- case "TSAsExpression":
7628
- case "TSSatisfiesExpression":
7629
- case "TSNonNullExpression": return isPrimitive(node.expression, plain);
7630
- default: return false;
7631
- }
7632
- }
7633
7903
  /** True if an expression calls no code and, unless `members`, reads no property. */
7634
7904
  function isSafe(node, members) {
7635
7905
  if (UNSAFE_NODES.has(node.type)) return false;
@@ -7734,12 +8004,6 @@ const TYPE_DECLARATIONS = /* @__PURE__ */ new Set([
7734
8004
  "TSDeclareFunction",
7735
8005
  "TSModuleDeclaration"
7736
8006
  ]);
7737
- /** Expressions whose value is never a promise, as the memo of a list or a function. */
7738
- const NEVER_PROMISE = /* @__PURE__ */ new Set([
7739
- "ArrayExpression",
7740
- "ArrowFunctionExpression",
7741
- "FunctionExpression"
7742
- ]);
7743
8007
  /**
7744
8008
  * True for a memo whose value is never a promise in the browser, such as `count * 2`, an array or
7745
8009
  * a function. A memo with `await` inside is an async function, so its value is a promise whatever
@@ -7757,7 +8021,7 @@ const MARKUP_SITES = /* @__PURE__ */ new Set([
7757
8021
  ]);
7758
8022
  function isNeverPromise(declaration) {
7759
8023
  const node = declaration.site?.node;
7760
- return declaration.kind === "memo" && node !== void 0 && (isPrimitive(node) || NEVER_PROMISE.has(node.type));
8024
+ return declaration.kind === "memo" && node !== void 0 && neverPromise(node);
7761
8025
  }
7762
8026
  /**
7763
8027
  * True for a memo that can hold a promise in the browser: an `await` in it makes one, and others
@@ -8091,6 +8355,10 @@ var Emitter = class {
8091
8355
  this.braces.push({ kind: "control" });
8092
8356
  }
8093
8357
  }
8358
+ /** `svg` or `math` when the elements around `owner`, a body or children, put its markup there. */
8359
+ foreignAround(owner) {
8360
+ return foreignContext(this.file, owner);
8361
+ }
8094
8362
  /**
8095
8363
  * The return of a render function of the browser: its clone, its HTML, or an empty string
8096
8364
  * for a function with no markup, which is not HTML that the core must parse.
@@ -8511,8 +8779,21 @@ var Emitter = class {
8511
8779
  if (!this.options.functions && this.isFunctionStatement(statement)) continue;
8512
8780
  }
8513
8781
  let code = this.patch.slice(statement.start, statement.end);
8782
+ let partial = false;
8783
+ if (this.options.mode === "client" && statement.type === "VariableDeclaration") {
8784
+ const kept = [];
8785
+ for (const declarator of statement.declarations) {
8786
+ const declaration = declarator.id.type === "Identifier" ? scope.declarations.get(declarator.id.name) : void 0;
8787
+ if (!declaration || !this.plan.graph.unread.has(declaration)) kept.push(this.patch.slice(declarator.start, declarator.end));
8788
+ }
8789
+ if (kept.length === 0) continue;
8790
+ if (kept.length < statement.declarations.length) {
8791
+ code = `${statement.kind} ${kept.join(", ")};`;
8792
+ partial = true;
8793
+ }
8794
+ }
8514
8795
  if (index < lastAwait && statement.type === "VariableDeclaration") {
8515
- if (statement.kind === "const") code = `let${this.patch.slice(statement.start + 5, statement.end)}`;
8796
+ if (statement.kind === "const") code = partial ? `let${code.slice(5)}` : `let${this.patch.slice(statement.start + 5, statement.end)}`;
8516
8797
  for (const declaration of scope.declarations.values()) if (declaration.range.start >= statement.start && declaration.range.end <= statement.end) this.reassignable.add(declaration);
8517
8798
  }
8518
8799
  this.raw(code, statement.start);
@@ -8630,18 +8911,19 @@ var Emitter = class {
8630
8911
  }
8631
8912
  }
8632
8913
  /**
8633
- * In the browser, a memo that nothing reads has no slot, so no load takes its promise. Its
8634
- * rejection goes to the nearest `#try`, which is where a memo that throws sends its error. A
8635
- * memo that always gives a primitive, such as `count * 2`, is never a promise, unless it has
8636
- * `await` inside. `await memo` compiles to a plain read of the promise, which drops it, unless
8637
- * the read is the whole value of another memo, as in `$memo(await memo)`, which then holds the
8638
- * same promise.
8914
+ * In the browser, a memo that only `await` reads has no slot, so no load takes its promise.
8915
+ * The server waits at the `await` and throws the error there, so the rejection goes to the
8916
+ * nearest `#try`, which is where a memo that throws sends its error. A memo that always gives a
8917
+ * primitive, such as `count * 2`, is never a promise, unless it has `await` inside. `await memo`
8918
+ * compiles to a plain read of the promise, which drops it, unless the read is the whole value of
8919
+ * another memo, as in `$memo(await memo)`, which then holds the same promise. A memo that
8920
+ * nothing reads is not declared (`Graph.unread`), and neither is one that only such a memo reads.
8639
8921
  */
8640
8922
  watchUnreadMemos(statement, scope, splits) {
8641
8923
  const awaited = splits ? this.markupAwaits(scope) : [];
8642
8924
  for (const declarator of statement.declarations) {
8643
8925
  const declaration = declarator.id.type === "Identifier" ? scope.declarations.get(declarator.id.name) : void 0;
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)) {
8926
+ if (declaration && !awaited.includes(declaration) && (declaration.kind === "memo" || declaration.kind === "async-memo") && !this.plan.graph.unread.has(declaration) && declaration.reads.every((read) => read.site.kind === "memo" && this.plan.graph.unread.has(read.site.declaration) || 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)) {
8645
8927
  const target = this.scopeVar(instanceScope(this.plan, scope));
8646
8928
  this.line(`$$b.unreadMemo(${target}, ${declaration.name});`);
8647
8929
  }
@@ -8831,11 +9113,20 @@ var Emitter = class {
8831
9113
  const last = template.params.at(-1);
8832
9114
  const params = first && last ? copy(this.file.source, first.start, last.end) : "";
8833
9115
  const type = this.options.mode === "server" ? ": Promise<$$b.Raw>" : "";
8834
- this.line(`${this.async}function ${template.name}(${params})${type} {`);
9116
+ const scope = this.plan.bodyScopes.get(template.body);
9117
+ const call = this.options.mode === "client" && templateArgs(this.plan, this.file.source, scope);
9118
+ const name = call ? `${template.name}$` : template.name;
9119
+ if (call) {
9120
+ const own = call.names ? call.params : "...$$a";
9121
+ const given = call.names ? `[${call.names.join(", ")}]` : "$$a";
9122
+ const owner = this.scopeVar(instanceScope(this.plan, scope.parent));
9123
+ const ref = JSON.stringify(`${this.plan.id}#T${scope.id}`);
9124
+ this.line(`function ${template.name}(${own}) { return $$b.templateCall(${ref}, ${owner}, ${name}, ${given}); }`);
9125
+ }
9126
+ this.line(`${this.async}function ${name}(${params})${type} {`);
8835
9127
  this.line(`let $$html = '';`);
8836
9128
  this.atTopLevel(() => this.emitBody(template.body));
8837
9129
  this.flush();
8838
- const scope = this.plan.bodyScopes.get(template.body);
8839
9130
  const at = this.plan.scopes.get(scope).needsId ? `, ${this.scopeVar(scope)}` : "";
8840
9131
  this.line(`return $$b.raw($$html${at});`);
8841
9132
  this.close();
@@ -8945,9 +9236,9 @@ var Emitter = class {
8945
9236
  if (setter) return `${event}=$set:${this.plan.id}#${setter}`;
8946
9237
  return `${event}=$bind#${hops}.${slotIndex(this.plan, binding.declaration)}`;
8947
9238
  }
8948
- eventEntry({ event, modifiers, handler }) {
9239
+ eventEntry({ event, handler }) {
8949
9240
  const site = this.sitesByNode.get(handler.ast);
8950
- return `${[event, ...[.../* @__PURE__ */ new Set([...modifiers, ...site.modifiers ?? []])]].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
9241
+ return `${[event, ...[...new Set(site.modifiers ?? [])]].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
8951
9242
  }
8952
9243
  emitRef(target, attribute, anchor, when) {
8953
9244
  const declaration = this.refTargets.get(attribute);
@@ -9248,7 +9539,7 @@ var Emitter = class {
9248
9539
  this.line(`let $$html = '';`);
9249
9540
  this.atTopLevel(() => this.emitNodes(nodes, scope));
9250
9541
  this.flush();
9251
- const cloned = this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn);
9542
+ const cloned = this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn, node);
9252
9543
  this.line(this.returnLine(fn, cloned));
9253
9544
  this.close("});");
9254
9545
  return name;
@@ -9449,7 +9740,7 @@ var Emitter = class {
9449
9740
  this.headBlocks -= block.kind === "head" ? 1 : 0;
9450
9741
  this.html("<!--/P-->");
9451
9742
  this.flush();
9452
- const cloned = this.options.mode === "client" && this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn);
9743
+ const cloned = this.options.mode === "client" && this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn, block.body);
9453
9744
  this.line(cloned ? "return $$f;" : "return $$html;");
9454
9745
  this.close("})();");
9455
9746
  this.line(`${this.helper(block.kind === "head" ? "head" : "portal")}(${name});`);
@@ -9624,7 +9915,7 @@ var Emitter = class {
9624
9915
  this.line(`let $$html = '';`);
9625
9916
  this.splitBody(scope, content, () => {
9626
9917
  this.flush();
9627
- const cloned = this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn);
9918
+ const cloned = this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn, scope?.body);
9628
9919
  this.line(this.returnLine(fn, cloned));
9629
9920
  });
9630
9921
  this.close("};");
@@ -10127,6 +10418,36 @@ function renderImport(file, statement, names) {
10127
10418
  const target = source.endsWith(".brm") ? `${source}?brumate-render` : source;
10128
10419
  return `import ${parts.join(", ")} from ${JSON.stringify(target)};`;
10129
10420
  }
10421
+ /** The exports of the module script, from its declarations and its export lists. */
10422
+ function moduleExports(file, plan) {
10423
+ const result = [];
10424
+ for (const statement of file.moduleScript?.program.body ?? []) {
10425
+ if (statement.type !== "ExportNamedDeclaration" || statement.source) continue;
10426
+ if (statement.declaration) {
10427
+ for (const declaration of plan.graph.model.module.declarations.values()) if (declaration.kind === "module" && declaration.range.start >= statement.start && declaration.range.end <= statement.end) result.push({
10428
+ local: declaration.name,
10429
+ name: declaration.name
10430
+ });
10431
+ continue;
10432
+ }
10433
+ for (const specifier of statement.specifiers) {
10434
+ const local = file.source.slice(specifier.local.start, specifier.local.end);
10435
+ const name = file.source.slice(specifier.exported.start, specifier.exported.end);
10436
+ if (plan.graph.model.module.declarations.get(local)?.kind === "module") result.push({
10437
+ local,
10438
+ name
10439
+ });
10440
+ }
10441
+ }
10442
+ return result;
10443
+ }
10444
+ /** True if the render module imports names of the module script from the shared part. */
10445
+ function rendersModule(plan) {
10446
+ for (const site of plan.graph.model.sites) if (!SKIPPED_SITES.has(site.kind)) {
10447
+ for (const read of site.reads) if (read.declaration.kind === "module") return true;
10448
+ }
10449
+ return false;
10450
+ }
10130
10451
  /** Returns the module script for client code. Server functions become `rpc` stubs. */
10131
10452
  function clientModuleScript(file, plan) {
10132
10453
  const result = [];
@@ -10156,14 +10477,16 @@ function awaitsPromise(plan) {
10156
10477
  function generateRender(file, plan, getFill) {
10157
10478
  const model = plan.graph.model;
10158
10479
  const patch = new Patch(file.source);
10159
- addValueEdits(patch, file, model.sites, "client", void 0, void 0, model.component.id);
10480
+ addValueEdits(patch, file, model.sites, "render", void 0, void 0, model.component.id);
10160
10481
  const names = componentNames(file.children);
10161
10482
  for (const template of file.templates) bodyNames(template.body, names);
10162
10483
  for (const site of model.sites) if (!SKIPPED_SITES.has(site.kind)) for (const read of site.reads) names.add(read.declaration.name);
10163
- let usesModule = false;
10164
- for (const name of names) if (model.module.declarations.get(name)?.kind === "module") {
10165
- usesModule = true;
10166
- break;
10484
+ const moduleNames = [];
10485
+ const serverNames = [];
10486
+ for (const name of names) {
10487
+ const found = model.module.declarations.get(name);
10488
+ if (found?.kind === "module") moduleNames.push(name);
10489
+ else if (found?.kind === "server-function") serverNames.push(name);
10167
10490
  }
10168
10491
  const header = ["import * as $$b from 'brumate/client';"];
10169
10492
  const moduleBody = [];
@@ -10174,16 +10497,19 @@ function generateRender(file, plan, getFill) {
10174
10497
  for (const program of programs) {
10175
10498
  const isModule = program === file.moduleScript?.program;
10176
10499
  for (const statement of program.body) if (statement.type === "ImportDeclaration") {
10177
- let code;
10178
- if (isModule && usesModule) {
10179
- const own = /* @__PURE__ */ new Set();
10180
- for (const specifier of statement.specifiers) own.add(specifier.local.name);
10181
- code = renderImport(file, statement, own);
10182
- } else code = renderImport(file, statement, names);
10500
+ const code = renderImport(file, statement, names);
10183
10501
  if (code) header.push(code);
10184
10502
  } else if (!isModule && TYPE_DECLARATIONS.has(statement.type)) moduleBody.push(copy(file.source, statement.start, statement.end));
10185
10503
  }
10186
- if (usesModule) moduleBody.push(...clientModuleScript(file, plan));
10504
+ const exported = moduleNames.length > 0 ? moduleExports(file, plan) : [];
10505
+ const imports = new Set(moduleNames);
10506
+ for (const item of exported) imports.add(item.name);
10507
+ if (imports.size > 0) {
10508
+ const base = file.filename.split(/[\\/]/).pop();
10509
+ header.push(`import { ${[...imports].join(", ")} } from ${JSON.stringify(`./${base}?brumate-client&part=shared`)};`);
10510
+ }
10511
+ if (exported.length > 0) moduleBody.push(`export { ${exported.map((item) => item.name).join(", ")} };`);
10512
+ for (const name of serverNames) if (model.module.declarations.get(name)?.scope === model.module) moduleBody.push(`const ${name} = (...$$a) => $$b.rpc(${JSON.stringify(serverFunctionId(plan, name))}, $$a);`);
10187
10513
  for (const declaration of model.declarations) if (declaration.kind === "server-function" && declaration.scope !== model.module) {
10188
10514
  const ref = serverFunctionId(plan, declaration.name);
10189
10515
  moduleBody.push(`const ${declaration.name} = (...$$a) => $$b.rpc(${JSON.stringify(ref)}, $$a);`);
@@ -10318,6 +10644,8 @@ var Rewriter = class {
10318
10644
  shared;
10319
10645
  /** The sites of `$handler` calls, by call. */
10320
10646
  handlers = /* @__PURE__ */ new Map();
10647
+ /** The signals of `$searchParam` calls, by call. */
10648
+ searches = /* @__PURE__ */ new Map();
10321
10649
  /** The declarations of the names of `$bind` calls, by call. */
10322
10650
  bindings = /* @__PURE__ */ new Map();
10323
10651
  constructor(file, plan, diagnostics, shared) {
@@ -10326,6 +10654,7 @@ var Rewriter = class {
10326
10654
  this.diagnostics = diagnostics;
10327
10655
  this.shared = shared;
10328
10656
  for (const site of plan.graph.model.sites) if (site.handler) this.handlers.set(site.handler, site);
10657
+ for (const declaration of plan.graph.model.declarations) if (declaration.searchParam) this.searches.set(declaration.searchParam, declaration);
10329
10658
  for (const binding of plan.graph.model.bindings) this.bindings.set(binding.call, binding);
10330
10659
  }
10331
10660
  /**
@@ -10572,6 +10901,13 @@ var Rewriter = class {
10572
10901
  for (const argument of node.arguments) visit(argument);
10573
10902
  return;
10574
10903
  }
10904
+ const searched = this.searches.get(node);
10905
+ if (searched && node.arguments[0]) {
10906
+ const slot = slotIndex(this.plan, searched);
10907
+ patch.replace(node.start, node.arguments[0].start, `$$b.paramEffect(${path(searched)}, ${slot}, `);
10908
+ for (const argument of node.arguments) visit(argument);
10909
+ return;
10910
+ }
10575
10911
  if (node.callee.type === "Identifier" && node.callee.name === "$isBound" && !references.has(node.callee.start)) {
10576
10912
  const prop = node.arguments[0];
10577
10913
  const declaration = prop && references.get(prop.start)?.declaration;
@@ -10752,6 +11088,7 @@ var ClientGenerator = class {
10752
11088
  this.emitFunctions();
10753
11089
  this.emitRoots();
10754
11090
  this.part = "update";
11091
+ this.emitTemplateExports();
10755
11092
  this.emitUpdates();
10756
11093
  this.emitWindowStarts();
10757
11094
  this.emitRenders();
@@ -10963,7 +11300,7 @@ var ClientGenerator = class {
10963
11300
  if (item.kind === "import") names.add(item.name);
10964
11301
  if (item.kind === "function" && this.placement.get(item) === "shared" || item.kind === "module" && item.scope === this.model.module) shared.push(item.kind === "function" ? `${item.name}$` : item.name);
10965
11302
  }
10966
- const lines = ["import * as $$b from 'brumate/client';", ...this.importsFor(names, name === "update" || this.templateScopes(name))];
11303
+ const lines = ["import * as $$b from 'brumate/client';", ...this.importsFor(names, this.partScopes(name), name === "update")];
10967
11304
  if (shared.length > 0) lines.push(`import { ${[...new Set(shared)].join(", ")} } from ${JSON.stringify(this.partPath("shared"))};`);
10968
11305
  lines.push("", ...this.serverStubs([name]), ...this.out.get(name) ?? [], "");
10969
11306
  return lines.join("\n");
@@ -10973,7 +11310,7 @@ var ClientGenerator = class {
10973
11310
  const imports = /* @__PURE__ */ new Set();
10974
11311
  for (const name of names) for (const item of this.reads(this.partSites(name))) if (item.kind === "import") imports.add(item.name);
10975
11312
  const scopes = [...this.renderedScopes()];
10976
- for (const name of names) scopes.push(...this.templateScopes(name));
11313
+ for (const name of names) for (const scope of this.partScopes(name)) if (!scopes.includes(scope)) scopes.push(scope);
10977
11314
  const lines = [
10978
11315
  "import * as $$b from 'brumate/client';",
10979
11316
  ...this.importsFor(imports, scopes, names.includes("update")),
@@ -10993,9 +11330,7 @@ var ClientGenerator = class {
10993
11330
  for (const statement of this.file.moduleScript.program.body) if (statement.type === "ImportDeclaration" && !isMacroImport(statement)) lines.push(copy(this.file.source, statement.start, statement.end));
10994
11331
  lines.push(...clientModuleScript(this.file, this.plan));
10995
11332
  const exported = /* @__PURE__ */ new Set();
10996
- for (const statement of this.file.moduleScript.program.body) if (statement.type === "ExportNamedDeclaration" && statement.declaration) {
10997
- for (const declaration of this.model.module.declarations.values()) if (declaration.range.start >= statement.start && declaration.range.end <= statement.end) exported.add(declaration.name);
10998
- }
11333
+ for (const item of moduleExports(this.file, this.plan)) if (item.local === item.name) exported.add(item.name);
10999
11334
  const rest = [];
11000
11335
  for (const declaration of this.model.module.declarations.values()) if (declaration.kind === "module" && !exported.has(declaration.name)) rest.push(declaration.name);
11001
11336
  if (rest.length > 0) lines.push(`export { ${rest.join(", ")} };`);
@@ -11023,6 +11358,7 @@ var ClientGenerator = class {
11023
11358
  return reads;
11024
11359
  }
11025
11360
  usesModuleScript() {
11361
+ if (rendersModule(this.plan)) return true;
11026
11362
  for (const declaration of this.clientReads()) if (declaration.kind === "module") return true;
11027
11363
  return false;
11028
11364
  }
@@ -11041,6 +11377,23 @@ var ClientGenerator = class {
11041
11377
  }
11042
11378
  return result;
11043
11379
  }
11380
+ /**
11381
+ * The scopes whose components and imports a part needs: the scopes that the update part
11382
+ * renders, the templates of a template part, and the templates that the code of the part
11383
+ * copies into itself, such as a call `row(item)` in an update.
11384
+ */
11385
+ partScopes(part) {
11386
+ const result = part === "update" ? this.renderedScopes() : this.templateScopes(part);
11387
+ for (const site of this.partSites(part)) {
11388
+ const used = [...site.calls];
11389
+ for (const read of site.reads) used.push(read.declaration);
11390
+ for (const callee of used) {
11391
+ const template = callee.kind === "template" ? this.findTemplateScope(callee) : void 0;
11392
+ for (const item of template ? this.inside(template) : []) if (!result.includes(item)) result.push(item);
11393
+ }
11394
+ }
11395
+ return result;
11396
+ }
11044
11397
  /** Every scope that a render function of this module renders, including templates. */
11045
11398
  renderedScopes() {
11046
11399
  const result = /* @__PURE__ */ new Set();
@@ -11217,8 +11570,7 @@ var ClientGenerator = class {
11217
11570
  case "memo": {
11218
11571
  const slot = slotIndex(this.plan, node.declaration);
11219
11572
  if (slot !== -1) {
11220
- const code = site.awaits ? `(async () => (${expression()}))()` : expression();
11221
- const value = site.node.type === "ObjectExpression" ? `(${code})` : code;
11573
+ const value = arrowBody(site.awaits ? `(async () => (${expression()}))()` : expression(), this.file.source, site.node.start);
11222
11574
  const timing = node.declaration.timing;
11223
11575
  const call = timing ? `$$b.timed($$s, ${slot}, ${timing.ms}, ${timing.kind === "throttled"}, () => ${value})` : `$$b.memo($$s, ${slot}, () => ${value})`;
11224
11576
  this.emit(`export function ${name("m")}($$s) {\n ${call};\n}`);
@@ -11351,7 +11703,7 @@ var ClientGenerator = class {
11351
11703
  }
11352
11704
  }
11353
11705
  if (attribute.kind === "event" && site) {
11354
- const all = [.../* @__PURE__ */ new Set([...attribute.modifiers, ...site.modifiers ?? []])];
11706
+ const all = [...new Set(site.modifiers ?? [])];
11355
11707
  const entry = `${[attribute.event, ...all].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}@`;
11356
11708
  entries.push(`${JSON.stringify(entry)} + $$s.id`);
11357
11709
  }
@@ -11593,8 +11945,8 @@ var ClientGenerator = class {
11593
11945
  * Replaces the one `$$html +=` line of a render with a clone of a template and the writes on
11594
11946
  * its elements. Returns false when the markup needs HTML.
11595
11947
  */
11596
- cloneRender(emitter) {
11597
- return cloneLines(emitter, (code) => this.hoist(code));
11948
+ cloneRender(emitter, body) {
11949
+ return cloneLines(emitter, (code) => this.hoist(code), 0, body);
11598
11950
  }
11599
11951
  /**
11600
11952
  * The code of the render function of a body. With `fill`, the body fills its nested blocks
@@ -11632,7 +11984,7 @@ var ClientGenerator = class {
11632
11984
  else emitter.emitBody(body);
11633
11985
  }, () => {
11634
11986
  emitter.flush();
11635
- cloned = block.kind === "if" || block.kind === "for" || block.kind === "loading" ? this.cloneRender(emitter) : false;
11987
+ cloned = this.cloneRender(emitter, body);
11636
11988
  emitter.line(emitter.returnLine(0, cloned));
11637
11989
  });
11638
11990
  if (fill && !cloned) return;
@@ -11760,7 +12112,7 @@ var ClientGenerator = class {
11760
12112
  for (const template of this.declared(inside)) if (template.kind === "template") emitter.emitTemplate(template.template);
11761
12113
  emitter.emitChildrenBody(node, scope);
11762
12114
  emitter.flush();
11763
- const cloned = cloneLines(emitter, (code) => this.hoist(code));
12115
+ const cloned = cloneLines(emitter, (code) => this.hoist(code), 0, node);
11764
12116
  emitter.line(emitter.returnLine(0, cloned));
11765
12117
  emitter.close();
11766
12118
  this.emit(emitter.lines.join("\n"));
@@ -11782,21 +12134,23 @@ var ClientGenerator = class {
11782
12134
  break;
11783
12135
  }
11784
12136
  const scope = callee && this.findTemplateScope(callee);
11785
- const template = scope?.template;
11786
- if (!scope || !template) return;
11787
- const first = template.params[0];
11788
- const last = template.params.at(-1);
11789
- const params = first && last ? copy(this.file.source, first.start, last.end) : "";
11790
- const pairs = [];
11791
- for (const declaration of scope.declarations.values()) {
11792
- if (declaration.kind !== "template-param") continue;
11793
- const slot = slotIndex(this.plan, declaration);
11794
- if (slot === -1) return;
11795
- pairs.push(`[${slot}, ${declaration.name}]`);
11796
- }
11797
- this.emit(`export const ${symbol}a = (${params}) => [${pairs.join(", ")}];`);
12137
+ if (scope) this.emitArgsExports(symbol, scope);
12138
+ }
12139
+ /** The `a` and `k` exports of a template, which `symbol` names. */
12140
+ emitArgsExports(symbol, scope) {
12141
+ const args = templateArgs(this.plan, this.file.source, scope);
12142
+ if (!args) return;
12143
+ this.emit(`export const ${symbol}a = (${args.exported}) => [${args.pairs.join(", ")}];`);
11798
12144
  this.emit(`export const ${symbol}k = ${scope.id};`);
11799
12145
  }
12146
+ /**
12147
+ * The exports of the templates of the file that a call in markup can update in place: the
12148
+ * template is `T` and its scope ID, as `templateCall` of the template's code names it.
12149
+ */
12150
+ emitTemplateExports() {
12151
+ this.part = "update";
12152
+ for (const scope of this.model.scopes) if (scope.template) this.emitArgsExports(`T${scope.id}`, scope);
12153
+ }
11800
12154
  withTemplates(site, code) {
11801
12155
  const templates = [];
11802
12156
  const used = [...site.calls];
@@ -12392,4 +12746,4 @@ function inspect(source, options = {}) {
12392
12746
  //#endregion
12393
12747
  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 };
12394
12748
 
12395
- //# sourceMappingURL=inspect-BLPt-dZZ.js.map
12749
+ //# sourceMappingURL=inspect-Q5W0A66e.js.map