brumate 0.6.0 → 0.6.2

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 (47) hide show
  1. package/dist/{boot-CMvhoWRu.d.ts → boot-DkbcqdUz.d.ts} +2 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/{client-eVI8Wc95.js → client-C3vRNuLi.js} +186 -78
  4. package/dist/client-C3vRNuLi.js.map +1 -0
  5. package/dist/{client-C4kNKGwH.d.ts → client-CqGDbWd_.d.ts} +29 -5
  6. package/dist/{defer-pKO0S6UT.js → defer-M18UKyfG.js} +2 -2
  7. package/dist/{defer-pKO0S6UT.js.map → defer-M18UKyfG.js.map} +1 -1
  8. package/dist/{devtools-DqqqdI4b.js → devtools-D9Q7a41M.js} +34 -24
  9. package/dist/devtools-D9Q7a41M.js.map +1 -0
  10. package/dist/{devtools-panel--GYjFZ35.js → devtools-panel-DTQtljeA.js} +2 -2
  11. package/dist/{devtools-panel--GYjFZ35.js.map → devtools-panel-DTQtljeA.js.map} +1 -1
  12. package/dist/{files-CR-V05xd.js → files-DtDH5AR4.js} +2 -2
  13. package/dist/{files-CR-V05xd.js.map → files-DtDH5AR4.js.map} +1 -1
  14. package/dist/index.d.ts +5 -0
  15. package/dist/index.js +1 -1
  16. package/dist/{inspect-ddfGeww0.js → inspect-Bonq6EJO.js} +338 -69
  17. package/dist/inspect-Bonq6EJO.js.map +1 -0
  18. package/dist/{loader-CQkAXO0g.js → loader-C-S3yzep.js} +4 -4
  19. package/dist/{loader-CQkAXO0g.js.map → loader-C-S3yzep.js.map} +1 -1
  20. package/dist/{navigate-BcV1qkkx.js → navigate-r23FFR6e.js} +5 -2
  21. package/dist/{navigate-BcV1qkkx.js.map → navigate-r23FFR6e.js.map} +1 -1
  22. package/dist/{rpc-BgYnfg_a.js → rpc-C_znDZ_w.js} +2 -2
  23. package/dist/{rpc-BgYnfg_a.js.map → rpc-C_znDZ_w.js.map} +1 -1
  24. package/dist/runtime/bundles.d.ts +1 -1
  25. package/dist/runtime/client.d.ts +2 -2
  26. package/dist/runtime/client.js +2 -2
  27. package/dist/runtime/devtools.d.ts +14 -1
  28. package/dist/runtime/devtools.js +2 -2
  29. package/dist/runtime/hot.d.ts +1 -1
  30. package/dist/runtime/loader.d.ts +2 -2
  31. package/dist/runtime/loader.js +2 -2
  32. package/dist/runtime/static-loader.d.ts +2 -2
  33. package/dist/runtime/static-loader.js +1 -1
  34. package/dist/runtime/testing.d.ts +1 -1
  35. package/dist/runtime/testing.js +1 -1
  36. package/dist/{static-loader-DCxASuzA.js → static-loader-Bt2WDkY1.js} +2 -2
  37. package/dist/{static-loader-DCxASuzA.js.map → static-loader-Bt2WDkY1.js.map} +1 -1
  38. package/dist/{static-loader-CGthkX0s.d.ts → static-loader-DysAET-w.d.ts} +2 -2
  39. package/dist/vite.d.ts +1 -1
  40. package/dist/vite.js +3 -3
  41. package/dist/vite.js.map +1 -1
  42. package/elements.d.ts +8 -2
  43. package/package.json +1 -1
  44. package/skills/brumate/references/errors.md +14 -0
  45. package/dist/client-eVI8Wc95.js.map +0 -1
  46. package/dist/devtools-DqqqdI4b.js.map +0 -1
  47. package/dist/inspect-ddfGeww0.js.map +0 -1
@@ -1935,6 +1935,7 @@ const SYNTAX = [
1935
1935
  entry("BRM021", "Expected an attribute name", "A tag has a character where an attribute name belongs.", "<input disabled>"),
1936
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>"),
1937
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>"),
1938
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}"),
1939
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>"),
1940
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}"),
@@ -2315,6 +2316,18 @@ function callsRefreshed(declaration) {
2315
2316
  for (const callee of declaration.site?.calls ?? []) if (callee.refreshed) return true;
2316
2317
  return false;
2317
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
+ }
2318
2331
  /** True if the declaration is referenced from one of the scopes. */
2319
2332
  function hasRefIn(declaration, scopes) {
2320
2333
  for (const ref of declaration.refs) if (scopes.has(ref.scope)) return true;
@@ -2442,8 +2455,9 @@ function isFunctionValue(site) {
2442
2455
  }
2443
2456
  if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") return true;
2444
2457
  if (node.type === "Identifier") {
2445
- const kind = lookup(site.scope, node.name)?.kind;
2446
- return kind === "function" || kind === "server-function" || kind === "template";
2458
+ const declaration = lookup(site.scope, node.name);
2459
+ const kind = declaration?.kind;
2460
+ return kind === "function" || kind === "server-function" || kind === "template" || kind === "import" && declaration?.callable === true;
2447
2461
  }
2448
2462
  return false;
2449
2463
  }
@@ -2557,7 +2571,7 @@ function buildGraph(model, options = {}) {
2557
2571
  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);
2558
2572
  for (const [declaration, node] of declarationNodes) {
2559
2573
  if (live.has(node)) continue;
2560
- 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);
2574
+ 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);
2561
2575
  }
2562
2576
  for (let propagated = true; propagated;) {
2563
2577
  propagated = false;
@@ -2722,6 +2736,31 @@ function camelEventName(attribute) {
2722
2736
  const camel = BY_LOWER.get(attribute.toLowerCase());
2723
2737
  return camel === attribute ? void 0 : camel;
2724
2738
  }
2739
+ const NO_HANDLER = /* @__PURE__ */ new Map([
2740
+ ["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')"],
2741
+ ["domactivate", "The event is deprecated. Write onClick"],
2742
+ ["domfocusin", "The event is deprecated. Write onFocusIn"],
2743
+ ["domfocusout", "The event is deprecated. Write onFocusOut"],
2744
+ ["dommousescroll", "The event is not standard. Write onWheel"],
2745
+ ["mozmousepixelscroll", "The event is not standard. Write onWheel"],
2746
+ ["webkitanimationstart", "The browser fires the prefixed name only. Write onAnimationStart"],
2747
+ ["webkitanimationiteration", "The browser fires the prefixed name only. Write onAnimationIteration"],
2748
+ ["webkitanimationend", "The browser fires the prefixed name only. Write onAnimationEnd"],
2749
+ ["webkittransitionend", "The browser fires the prefixed name only. Write onTransitionEnd"]
2750
+ ]);
2751
+ for (const mutation of [
2752
+ "DOMAttrModified",
2753
+ "DOMCharacterDataModified",
2754
+ "DOMNodeInserted",
2755
+ "DOMNodeInsertedIntoDocument",
2756
+ "DOMNodeRemoved",
2757
+ "DOMNodeRemovedFromDocument",
2758
+ "DOMSubtreeModified"
2759
+ ]) NO_HANDLER.set(mutation.toLowerCase(), "The event is removed. Observe the DOM with a MutationObserver");
2760
+ /** What to write instead of a handler for an event that has none, such as `onDOMContentLoaded`. */
2761
+ function noHandlerFix(attribute) {
2762
+ return NO_HANDLER.get(attribute.slice(2).toLowerCase());
2763
+ }
2725
2764
  //#endregion
2726
2765
  //#region src/scan.ts
2727
2766
  function isWhitespace(char) {
@@ -3222,8 +3261,11 @@ var Parser = class {
3222
3261
  }
3223
3262
  /** A handler of an element is written in camel case: `onKeyDown`, not `onKeydown`. */
3224
3263
  checkEventName(name, owner, start) {
3225
- const camel = owner === "component" || owner === "dynamic" ? void 0 : camelEventName(name);
3264
+ if (owner === "component" || owner === "dynamic") return;
3265
+ const camel = camelEventName(name);
3226
3266
  if (camel) this.fail(`"${name}" is not an event name. Write "${camel}"`, start);
3267
+ const fix = noHandlerFix(name);
3268
+ if (fix) this.fail(`"${name}" cannot be a handler. ${fix}`, start);
3227
3269
  }
3228
3270
  parseAttribute(owner) {
3229
3271
  const start = this.pos;
@@ -4758,6 +4800,81 @@ function parseModule(module) {
4758
4800
  functions
4759
4801
  };
4760
4802
  }
4803
+ /**
4804
+ * True when the export `name` of the module at `specifier` can be a function: a function that
4805
+ * the module exports, or an export of a module that the compiler cannot read, such as one of a
4806
+ * package. A value that the module declares, a component, a module of reactive logic and a
4807
+ * module that does not parse are not.
4808
+ */
4809
+ function mayExportFunction(specifier, name, importer, resolve, seen = /* @__PURE__ */ new Set()) {
4810
+ if (/\.brm($|\?)/.test(specifier) || isReactiveModule(specifier)) return false;
4811
+ const module = resolve(specifier, importer);
4812
+ if (!module) return true;
4813
+ if (seen.has(module.path)) return false;
4814
+ seen.add(module.path);
4815
+ const result = parseSync(module.path, module.source, {
4816
+ lang: "ts",
4817
+ preserveParens: false
4818
+ });
4819
+ if (result.errors.length > 0) return false;
4820
+ const functions = /* @__PURE__ */ new Set();
4821
+ const values = /* @__PURE__ */ new Set();
4822
+ const imports = /* @__PURE__ */ new Map();
4823
+ const declare = (node) => {
4824
+ if (node.type === "FunctionDeclaration" && node.id) functions.add(node.id.name);
4825
+ else if (node.type === "VariableDeclaration") for (const declarator of node.declarations) {
4826
+ const init = declarator.init;
4827
+ const isFunction = init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression";
4828
+ for (const id of getPatternNames(declarator.id)) (isFunction && declarator.id.type === "Identifier" ? functions : values).add(id.name);
4829
+ }
4830
+ };
4831
+ for (const statement of result.program.body) if (statement.type === "ImportDeclaration") for (const specifier of statement.specifiers) {
4832
+ let imported = "*";
4833
+ if (specifier.type === "ImportDefaultSpecifier") imported = "default";
4834
+ else if (specifier.type === "ImportSpecifier") imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
4835
+ imports.set(specifier.local.name, {
4836
+ specifier: statement.source.value,
4837
+ imported
4838
+ });
4839
+ }
4840
+ else if ((statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") && statement.declaration) declare(statement.declaration);
4841
+ else declare(statement);
4842
+ const local = (localName) => {
4843
+ if (functions.has(localName)) return true;
4844
+ const found = imports.get(localName);
4845
+ if (found && found.imported !== "*") return mayExportFunction(found.specifier, found.imported, module.path, resolve, seen);
4846
+ return false;
4847
+ };
4848
+ const stars = [];
4849
+ for (const statement of result.program.body) {
4850
+ if (statement.type === "ExportDefaultDeclaration") {
4851
+ if (name !== "default") continue;
4852
+ const declaration = statement.declaration;
4853
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ArrowFunctionExpression" || declaration.type === "FunctionExpression") return true;
4854
+ return declaration.type === "Identifier" && local(declaration.name);
4855
+ }
4856
+ if (statement.type === "ExportAllDeclaration") {
4857
+ if (!statement.exported) stars.push(statement.source.value);
4858
+ continue;
4859
+ }
4860
+ if (statement.type !== "ExportNamedDeclaration") continue;
4861
+ if (statement.declaration) {
4862
+ const declaration = statement.declaration;
4863
+ if (declaration.type === "FunctionDeclaration" && declaration.id?.name === name) return true;
4864
+ if (declaration.type === "VariableDeclaration") {
4865
+ for (const declarator of declaration.declarations) for (const id of getPatternNames(declarator.id)) if (id.name === name) return functions.has(name);
4866
+ }
4867
+ continue;
4868
+ }
4869
+ for (const specifier of statement.specifiers) {
4870
+ if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) !== name) continue;
4871
+ const localName = specifier.local.type === "Identifier" ? specifier.local.name : specifier.local.value;
4872
+ return statement.source ? mayExportFunction(statement.source.value, localName, module.path, resolve, seen) : local(localName);
4873
+ }
4874
+ }
4875
+ for (const star of stars) if (mayExportFunction(star, name, module.path, resolve, seen)) return true;
4876
+ return false;
4877
+ }
4761
4878
  /** Joins and normalizes paths with `/`. */
4762
4879
  function normalize(path) {
4763
4880
  const parts = [];
@@ -5221,6 +5338,38 @@ function expandModules(file, path, resolve) {
5221
5338
  };
5222
5339
  }
5223
5340
  //#endregion
5341
+ //#region src/codegen/primitive.ts
5342
+ /**
5343
+ * True if an expression always gives a primitive, so it is never a promise
5344
+ * or an async iterable. A name is a primitive when `plain` says that it reads
5345
+ * a declaration that holds one.
5346
+ */
5347
+ function isPrimitive(node, plain = () => false) {
5348
+ switch (node.type) {
5349
+ case "Identifier": return plain(node);
5350
+ case "Literal": return !("regex" in node && node.regex);
5351
+ case "TemplateLiteral":
5352
+ case "BinaryExpression":
5353
+ case "UnaryExpression": return true;
5354
+ case "LogicalExpression": return isPrimitive(node.left, plain) && isPrimitive(node.right, plain);
5355
+ case "ConditionalExpression": return isPrimitive(node.consequent, plain) && isPrimitive(node.alternate, plain);
5356
+ case "TSAsExpression":
5357
+ case "TSSatisfiesExpression":
5358
+ case "TSNonNullExpression": return isPrimitive(node.expression, plain);
5359
+ default: return false;
5360
+ }
5361
+ }
5362
+ /** Expressions whose value is never a promise, as the memo of a list or a function. */
5363
+ const NEVER_PROMISE = /* @__PURE__ */ new Set([
5364
+ "ArrayExpression",
5365
+ "ArrowFunctionExpression",
5366
+ "FunctionExpression"
5367
+ ]);
5368
+ /** True for an expression that gives a primitive, an array or a function, never a promise. */
5369
+ function neverPromise(node) {
5370
+ return isPrimitive(node) || NEVER_PROMISE.has(node.type);
5371
+ }
5372
+ //#endregion
5224
5373
  //#region src/codegen/patch.ts
5225
5374
  /** Rewrites ranges of the source with edits that do not overlap. */
5226
5375
  var Patch = class {
@@ -5268,6 +5417,16 @@ const MEMOS = /* @__PURE__ */ new Set([
5268
5417
  "$debounced",
5269
5418
  "$throttled"
5270
5419
  ]);
5420
+ /**
5421
+ * The code of an arrow function body, given the source offset where the user's expression starts.
5422
+ * An expression that starts with `{` is wrapped in parentheses, or the arrow reads it as a block.
5423
+ * This covers an object literal under `as`, `satisfies`, `!` and a `<T>` cast, and a sequence or
5424
+ * member access that starts with one. The source is checked, not the code, because the code can
5425
+ * start with a marker of the compiler.
5426
+ */
5427
+ function arrowBody(code, source, start) {
5428
+ return source[start] === "{" ? `(${code})` : code;
5429
+ }
5271
5430
  function promiseName(name) {
5272
5431
  return `$$p_${name}`;
5273
5432
  }
@@ -5339,11 +5498,18 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
5339
5498
  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")) {
5340
5499
  const range = read.await ?? read.range;
5341
5500
  const key = shorthands.has(range.start) ? `${read.declaration.name}: ` : "";
5342
- patch.replace(range.start, range.end, `${key}$$b.read(${promiseName(read.declaration.name)})`);
5501
+ patch.replace(range.start, range.end, mode === "render" ? `${key}$$b.readMemo(${read.declaration.name})` : `${key}$$b.read(${promiseName(read.declaration.name)})`);
5343
5502
  replaced.add(read);
5344
5503
  replacedAt.add(range.start);
5345
5504
  }
5346
5505
  }
5506
+ if (mode === "render") {
5507
+ const held = /* @__PURE__ */ new Set();
5508
+ for (const site of sites) if (site.kind === "memo" && site.declaration && !inline.has(site.declaration)) {
5509
+ if (site.awaits || !neverPromise(site.node)) held.add(site.declaration);
5510
+ }
5511
+ for (const site of sites) readMemos(site, site.node, site.declaration, held);
5512
+ }
5347
5513
  if (mode === "server") {
5348
5514
  for (const site of sites) if (site.kind === "function") readMemos(site, site.node);
5349
5515
  if (lazy.size > 0) {
@@ -5420,6 +5586,9 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
5420
5586
  readMemos(site, argument, declaration);
5421
5587
  patch.replace(node.start, argument.start, site.awaits ? "$$b.memo(async () => (" : "$$b.memo(() => (");
5422
5588
  patch.replace(argument.end, node.end, `), $$ctx, ${JSON.stringify(declaration.name)})`);
5589
+ } else if (mode === "render" && declaration && (site.awaits || !neverPromise(argument))) {
5590
+ patch.replace(node.start, argument.start, site.awaits ? "$$b.renderMemo(async () => (" : "$$b.renderMemo(() => (");
5591
+ patch.replace(argument.end, node.end, "))");
5423
5592
  } else if (site?.awaits) {
5424
5593
  patch.replace(node.start, argument.start, "(async () => (");
5425
5594
  patch.replace(argument.end, node.end, "))()");
@@ -6688,7 +6857,8 @@ const ATTRIBUTE = /^\$\$b\.attribute\(("(?:[^"\\]|\\.)*"), ([\s\S]*)\)$/;
6688
6857
  const CLASS_TOKEN = /^\(\(([\s\S]*)\) \? " ([^"\\&<>]+)" : ""\)$/;
6689
6858
  /**
6690
6859
  * The static classes of a `class` with code in its quotes, and the calls that add the classes
6691
- * that conditions add, when each piece of code is such a condition. `parts` are the parts of
6860
+ * that conditions add, when each piece of code is such a condition and no static class follows
6861
+ * one, so the classes keep their order. `parts` are the parts of
6692
6862
  * the value after its static `prefix`, up to its closing quote.
6693
6863
  */
6694
6864
  function classTokens(parts, prefix) {
@@ -6696,6 +6866,7 @@ function classTokens(parts, prefix) {
6696
6866
  const calls = [];
6697
6867
  for (const part of parts) {
6698
6868
  if ("static" in part) {
6869
+ if (calls.length > 0 && part.static.trim() !== "") return;
6699
6870
  text += part.static;
6700
6871
  continue;
6701
6872
  }
@@ -7508,6 +7679,50 @@ function scopePath(plan, base, from, target) {
7508
7679
  }
7509
7680
  return expression;
7510
7681
  }
7682
+ /**
7683
+ * The parameters of a template of the file, and the `[slot, value]` pairs of its arguments, so a
7684
+ * call that comes again writes its new arguments into the scope that it rendered. `params` are
7685
+ * the parameters as written, `exported` have no default values (the call passes the values with
7686
+ * them), and `names` are the arguments when each parameter is a name and one has a default.
7687
+ * Nothing if the template has no scope of its own, or a destructured parameter has a default
7688
+ * value: it then renders again. An argument that no slot holds is never read in the browser.
7689
+ */
7690
+ function templateArgs(plan, source, scope) {
7691
+ const template = scope.template;
7692
+ if (!template || !plan.scopes.get(scope)?.needsId) return;
7693
+ const first = template.params[0];
7694
+ const last = template.params.at(-1);
7695
+ const params = first && last ? copy(source, first.start, last.end) : "";
7696
+ const exported = [];
7697
+ const names = [];
7698
+ let simple = true;
7699
+ let defaults = false;
7700
+ for (const param of template.params) {
7701
+ const target = param.type === "AssignmentPattern" ? param.left : param;
7702
+ defaults ||= target !== param;
7703
+ if (target.type === "Identifier") names.push(target.name);
7704
+ else simple = false;
7705
+ if (target.type !== "Identifier" && hasDefault(target)) return;
7706
+ exported.push(copy(source, target.start, target.end));
7707
+ }
7708
+ const pairs = [];
7709
+ for (const declaration of scope.declarations.values()) {
7710
+ if (declaration.kind !== "template-param") continue;
7711
+ const slot = slotIndex(plan, declaration);
7712
+ if (slot !== -1) pairs.push(`[${slot}, ${declaration.name}]`);
7713
+ }
7714
+ return {
7715
+ params,
7716
+ exported: exported.join(", "),
7717
+ names: simple && defaults ? names : void 0,
7718
+ pairs
7719
+ };
7720
+ }
7721
+ function hasDefault(node) {
7722
+ if (node.type === "AssignmentPattern") return true;
7723
+ for (const [, child] of children(node)) if (hasDefault(child)) return true;
7724
+ return false;
7725
+ }
7511
7726
  /** Returns the slot index of a declaration, or -1. */
7512
7727
  function slotIndex(plan, declaration) {
7513
7728
  return plan.scopes.get(declaration.scope)?.slots.indexOf(declaration) ?? -1;
@@ -7761,26 +7976,6 @@ const UNSAFE_NODES = /* @__PURE__ */ new Set([
7761
7976
  "ArrowFunctionExpression",
7762
7977
  "ClassExpression"
7763
7978
  ]);
7764
- /**
7765
- * True if an expression always gives a primitive, so it is never a promise
7766
- * or an async iterable. A name is a primitive when `plain` says that it reads
7767
- * a declaration that holds one.
7768
- */
7769
- function isPrimitive(node, plain = () => false) {
7770
- switch (node.type) {
7771
- case "Identifier": return plain(node);
7772
- case "Literal": return !("regex" in node && node.regex);
7773
- case "TemplateLiteral":
7774
- case "BinaryExpression":
7775
- case "UnaryExpression": return true;
7776
- case "LogicalExpression": return isPrimitive(node.left, plain) && isPrimitive(node.right, plain);
7777
- case "ConditionalExpression": return isPrimitive(node.consequent, plain) && isPrimitive(node.alternate, plain);
7778
- case "TSAsExpression":
7779
- case "TSSatisfiesExpression":
7780
- case "TSNonNullExpression": return isPrimitive(node.expression, plain);
7781
- default: return false;
7782
- }
7783
- }
7784
7979
  /** True if an expression calls no code and, unless `members`, reads no property. */
7785
7980
  function isSafe(node, members) {
7786
7981
  if (UNSAFE_NODES.has(node.type)) return false;
@@ -7885,12 +8080,6 @@ const TYPE_DECLARATIONS = /* @__PURE__ */ new Set([
7885
8080
  "TSDeclareFunction",
7886
8081
  "TSModuleDeclaration"
7887
8082
  ]);
7888
- /** Expressions whose value is never a promise, as the memo of a list or a function. */
7889
- const NEVER_PROMISE = /* @__PURE__ */ new Set([
7890
- "ArrayExpression",
7891
- "ArrowFunctionExpression",
7892
- "FunctionExpression"
7893
- ]);
7894
8083
  /**
7895
8084
  * True for a memo whose value is never a promise in the browser, such as `count * 2`, an array or
7896
8085
  * a function. A memo with `await` inside is an async function, so its value is a promise whatever
@@ -7908,7 +8097,7 @@ const MARKUP_SITES = /* @__PURE__ */ new Set([
7908
8097
  ]);
7909
8098
  function isNeverPromise(declaration) {
7910
8099
  const node = declaration.site?.node;
7911
- return declaration.kind === "memo" && node !== void 0 && (isPrimitive(node) || NEVER_PROMISE.has(node.type));
8100
+ return declaration.kind === "memo" && node !== void 0 && neverPromise(node);
7912
8101
  }
7913
8102
  /**
7914
8103
  * True for a memo that can hold a promise in the browser: an `await` in it makes one, and others
@@ -9000,11 +9189,20 @@ var Emitter = class {
9000
9189
  const last = template.params.at(-1);
9001
9190
  const params = first && last ? copy(this.file.source, first.start, last.end) : "";
9002
9191
  const type = this.options.mode === "server" ? ": Promise<$$b.Raw>" : "";
9003
- this.line(`${this.async}function ${template.name}(${params})${type} {`);
9192
+ const scope = this.plan.bodyScopes.get(template.body);
9193
+ const call = this.options.mode === "client" && templateArgs(this.plan, this.file.source, scope);
9194
+ const name = call ? `${template.name}$` : template.name;
9195
+ if (call) {
9196
+ const own = call.names ? call.params : "...$$a";
9197
+ const given = call.names ? `[${call.names.join(", ")}]` : "$$a";
9198
+ const owner = this.scopeVar(instanceScope(this.plan, scope.parent));
9199
+ const ref = JSON.stringify(`${this.plan.id}#T${scope.id}`);
9200
+ this.line(`function ${template.name}(${own}) { return $$b.templateCall(${ref}, ${owner}, ${name}, ${given}); }`);
9201
+ }
9202
+ this.line(`${this.async}function ${name}(${params})${type} {`);
9004
9203
  this.line(`let $$html = '';`);
9005
9204
  this.atTopLevel(() => this.emitBody(template.body));
9006
9205
  this.flush();
9007
- const scope = this.plan.bodyScopes.get(template.body);
9008
9206
  const at = this.plan.scopes.get(scope).needsId ? `, ${this.scopeVar(scope)}` : "";
9009
9207
  this.line(`return $$b.raw($$html${at});`);
9010
9208
  this.close();
@@ -9512,7 +9710,8 @@ var Emitter = class {
9512
9710
  const symbol = site && this.plan.symbols.get(site);
9513
9711
  if (symbol) {
9514
9712
  const instance = this.scopeVar(instanceScope(this.plan, scope));
9515
- return `${this.helper("fn")}(${code}, ${JSON.stringify(`${this.plan.id}#${symbol}`)}, ${instance})`;
9713
+ const copy = this.options.mode === "server" && isImported(expression.ast, scope) ? ", []" : "";
9714
+ return `${this.helper("fn")}(${code}, ${JSON.stringify(`${this.plan.id}#${symbol}`)}, ${instance}${copy})`;
9516
9715
  }
9517
9716
  return code;
9518
9717
  }
@@ -10125,6 +10324,11 @@ function classText(classes) {
10125
10324
  function variableValue(variable, expression) {
10126
10325
  return variable.prefix || variable.suffix ? `$$b.affix(${JSON.stringify(variable.prefix)}, ${expression}, ${JSON.stringify(variable.suffix)})` : expression;
10127
10326
  }
10327
+ /** True for the name of an import, in parentheses or not. */
10328
+ function isImported(node, scope) {
10329
+ while (node.type === "ParenthesizedExpression") node = node.expression;
10330
+ return node.type === "Identifier" && lookup(scope, node.name)?.kind === "import";
10331
+ }
10128
10332
  //#endregion
10129
10333
  //#region src/codegen/server.ts
10130
10334
  function propsType(file) {
@@ -10296,6 +10500,36 @@ function renderImport(file, statement, names) {
10296
10500
  const target = source.endsWith(".brm") ? `${source}?brumate-render` : source;
10297
10501
  return `import ${parts.join(", ")} from ${JSON.stringify(target)};`;
10298
10502
  }
10503
+ /** The exports of the module script, from its declarations and its export lists. */
10504
+ function moduleExports(file, plan) {
10505
+ const result = [];
10506
+ for (const statement of file.moduleScript?.program.body ?? []) {
10507
+ if (statement.type !== "ExportNamedDeclaration" || statement.source) continue;
10508
+ if (statement.declaration) {
10509
+ 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({
10510
+ local: declaration.name,
10511
+ name: declaration.name
10512
+ });
10513
+ continue;
10514
+ }
10515
+ for (const specifier of statement.specifiers) {
10516
+ const local = file.source.slice(specifier.local.start, specifier.local.end);
10517
+ const name = file.source.slice(specifier.exported.start, specifier.exported.end);
10518
+ if (plan.graph.model.module.declarations.get(local)?.kind === "module") result.push({
10519
+ local,
10520
+ name
10521
+ });
10522
+ }
10523
+ }
10524
+ return result;
10525
+ }
10526
+ /** True if the render module imports names of the module script from the shared part. */
10527
+ function rendersModule(plan) {
10528
+ for (const site of plan.graph.model.sites) if (!SKIPPED_SITES.has(site.kind)) {
10529
+ for (const read of site.reads) if (read.declaration.kind === "module") return true;
10530
+ }
10531
+ return false;
10532
+ }
10299
10533
  /** Returns the module script for client code. Server functions become `rpc` stubs. */
10300
10534
  function clientModuleScript(file, plan) {
10301
10535
  const result = [];
@@ -10325,14 +10559,16 @@ function awaitsPromise(plan) {
10325
10559
  function generateRender(file, plan, getFill) {
10326
10560
  const model = plan.graph.model;
10327
10561
  const patch = new Patch(file.source);
10328
- addValueEdits(patch, file, model.sites, "client", void 0, void 0, model.component.id);
10562
+ addValueEdits(patch, file, model.sites, "render", void 0, void 0, model.component.id);
10329
10563
  const names = componentNames(file.children);
10330
10564
  for (const template of file.templates) bodyNames(template.body, names);
10331
10565
  for (const site of model.sites) if (!SKIPPED_SITES.has(site.kind)) for (const read of site.reads) names.add(read.declaration.name);
10332
- let usesModule = false;
10333
- for (const name of names) if (model.module.declarations.get(name)?.kind === "module") {
10334
- usesModule = true;
10335
- break;
10566
+ const moduleNames = [];
10567
+ const serverNames = [];
10568
+ for (const name of names) {
10569
+ const found = model.module.declarations.get(name);
10570
+ if (found?.kind === "module") moduleNames.push(name);
10571
+ else if (found?.kind === "server-function") serverNames.push(name);
10336
10572
  }
10337
10573
  const header = ["import * as $$b from 'brumate/client';"];
10338
10574
  const moduleBody = [];
@@ -10343,16 +10579,19 @@ function generateRender(file, plan, getFill) {
10343
10579
  for (const program of programs) {
10344
10580
  const isModule = program === file.moduleScript?.program;
10345
10581
  for (const statement of program.body) if (statement.type === "ImportDeclaration") {
10346
- let code;
10347
- if (isModule && usesModule) {
10348
- const own = /* @__PURE__ */ new Set();
10349
- for (const specifier of statement.specifiers) own.add(specifier.local.name);
10350
- code = renderImport(file, statement, own);
10351
- } else code = renderImport(file, statement, names);
10582
+ const code = renderImport(file, statement, names);
10352
10583
  if (code) header.push(code);
10353
10584
  } else if (!isModule && TYPE_DECLARATIONS.has(statement.type)) moduleBody.push(copy(file.source, statement.start, statement.end));
10354
10585
  }
10355
- if (usesModule) moduleBody.push(...clientModuleScript(file, plan));
10586
+ const exported = moduleNames.length > 0 ? moduleExports(file, plan) : [];
10587
+ const imports = new Set(moduleNames);
10588
+ for (const item of exported) imports.add(item.name);
10589
+ if (imports.size > 0) {
10590
+ const base = file.filename.split(/[\\/]/).pop();
10591
+ header.push(`import { ${[...imports].join(", ")} } from ${JSON.stringify(`./${base}?brumate-client&part=shared`)};`);
10592
+ }
10593
+ if (exported.length > 0) moduleBody.push(`export { ${exported.map((item) => item.name).join(", ")} };`);
10594
+ 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);`);
10356
10595
  for (const declaration of model.declarations) if (declaration.kind === "server-function" && declaration.scope !== model.module) {
10357
10596
  const ref = serverFunctionId(plan, declaration.name);
10358
10597
  moduleBody.push(`const ${declaration.name} = (...$$a) => $$b.rpc(${JSON.stringify(ref)}, $$a);`);
@@ -10931,6 +11170,7 @@ var ClientGenerator = class {
10931
11170
  this.emitFunctions();
10932
11171
  this.emitRoots();
10933
11172
  this.part = "update";
11173
+ this.emitTemplateExports();
10934
11174
  this.emitUpdates();
10935
11175
  this.emitWindowStarts();
10936
11176
  this.emitRenders();
@@ -11142,7 +11382,7 @@ var ClientGenerator = class {
11142
11382
  if (item.kind === "import") names.add(item.name);
11143
11383
  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);
11144
11384
  }
11145
- const lines = ["import * as $$b from 'brumate/client';", ...this.importsFor(names, name === "update" || this.templateScopes(name))];
11385
+ const lines = ["import * as $$b from 'brumate/client';", ...this.importsFor(names, this.partScopes(name), name === "update")];
11146
11386
  if (shared.length > 0) lines.push(`import { ${[...new Set(shared)].join(", ")} } from ${JSON.stringify(this.partPath("shared"))};`);
11147
11387
  lines.push("", ...this.serverStubs([name]), ...this.out.get(name) ?? [], "");
11148
11388
  return lines.join("\n");
@@ -11152,7 +11392,7 @@ var ClientGenerator = class {
11152
11392
  const imports = /* @__PURE__ */ new Set();
11153
11393
  for (const name of names) for (const item of this.reads(this.partSites(name))) if (item.kind === "import") imports.add(item.name);
11154
11394
  const scopes = [...this.renderedScopes()];
11155
- for (const name of names) scopes.push(...this.templateScopes(name));
11395
+ for (const name of names) for (const scope of this.partScopes(name)) if (!scopes.includes(scope)) scopes.push(scope);
11156
11396
  const lines = [
11157
11397
  "import * as $$b from 'brumate/client';",
11158
11398
  ...this.importsFor(imports, scopes, names.includes("update")),
@@ -11172,9 +11412,7 @@ var ClientGenerator = class {
11172
11412
  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));
11173
11413
  lines.push(...clientModuleScript(this.file, this.plan));
11174
11414
  const exported = /* @__PURE__ */ new Set();
11175
- for (const statement of this.file.moduleScript.program.body) if (statement.type === "ExportNamedDeclaration" && statement.declaration) {
11176
- for (const declaration of this.model.module.declarations.values()) if (declaration.range.start >= statement.start && declaration.range.end <= statement.end) exported.add(declaration.name);
11177
- }
11415
+ for (const item of moduleExports(this.file, this.plan)) if (item.local === item.name) exported.add(item.name);
11178
11416
  const rest = [];
11179
11417
  for (const declaration of this.model.module.declarations.values()) if (declaration.kind === "module" && !exported.has(declaration.name)) rest.push(declaration.name);
11180
11418
  if (rest.length > 0) lines.push(`export { ${rest.join(", ")} };`);
@@ -11202,6 +11440,7 @@ var ClientGenerator = class {
11202
11440
  return reads;
11203
11441
  }
11204
11442
  usesModuleScript() {
11443
+ if (rendersModule(this.plan)) return true;
11205
11444
  for (const declaration of this.clientReads()) if (declaration.kind === "module") return true;
11206
11445
  return false;
11207
11446
  }
@@ -11220,6 +11459,23 @@ var ClientGenerator = class {
11220
11459
  }
11221
11460
  return result;
11222
11461
  }
11462
+ /**
11463
+ * The scopes whose components and imports a part needs: the scopes that the update part
11464
+ * renders, the templates of a template part, and the templates that the code of the part
11465
+ * copies into itself, such as a call `row(item)` in an update.
11466
+ */
11467
+ partScopes(part) {
11468
+ const result = part === "update" ? this.renderedScopes() : this.templateScopes(part);
11469
+ for (const site of this.partSites(part)) {
11470
+ const used = [...site.calls];
11471
+ for (const read of site.reads) used.push(read.declaration);
11472
+ for (const callee of used) {
11473
+ const template = callee.kind === "template" ? this.findTemplateScope(callee) : void 0;
11474
+ for (const item of template ? this.inside(template) : []) if (!result.includes(item)) result.push(item);
11475
+ }
11476
+ }
11477
+ return result;
11478
+ }
11223
11479
  /** Every scope that a render function of this module renders, including templates. */
11224
11480
  renderedScopes() {
11225
11481
  const result = /* @__PURE__ */ new Set();
@@ -11396,8 +11652,7 @@ var ClientGenerator = class {
11396
11652
  case "memo": {
11397
11653
  const slot = slotIndex(this.plan, node.declaration);
11398
11654
  if (slot !== -1) {
11399
- const code = site.awaits ? `(async () => (${expression()}))()` : expression();
11400
- const value = site.node.type === "ObjectExpression" ? `(${code})` : code;
11655
+ const value = arrowBody(site.awaits ? `(async () => (${expression()}))()` : expression(), this.file.source, site.node.start);
11401
11656
  const timing = node.declaration.timing;
11402
11657
  const call = timing ? `$$b.timed($$s, ${slot}, ${timing.ms}, ${timing.kind === "throttled"}, () => ${value})` : `$$b.memo($$s, ${slot}, () => ${value})`;
11403
11658
  this.emit(`export function ${name("m")}($$s) {\n ${call};\n}`);
@@ -11961,21 +12216,23 @@ var ClientGenerator = class {
11961
12216
  break;
11962
12217
  }
11963
12218
  const scope = callee && this.findTemplateScope(callee);
11964
- const template = scope?.template;
11965
- if (!scope || !template) return;
11966
- const first = template.params[0];
11967
- const last = template.params.at(-1);
11968
- const params = first && last ? copy(this.file.source, first.start, last.end) : "";
11969
- const pairs = [];
11970
- for (const declaration of scope.declarations.values()) {
11971
- if (declaration.kind !== "template-param") continue;
11972
- const slot = slotIndex(this.plan, declaration);
11973
- if (slot === -1) return;
11974
- pairs.push(`[${slot}, ${declaration.name}]`);
11975
- }
11976
- this.emit(`export const ${symbol}a = (${params}) => [${pairs.join(", ")}];`);
12219
+ if (scope) this.emitArgsExports(symbol, scope);
12220
+ }
12221
+ /** The `a` and `k` exports of a template, which `symbol` names. */
12222
+ emitArgsExports(symbol, scope) {
12223
+ const args = templateArgs(this.plan, this.file.source, scope);
12224
+ if (!args) return;
12225
+ this.emit(`export const ${symbol}a = (${args.exported}) => [${args.pairs.join(", ")}];`);
11977
12226
  this.emit(`export const ${symbol}k = ${scope.id};`);
11978
12227
  }
12228
+ /**
12229
+ * The exports of the templates of the file that a call in markup can update in place: the
12230
+ * template is `T` and its scope ID, as `templateCall` of the template's code names it.
12231
+ */
12232
+ emitTemplateExports() {
12233
+ this.part = "update";
12234
+ for (const scope of this.model.scopes) if (scope.template) this.emitArgsExports(`T${scope.id}`, scope);
12235
+ }
11979
12236
  withTemplates(site, code) {
11980
12237
  const templates = [];
11981
12238
  const used = [...site.calls];
@@ -12297,6 +12554,18 @@ function compile(source, options = {}) {
12297
12554
  for (const read of declaration.reads) read.site.calls.add(declaration);
12298
12555
  }
12299
12556
  }
12557
+ for (const site of model.sites) {
12558
+ if (site.kind !== "prop") continue;
12559
+ let node = site.node;
12560
+ while (node.type === "ParenthesizedExpression" || node.type === "CallExpression" && node.arguments[0]?.type !== "SpreadElement") {
12561
+ const inner = node.type === "ParenthesizedExpression" ? node.expression : node.arguments[0];
12562
+ if (!inner) break;
12563
+ node = inner;
12564
+ }
12565
+ if (node.type !== "Identifier") continue;
12566
+ const declaration = lookup(site.scope, node.name);
12567
+ if (declaration?.kind === "import" && declaration.imported && declaration.serverImport === void 0 && declaration.callable === void 0) declaration.callable = mayExportFunction(declaration.imported.source, declaration.imported.name, options.path ?? filename, options.resolveModule ?? resolveFromDisk);
12568
+ }
12300
12569
  checkPendingReads(model.sites, model.pendingCalls, (message, range) => model.diagnostics.push({
12301
12570
  severity: "error",
12302
12571
  message,
@@ -12571,4 +12840,4 @@ function inspect(source, options = {}) {
12571
12840
  //#endregion
12572
12841
  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 };
12573
12842
 
12574
- //# sourceMappingURL=inspect-ddfGeww0.js.map
12843
+ //# sourceMappingURL=inspect-Bonq6EJO.js.map