brumate 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/{boot-BkUdiYOF.d.ts → boot-ej-9NRT3.d.ts} +20 -2
  2. package/dist/cli.js +88 -82
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{client-B0FXW5Kw.js → client-B-ww-PQ7.js} +402 -63
  5. package/dist/client-B-ww-PQ7.js.map +1 -0
  6. package/dist/{client-Cq6aTiDs.d.ts → client-Do6IBIhI.d.ts} +58 -14
  7. package/dist/{defer-BMIMP4Hq.js → defer-JD2FK9mV.js} +5 -3
  8. package/dist/defer-JD2FK9mV.js.map +1 -0
  9. package/dist/{devtools-calls-DGW6nLZ2.js → devtools-calls-DCjuSkim.js} +3 -3
  10. package/dist/{devtools-calls-DGW6nLZ2.js.map → devtools-calls-DCjuSkim.js.map} +1 -1
  11. package/dist/{devtools-panel-B1nF1KB7.js → devtools-panel-DLeWTPhU.js} +4 -4
  12. package/dist/{devtools-panel-B1nF1KB7.js.map → devtools-panel-DLeWTPhU.js.map} +1 -1
  13. package/dist/{devtools-B4prrxht.js → devtools-tuq7ATGN.js} +10 -7
  14. package/dist/devtools-tuq7ATGN.js.map +1 -0
  15. package/dist/{error-catalog-DakxjSgj.js → error-catalog-BBWB7w-E.js} +11 -4
  16. package/dist/error-catalog-BBWB7w-E.js.map +1 -0
  17. package/dist/{error-catalog-VxLbz-6p.js → error-catalog-CbmQqfat.js} +1 -1
  18. package/dist/{events-LgLdp1R7.js → events-BDVITj3P.js} +3 -5
  19. package/dist/events-BDVITj3P.js.map +1 -0
  20. package/dist/{features-DwMYKBIC.js → features-Cte5aj20.js} +8 -2
  21. package/dist/features-Cte5aj20.js.map +1 -0
  22. package/dist/{files-D5GtxwEQ.js → files-Bz0lAQzD.js} +2 -2
  23. package/dist/{files-D5GtxwEQ.js.map → files-Bz0lAQzD.js.map} +1 -1
  24. package/dist/{html-Cf5uKhLs.js → html-BYuHDvxy.js} +10 -3
  25. package/dist/html-BYuHDvxy.js.map +1 -0
  26. package/dist/index.d.ts +71 -19
  27. package/dist/index.js +3 -3
  28. package/dist/{inspect-CGl5Y8q6.js → inspect-fpaBJ5pm.js} +1305 -75
  29. package/dist/inspect-fpaBJ5pm.js.map +1 -0
  30. package/dist/{loader-BsaSuIoG.js → loader-DMxuZ6He.js} +14 -6
  31. package/dist/loader-DMxuZ6He.js.map +1 -0
  32. package/dist/{navigate-BlowKvhB.js → navigate-C5PjwYMh.js} +108 -20
  33. package/dist/navigate-C5PjwYMh.js.map +1 -0
  34. package/dist/{produce-CLABZ8k2.d.ts → produce-BDkCsGH7.d.ts} +3 -3
  35. package/dist/{rpc-C1jYVNAe.js → rpc-DOdrekhP.js} +23 -13
  36. package/dist/rpc-DOdrekhP.js.map +1 -0
  37. package/dist/runtime/bundles.d.ts +3 -2
  38. package/dist/runtime/bundles.js +20 -5
  39. package/dist/runtime/bundles.js.map +1 -1
  40. package/dist/runtime/client.d.ts +4 -3
  41. package/dist/runtime/client.js +5 -5
  42. package/dist/runtime/devtools.d.ts +3 -1
  43. package/dist/runtime/devtools.js +1 -1
  44. package/dist/runtime/events.js +1 -1
  45. package/dist/runtime/hot.d.ts +1 -1
  46. package/dist/runtime/html.js +1 -1
  47. package/dist/runtime/loader.d.ts +2 -2
  48. package/dist/runtime/loader.js +2 -2
  49. package/dist/runtime/otel.d.ts +18 -0
  50. package/dist/runtime/otel.js +127 -0
  51. package/dist/runtime/otel.js.map +1 -0
  52. package/dist/runtime/server.d.ts +4 -3
  53. package/dist/runtime/server.js +5 -5
  54. package/dist/runtime/signals.d.ts +2 -2
  55. package/dist/runtime/signals.js +4 -1
  56. package/dist/runtime/signals.js.map +1 -1
  57. package/dist/runtime/static-loader.d.ts +2 -2
  58. package/dist/runtime/static-loader.js +1 -1
  59. package/dist/runtime/store.d.ts +2 -2
  60. package/dist/runtime/store.js +1 -1
  61. package/dist/runtime/testing.d.ts +2 -2
  62. package/dist/runtime/testing.js +2 -2
  63. package/dist/search-params-qGERTLi3.js +382 -0
  64. package/dist/search-params-qGERTLi3.js.map +1 -0
  65. package/dist/{serial-ribg9NAj.js → serial-B2AJ9VGx.js} +1 -1
  66. package/dist/{serial-ioa17MuY.js → serial-Cj6pDGOq.js} +6 -6
  67. package/dist/{serial-ioa17MuY.js.map → serial-Cj6pDGOq.js.map} +1 -1
  68. package/dist/{server-DesBZv5g.d.ts → server-2-LS_KFo.d.ts} +125 -9
  69. package/dist/{server-BUuf7XPZ.js → server-CRGZMWnK.js} +545 -236
  70. package/dist/server-CRGZMWnK.js.map +1 -0
  71. package/dist/{shared-CX_YacDm.js → shared-CUBWrbiM.js} +4 -4
  72. package/dist/{shared-CX_YacDm.js.map → shared-CUBWrbiM.js.map} +1 -1
  73. package/dist/sheets-B9Zr50mf.js +105 -0
  74. package/dist/sheets-B9Zr50mf.js.map +1 -0
  75. package/dist/{signals-7VVD9C_H.d.ts → signals-BgsJK-uT.d.ts} +16 -6
  76. package/dist/{static-loader-C_en-4v8.js → static-loader-BDBtWsdg.js} +107 -19
  77. package/dist/static-loader-BDBtWsdg.js.map +1 -0
  78. package/dist/{static-loader-UKnK11Em.d.ts → static-loader-CAFn6p0l.d.ts} +2 -2
  79. package/dist/{store-9_oa0HG1.d.ts → store-BwWg-Iei.d.ts} +79 -2
  80. package/dist/store-DNr24Z8L.js +950 -0
  81. package/dist/store-DNr24Z8L.js.map +1 -0
  82. package/dist/{stream-read-BTsYstJY.js → stream-read-CiLDH60b.js} +2 -2
  83. package/dist/{stream-read-BTsYstJY.js.map → stream-read-CiLDH60b.js.map} +1 -1
  84. package/dist/{stream-read-Dek3HnqO.js → stream-read-DVoregpA.js} +1 -1
  85. package/dist/trace-DT7RGRAV.d.ts +52 -0
  86. package/dist/trace-browser-C7MFMove.js +170 -0
  87. package/dist/trace-browser-C7MFMove.js.map +1 -0
  88. package/dist/trace-flag-Dy267snx.js +7 -0
  89. package/dist/trace-flag-Dy267snx.js.map +1 -0
  90. package/dist/{trusted-g_zUJbh2.js → trusted-Bmwg4_hf.js} +12 -5
  91. package/dist/trusted-Bmwg4_hf.js.map +1 -0
  92. package/dist/view-transitions-BpnVwtS4.js +141 -0
  93. package/dist/view-transitions-BpnVwtS4.js.map +1 -0
  94. package/dist/vite.d.ts +8 -1
  95. package/dist/vite.js +356 -46
  96. package/dist/vite.js.map +1 -1
  97. package/elements.d.ts +8 -0
  98. package/package.json +13 -1
  99. package/skills/brumate/SKILL.md +9 -5
  100. package/skills/brumate/references/errors.md +95 -14
  101. package/skills/brumate/references/events.md +27 -1
  102. package/skills/brumate/references/signals.md +4 -4
  103. package/skills/brumate/references/state.md +79 -4
  104. package/skills/brumate/references/syntax.md +58 -9
  105. package/dist/client-B0FXW5Kw.js.map +0 -1
  106. package/dist/defer-BMIMP4Hq.js.map +0 -1
  107. package/dist/devtools-B4prrxht.js.map +0 -1
  108. package/dist/error-catalog-DakxjSgj.js.map +0 -1
  109. package/dist/events-LgLdp1R7.js.map +0 -1
  110. package/dist/features-DwMYKBIC.js.map +0 -1
  111. package/dist/html-Cf5uKhLs.js.map +0 -1
  112. package/dist/inspect-CGl5Y8q6.js.map +0 -1
  113. package/dist/loader-BsaSuIoG.js.map +0 -1
  114. package/dist/navigate-BlowKvhB.js.map +0 -1
  115. package/dist/rpc-C1jYVNAe.js.map +0 -1
  116. package/dist/search-params-Wg-0FsMj.js +0 -148
  117. package/dist/search-params-Wg-0FsMj.js.map +0 -1
  118. package/dist/server-BUuf7XPZ.js.map +0 -1
  119. package/dist/static-loader-C_en-4v8.js.map +0 -1
  120. package/dist/store-Cy4EEyZ7.js +0 -439
  121. package/dist/store-Cy4EEyZ7.js.map +0 -1
  122. package/dist/trusted-g_zUJbh2.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { a as findError } from "./error-catalog-DakxjSgj.js";
1
+ import { a as findError } from "./error-catalog-BBWB7w-E.js";
2
2
  import { i as paragraphComponents, t as checkNesting } from "./nesting-DA5vJw9X.js";
3
- import { t as KEY_NAMES } from "./events-LgLdp1R7.js";
4
- import { p as insertValue } from "./html-Cf5uKhLs.js";
3
+ import { t as KEY_NAMES } from "./events-BDVITj3P.js";
4
+ import { p as insertValue } from "./html-BYuHDvxy.js";
5
5
  import { parseSync } from "oxc-parser";
6
6
  import { parse } from "postcss";
7
7
  import selectorParser from "postcss-selector-parser";
@@ -165,17 +165,17 @@ function isFallbackLiteral(node) {
165
165
  }
166
166
  //#endregion
167
167
  //#region src/bridges.ts
168
- const STORE_MODULE = "brumate/store";
168
+ const STORE_MODULE$1 = "brumate/store";
169
169
  /** The name that `export default bridge(…)` gets, so the module can name it. */
170
170
  const DEFAULT_LOCAL = "$$default";
171
171
  /** The message of BRM200. */
172
172
  const BRIDGE_EXPORT = "The value of bridge() must be a module-level export of a script file or of <script module>, as \"export const name = bridge({ … })\"";
173
173
  /** True when a file can hold a call of `bridge`, which is cheap to know before it is parsed. */
174
174
  function mayHaveBridge(source) {
175
- return source.includes("bridge") && source.includes(STORE_MODULE);
175
+ return source.includes("bridge") && source.includes(STORE_MODULE$1);
176
176
  }
177
177
  /** The import that the naming calls need. */
178
- const NAME_BRIDGE_IMPORT = `import { nameBridge as $$nameBridge } from ${JSON.stringify(STORE_MODULE)};`;
178
+ const NAME_BRIDGE_IMPORT = `import { nameBridge as $$nameBridge } from ${JSON.stringify(STORE_MODULE$1)};`;
179
179
  /**
180
180
  * The calls that name the bridges of the `<script module>` of a component, by the ID of the
181
181
  * component, `bridge:<id>#<export>`. A bridge that is not an export by name is not in the list;
@@ -199,7 +199,7 @@ function importedNames(program) {
199
199
  const direct = /* @__PURE__ */ new Set();
200
200
  const spaces = /* @__PURE__ */ new Set();
201
201
  for (const statement of program.body) {
202
- if (statement.type !== "ImportDeclaration" || statement.source.value !== STORE_MODULE) continue;
202
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== STORE_MODULE$1) continue;
203
203
  for (const specifier of statement.specifiers) if (specifier.type === "ImportNamespaceSpecifier") spaces.add(specifier.local.name);
204
204
  else if (specifier.type === "ImportSpecifier") {
205
205
  if ((specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value) === "bridge") direct.add(specifier.local.name);
@@ -523,7 +523,7 @@ const REACTIVE = /* @__PURE__ */ new Set([
523
523
  /** The module of the wrappers of event handlers, which the compiler reads. */
524
524
  const EVENTS_MODULE = "brumate/events";
525
525
  /** The wrappers that `brumate/events` exports. */
526
- const WRAPPERS$3 = /* @__PURE__ */ new Set([
526
+ const WRAPPERS$4 = /* @__PURE__ */ new Set([
527
527
  "prevent",
528
528
  "stop",
529
529
  "once",
@@ -645,6 +645,80 @@ const TYPE_WRAPPERS = /* @__PURE__ */ new Set([
645
645
  "TSTypeAssertion",
646
646
  "TSInstantiationExpression"
647
647
  ]);
648
+ /** The names that every path of a statement assigns. */
649
+ function assignedOnEveryPath(node) {
650
+ const names = /* @__PURE__ */ new Set();
651
+ switch (node.type) {
652
+ case "BlockStatement":
653
+ for (const statement of node.body) for (const name of assignedOnEveryPath(statement)) names.add(name);
654
+ break;
655
+ case "ExpressionStatement":
656
+ case "ParenthesizedExpression": return assignedOnEveryPath(node.expression);
657
+ case "SequenceExpression":
658
+ for (const expression of node.expressions) for (const name of assignedOnEveryPath(expression)) names.add(name);
659
+ break;
660
+ case "AssignmentExpression":
661
+ if (node.left.type === "Identifier") names.add(node.left.name);
662
+ break;
663
+ case "IfStatement": if (node.alternate) {
664
+ const other = assignedOnEveryPath(node.alternate);
665
+ for (const name of assignedOnEveryPath(node.consequent)) if (other.has(name)) names.add(name);
666
+ }
667
+ }
668
+ return names;
669
+ }
670
+ /** True when an identifier of the expression has one of the names. */
671
+ function mentionsName(node, names) {
672
+ if (node.type === "Identifier" && names.has(node.name)) return true;
673
+ for (const [, child] of children(node)) if (mentionsName(child, names)) return true;
674
+ return false;
675
+ }
676
+ /**
677
+ * True when a statement only assigns identifiers, maybe under `if` and inside blocks, with no
678
+ * call, `await`, function, loop or `throw`. Collects the assignments.
679
+ */
680
+ function collectCopies(node, found) {
681
+ switch (node.type) {
682
+ case "BlockStatement":
683
+ for (const statement of node.body) if (!collectCopies(statement, found)) return false;
684
+ return true;
685
+ case "EmptyStatement": return true;
686
+ case "ExpressionStatement": return collectCopies(node.expression, found);
687
+ case "IfStatement":
688
+ found.branches = true;
689
+ found.reads.push(node.test);
690
+ return isPure(node.test) && collectCopies(node.consequent, found) && (!node.alternate || collectCopies(node.alternate, found));
691
+ case "SequenceExpression":
692
+ for (const expression of node.expressions) if (!collectCopies(expression, found)) return false;
693
+ return true;
694
+ case "AssignmentExpression":
695
+ if (node.left.type !== "Identifier" || node.operator !== "=" || !isPure(node.right)) return false;
696
+ found.reads.push(node.right);
697
+ found.assignments.push(node);
698
+ return true;
699
+ case "ParenthesizedExpression": return collectCopies(node.expression, found);
700
+ default: return false;
701
+ }
702
+ }
703
+ /** True for an expression with no call, `await`, `new`, function, tagged template or assignment. */
704
+ function isPure(node) {
705
+ switch (node.type) {
706
+ case "CallExpression":
707
+ case "NewExpression":
708
+ case "TaggedTemplateExpression":
709
+ case "AwaitExpression":
710
+ case "YieldExpression":
711
+ case "AssignmentExpression":
712
+ case "UpdateExpression":
713
+ case "ImportExpression":
714
+ case "ArrowFunctionExpression":
715
+ case "FunctionExpression":
716
+ case "ClassExpression": return false;
717
+ default:
718
+ for (const [, child] of children(node)) if (!isPure(child)) return false;
719
+ return true;
720
+ }
721
+ }
648
722
  function isFunction$2(node) {
649
723
  return node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression" || node?.type === "FunctionDeclaration";
650
724
  }
@@ -751,8 +825,8 @@ function readProvidedValues(value) {
751
825
  }
752
826
  return [value];
753
827
  }
754
- function analyze$1(file) {
755
- return new Analyzer(file).run();
828
+ function analyze$1(file, moduleSignals = /* @__PURE__ */ new Map()) {
829
+ return new Analyzer(file, moduleSignals).run();
756
830
  }
757
831
  var Analyzer = class {
758
832
  file;
@@ -774,8 +848,11 @@ var Analyzer = class {
774
848
  propsTypes = [];
775
849
  module;
776
850
  component;
777
- constructor(file) {
851
+ /** The names that read a module signal, with the module of the signal that an import gives. */
852
+ moduleSignals;
853
+ constructor(file, moduleSignals) {
778
854
  this.file = file;
855
+ this.moduleSignals = moduleSignals;
779
856
  this.module = this.createScope("module", void 0);
780
857
  this.component = this.createScope("component", this.module);
781
858
  }
@@ -802,6 +879,7 @@ var Analyzer = class {
802
879
  this.check();
803
880
  this.checkPromises();
804
881
  this.checkStoreSources();
882
+ this.checkEffectCopies();
805
883
  return {
806
884
  module: this.module,
807
885
  component: this.component,
@@ -994,6 +1072,54 @@ var Analyzer = class {
994
1072
  }
995
1073
  for (const declaration of props) if (!written.has(declaration.propKey)) this.report("warning", `The prop "${declaration.propKey}" is Bindable, but the component reads it with const and never writes it. Destructure it with let`, declaration.range);
996
1074
  }
1075
+ /**
1076
+ * Warns about a signal that only an `$effect` writes, when the effect does nothing else: the
1077
+ * signal is a memo written the long way. Any call, `await`, loop or cleanup ends the check, and
1078
+ * so does a write of the signal anywhere else, which makes it state.
1079
+ */
1080
+ checkEffectCopies() {
1081
+ for (const site of this.sites) {
1082
+ if (site.kind !== "effect" || !isFunction$2(site.node)) continue;
1083
+ const body = site.node.body;
1084
+ if (!body) continue;
1085
+ const copy = {
1086
+ assignments: [],
1087
+ branches: false,
1088
+ reads: []
1089
+ };
1090
+ if (!collectCopies(body, copy) || copy.assignments.length === 0) continue;
1091
+ const assigned = /* @__PURE__ */ new Set();
1092
+ for (const node of copy.assignments) assigned.add(node.left.name);
1093
+ const every = assignedOnEveryPath(body);
1094
+ let equivalent = true;
1095
+ for (const name of assigned) equivalent &&= every.has(name);
1096
+ for (const read of copy.reads) equivalent &&= !mentionsName(read, assigned);
1097
+ if (!equivalent) continue;
1098
+ const targets = [];
1099
+ let copies = true;
1100
+ for (const node of copy.assignments) {
1101
+ const target = node.left;
1102
+ const declaration = site.writes.find((item) => item.range.start === target.start && item.range.end === target.end)?.declaration;
1103
+ if (!declaration || declaration.kind !== "signal" || declaration.bound || declaration.searchParam || declaration.optimistic || declaration.writes.some((item) => item.site !== site)) {
1104
+ copies = false;
1105
+ break;
1106
+ }
1107
+ targets.push({
1108
+ name: declaration.name,
1109
+ node
1110
+ });
1111
+ }
1112
+ if (!copies) continue;
1113
+ const single = copy.assignments.length === 1 && !copy.branches;
1114
+ const reported = /* @__PURE__ */ new Set();
1115
+ for (const { name, node } of targets) {
1116
+ if (reported.has(name)) continue;
1117
+ reported.add(name);
1118
+ const form = single ? `const ${name} = $memo(...)` : "a $memo";
1119
+ this.report("warning", `"${name}" is written only by this effect. Use ${form}`, node);
1120
+ }
1121
+ }
1122
+ }
997
1123
  report(severity, message, at) {
998
1124
  this.diagnostics.push({
999
1125
  severity,
@@ -1071,7 +1197,7 @@ var Analyzer = class {
1071
1197
  node = node.arguments[0];
1072
1198
  continue;
1073
1199
  }
1074
- if (name === void 0 || !WRAPPERS$3.has(name)) break;
1200
+ if (name === void 0 || !WRAPPERS$4.has(name)) break;
1075
1201
  const [handler, ...rest] = node.arguments;
1076
1202
  if (!handler || name !== "prevent" && rest.length > 0) {
1077
1203
  this.report("error", `${name} takes a handler`, node);
@@ -1321,6 +1447,7 @@ var Analyzer = class {
1321
1447
  }
1322
1448
  const declaration = this.addDeclaration(scope, id.name, "context", id);
1323
1449
  declaration.guard = guard;
1450
+ if (this.moduleSignals.get(id.name)?.memo) declaration.moduleMemo = true;
1324
1451
  if (calleeName$1(argument) === "$getContext") {
1325
1452
  const read = argument;
1326
1453
  const [context, fallback] = read.arguments;
@@ -1551,7 +1678,7 @@ var Analyzer = class {
1551
1678
  node = handler;
1552
1679
  continue;
1553
1680
  }
1554
- if (name === void 0 || !WRAPPERS$3.has(name) || !handler) break;
1681
+ if (name === void 0 || !WRAPPERS$4.has(name) || !handler) break;
1555
1682
  const names = [];
1556
1683
  let unnamed = false;
1557
1684
  for (const key of keys) {
@@ -1605,7 +1732,6 @@ var Analyzer = class {
1605
1732
  return;
1606
1733
  }
1607
1734
  if (callback.params.length > 0) this.report("error", `The callback of ${name} takes no parameters`, callback);
1608
- if (callback.async) this.report("error", `The callback of ${name} cannot be async`, callback);
1609
1735
  if (name === "$effect") {
1610
1736
  if (call.arguments.length > 1) this.report("error", "$effect takes one argument", call);
1611
1737
  this.createSite("effect", scope, callback, "effect");
@@ -1819,6 +1945,28 @@ var Analyzer = class {
1819
1945
  for (const binding of this.bindings) if (binding.declaration.promise) this.report("error", promiseMessage(binding.declaration.name, "a binding"), binding.call);
1820
1946
  for (const declaration of this.declarations) if (declaration.promise) for (const ref of declaration.refs) this.report("error", promiseMessage(declaration.name, "a ref"), ref.attribute);
1821
1947
  }
1948
+ /** True for a name that reads a signal or a memo of a module. */
1949
+ isModuleSignal(name) {
1950
+ return this.moduleSignals.has(name);
1951
+ }
1952
+ /**
1953
+ * The advice for a write of a name that reads a module signal, or undefined for any other name.
1954
+ * A module cannot be written through an import, so the advice is a function that writes it.
1955
+ */
1956
+ moduleSignalHint(declaration) {
1957
+ const found = this.moduleSignals.get(declaration.name);
1958
+ const memoKind = declaration.kind === "memo" || declaration.kind === "async-memo";
1959
+ if (!found || declaration.kind !== "context" && !(found.memo && memoKind)) return;
1960
+ const { specifier, memo } = found;
1961
+ if (memo) return {
1962
+ kind: "module memo",
1963
+ text: ". A memo is read-only"
1964
+ };
1965
+ return {
1966
+ kind: "module signal",
1967
+ text: specifier === void 0 ? "" : `. Export a function from ${specifier} that writes it, and call that function`
1968
+ };
1969
+ }
1822
1970
  check() {
1823
1971
  for (const declaration of this.declarations) if (declaration.kind === "action") {
1824
1972
  if (lookup(declaration.scope, declaration.action)?.kind !== "server-function") this.report("error", `$action needs a server function of this file, and ${declaration.action} is not one`, declaration.range);
@@ -1826,8 +1974,12 @@ var Analyzer = class {
1826
1974
  for (const site of this.sites) {
1827
1975
  for (const write of site.writes) {
1828
1976
  const declaration = write.declaration;
1829
- if (!WRITABLE.has(declaration.kind) && !declaration.writable && !declaration.store?.write) this.report("error", `Cannot assign to ${declaration.kind} "${declaration.name}"`, write.range);
1830
- else if ((declaration.kind === "signal" || declaration.writable || declaration.store?.write) && !write.inFunction && !WRITING_SITES.has(site.kind)) this.report("error", `Signal "${declaration.name}" can only be written in event handlers, effects, $client callbacks and functions`, write.range);
1977
+ if (!WRITABLE.has(declaration.kind) && !declaration.writable && !declaration.store?.write) {
1978
+ const signal = this.moduleSignalHint(declaration);
1979
+ const kind = signal?.kind ?? declaration.kind;
1980
+ const hint = signal?.text ?? "";
1981
+ this.report("error", `Cannot assign to ${kind} "${declaration.name}"${hint}`, write.range);
1982
+ } else if ((declaration.kind === "signal" || declaration.writable || declaration.store?.write) && !write.inFunction && !WRITING_SITES.has(site.kind)) this.report("error", `Signal "${declaration.name}" can only be written in event handlers, effects, $client callbacks and functions`, write.range);
1831
1983
  }
1832
1984
  if (site.kind === "server-function") {
1833
1985
  for (const read of site.reads) if (!SERVER_CAPTURABLE.has(read.declaration.kind)) this.report("error", `Server function "${site.declaration?.name}" captures "${read.declaration.name}". Pass it as an argument`, read.range);
@@ -2149,7 +2301,7 @@ var Resolver = class {
2149
2301
  reference,
2150
2302
  at: range(node)
2151
2303
  });
2152
- if (reference.declaration.kind !== "memo" && reference.declaration.kind !== "async-memo") this.analyzer.report("error", "$resolve needs a $memo and, as an option, a timeout or a signal", node);
2304
+ if (reference.declaration.kind !== "memo" && reference.declaration.kind !== "async-memo" && !(reference.declaration.kind === "context" && this.analyzer.isModuleSignal(reference.declaration.name))) this.analyzer.report("error", "$resolve needs a $memo and, as an option, a timeout or a signal", node);
2153
2305
  }
2154
2306
  return;
2155
2307
  }
@@ -2674,7 +2826,7 @@ function tryCatchesClient(model, block) {
2674
2826
  if (holdsComponent(block.body.children)) return true;
2675
2827
  for (const scope of model.scopes) if (scope.template && isWithinAny$1(scope, inside) && holdsComponent(scope.template.body.children)) return true;
2676
2828
  for (const site of model.sites) if ((CLIENT_CODE.has(site.kind) || site.kind === "memo" && site.declaration?.kind === "async-memo") && isWithinAny$1(site.scope, inside)) return true;
2677
- for (const declaration of model.declarations) if (isMemoKind(declaration.kind)) {
2829
+ for (const declaration of model.declarations) if (isMemoKind(declaration.kind) || declaration.moduleMemo) {
2678
2830
  for (const read of declaration.reads) if (isWithinAny$1(read.site.scope, inside)) return true;
2679
2831
  }
2680
2832
  return false;
@@ -3203,7 +3355,7 @@ function findTopLevel(code, word, fail) {
3203
3355
  }
3204
3356
  //#endregion
3205
3357
  //#region src/parser.ts
3206
- const WRAPPERS$2 = /* @__PURE__ */ new Set([
3358
+ const WRAPPERS$3 = /* @__PURE__ */ new Set([
3207
3359
  "prevent",
3208
3360
  "stop",
3209
3361
  "once",
@@ -3253,6 +3405,15 @@ const CLIENT_TRIGGERS = /* @__PURE__ */ new Set([
3253
3405
  "idle",
3254
3406
  "load"
3255
3407
  ]);
3408
+ const SCRIPT_TRIGGERS = /* @__PURE__ */ new Set([
3409
+ "idle",
3410
+ "visible",
3411
+ "interaction",
3412
+ "load"
3413
+ ]);
3414
+ /** The open tag of a script that has `src` or `inline`, which makes it markup. */
3415
+ const MARKUP_SCRIPT = /^<script((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*)>/;
3416
+ const MARKUP_SCRIPT_MARK = /(?:^|\s)(?:src|inline)(?=[\s=/>]|$)/;
3256
3417
  function parse$1(source, options = {}) {
3257
3418
  return new Parser(source, options.filename ?? "Component.brm").parseFile();
3258
3419
  }
@@ -3261,6 +3422,8 @@ var Parser = class {
3261
3422
  source;
3262
3423
  fail;
3263
3424
  file;
3425
+ /** How many `#head` blocks the parser is inside. */
3426
+ heads = 0;
3264
3427
  constructor(source, filename) {
3265
3428
  this.source = source;
3266
3429
  this.fail = createFail(source, filename);
@@ -3361,6 +3524,10 @@ var Parser = class {
3361
3524
  this.skipHTMLComment();
3362
3525
  continue;
3363
3526
  }
3527
+ if (this.isTagStart("script") && this.isMarkupScript()) {
3528
+ nodes.push(this.parseMarkupScript());
3529
+ continue;
3530
+ }
3364
3531
  if (this.isTagStart("script")) {
3365
3532
  if (mode !== "file") this.fail("<script> must be at the top level or at the start of a block", this.pos);
3366
3533
  this.parseTopLevelScript();
@@ -3601,7 +3768,7 @@ var Parser = class {
3601
3768
  const rest = parts.slice(1);
3602
3769
  const wrappers = [];
3603
3770
  let unknown;
3604
- for (const modifier of rest) if (WRAPPERS$2.has(modifier)) wrappers.push(modifier);
3771
+ for (const modifier of rest) if (WRAPPERS$3.has(modifier)) wrappers.push(modifier);
3605
3772
  else if (modifier !== "passive") unknown ??= modifier;
3606
3773
  let fix;
3607
3774
  if (unknown !== void 0) fix = `${name}=(handler) with the wrappers of brumate/events, since ":${unknown}" is not a modifier`;
@@ -3765,6 +3932,61 @@ var Parser = class {
3765
3932
  attributes
3766
3933
  };
3767
3934
  }
3935
+ /** True for a `<script>` with `src` or `inline`, which is markup and not the script of a component. */
3936
+ isMarkupScript() {
3937
+ const tag = MARKUP_SCRIPT.exec(this.source.slice(this.pos, this.pos + 2e3));
3938
+ return tag !== null && MARKUP_SCRIPT_MARK.test(tag[1]);
3939
+ }
3940
+ /** Parses a `<script src>` or `<script inline>` in markup. */
3941
+ parseMarkupScript() {
3942
+ const start = this.pos;
3943
+ this.pos += 7;
3944
+ const close = "<\/script>";
3945
+ const attributes = this.parseAttributes("element");
3946
+ if (this.startsWith("/>")) this.fail(`Expected ${close}`, this.pos);
3947
+ this.pos++;
3948
+ const contentStart = this.pos;
3949
+ const contentEnd = this.source.indexOf(close, contentStart);
3950
+ if (contentEnd === -1) this.fail(`Expected ${close}`, contentStart);
3951
+ this.pos = contentEnd + 9;
3952
+ const text = this.source.slice(contentStart, contentEnd);
3953
+ let src = false;
3954
+ let inline = false;
3955
+ let rerun = false;
3956
+ let trigger;
3957
+ for (const attribute of attributes) {
3958
+ if (attribute.kind === "spread" || attribute.kind === "computed" || attribute.kind === "ref") continue;
3959
+ if (attribute.name === "src") src = true;
3960
+ else if (attribute.name === "inline") inline = true;
3961
+ else if (attribute.name === "data-rerun") rerun = true;
3962
+ else if (attribute.name === "trigger") {
3963
+ if (attribute.kind !== "static" || typeof attribute.value !== "string" || !SCRIPT_TRIGGERS.has(attribute.value)) this.fail("The trigger of a <script> is a plain string: idle, visible, interaction or load", attribute.start);
3964
+ trigger = attribute.value;
3965
+ }
3966
+ }
3967
+ if (src && inline) this.fail("A <script> with src is not inline. Give it src or inline, not both", start);
3968
+ if (src && text.trim() !== "") this.fail("A <script> with src has no code inside. Write the code in <script inline>", start);
3969
+ if (trigger === "visible" && this.heads > 0) this.fail("A script in #head cannot wait to be visible, since no element follows it. Use idle or interaction", start);
3970
+ if (trigger && rerun) this.fail("A script with a trigger runs once per page, so data-rerun does not apply. Remove one of them", start);
3971
+ return {
3972
+ kind: "element",
3973
+ start,
3974
+ end: this.pos,
3975
+ tag: "script",
3976
+ attributes,
3977
+ children: inline ? [{
3978
+ kind: "text",
3979
+ start: contentStart,
3980
+ end: contentEnd,
3981
+ value: text
3982
+ }] : [],
3983
+ script: {
3984
+ trigger,
3985
+ inline,
3986
+ head: this.heads > 0
3987
+ }
3988
+ };
3989
+ }
3768
3990
  parseTopLevelScript() {
3769
3991
  const start = this.pos;
3770
3992
  const { script, attributes } = this.parseScriptBlock();
@@ -3858,7 +4080,7 @@ var Parser = class {
3858
4080
  this.pos++;
3859
4081
  this.skipTrivia();
3860
4082
  let script;
3861
- if (this.isTagStart("script")) {
4083
+ if (this.isTagStart("script") && !this.isMarkupScript()) {
3862
4084
  const scriptStart = this.pos;
3863
4085
  const parsed = this.parseScriptBlock();
3864
4086
  if (Object.keys(parsed.attributes).length > 0) this.fail("The script of a block takes no attributes", scriptStart);
@@ -3994,12 +4216,17 @@ var Parser = class {
3994
4216
  fallback
3995
4217
  };
3996
4218
  }
3997
- case "head": return {
3998
- kind: "head",
3999
- start,
4000
- end: this.pos,
4001
- body: this.parseBody("head")
4002
- };
4219
+ case "head": {
4220
+ this.heads++;
4221
+ const body = this.parseBody("head");
4222
+ this.heads--;
4223
+ return {
4224
+ kind: "head",
4225
+ start,
4226
+ end: this.pos,
4227
+ body
4228
+ };
4229
+ }
4003
4230
  case "reveal": return this.parseReveal(start);
4004
4231
  case "portal": {
4005
4232
  const header = this.parseHeader("portal", false);
@@ -4625,7 +4852,7 @@ const SENDABLE = /* @__PURE__ */ new Set([
4625
4852
  "Boolean"
4626
4853
  ]);
4627
4854
  /** Compile-time functions whose argument is the value, such as `$signal(new Foo())`. */
4628
- const WRAPPERS$1 = /* @__PURE__ */ new Set([
4855
+ const WRAPPERS$2 = /* @__PURE__ */ new Set([
4629
4856
  "$signal",
4630
4857
  "$memo",
4631
4858
  "$debounced",
@@ -4637,7 +4864,7 @@ function initializers(file) {
4637
4864
  function visit(node) {
4638
4865
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
4639
4866
  let init = node.init;
4640
- if (init.type === "CallExpression" && init.callee.type === "Identifier" && WRAPPERS$1.has(init.callee.name) && init.arguments[0]) init = init.arguments[0];
4867
+ if (init.type === "CallExpression" && init.callee.type === "Identifier" && WRAPPERS$2.has(init.callee.name) && init.arguments[0]) init = init.arguments[0];
4641
4868
  result.set(node.id.start, init);
4642
4869
  }
4643
4870
  for (const [, child] of children(node)) visit(child);
@@ -5614,6 +5841,849 @@ function expandModules(file, path, resolve) {
5614
5841
  };
5615
5842
  }
5616
5843
  //#endregion
5844
+ //#region src/module-signals.ts
5845
+ /** The module of stores. */
5846
+ const STORE_MODULE = "brumate/store";
5847
+ /** The module of the runtime that holds `produce`. */
5848
+ const CLIENT_MODULE = "brumate/client";
5849
+ const STORE = "$$store";
5850
+ const DERIVED = "$$derived";
5851
+ /** The store of a memo: it holds an error, and its value can load. */
5852
+ const HELD = "memoStore";
5853
+ const PRODUCE = "$$produce";
5854
+ const OPTIMISTIC = "$$optimistic";
5855
+ /** The compile-time functions that declare a value at the top level, and what each makes. */
5856
+ const FORMS = /* @__PURE__ */ new Map([
5857
+ ["$signal", "signal"],
5858
+ ["$memo", "memo"],
5859
+ ["$gate", "memo"],
5860
+ ["$debounced", "memo"],
5861
+ ["$throttled", "memo"],
5862
+ ["$optimistic", "signal"]
5863
+ ]);
5864
+ /** The prefix of the store of a signal of `<script module>`. */
5865
+ const PREFIX = "$$ms_";
5866
+ /** The `$store` that the importer side calls. */
5867
+ const READ = "$$ms_read";
5868
+ /** The `$memo` that the importer side calls. */
5869
+ const MEMO = "$$ms_memo";
5870
+ /** The prefix of the slot that holds the values of the sources of a memo. */
5871
+ const INPUTS = "$$ms_in_";
5872
+ /**
5873
+ * The declaration that reads a module value in a component. A signal and an optimistic value read
5874
+ * the store with `$store`. A memo, a gate and a timed value are memos of the component over the
5875
+ * load of the store, which compute again on each notice of `store.i`, so `#loading`, `await`,
5876
+ * `$isPending` and `$resolve` work on them as on a memo of the component. The slot of `store.i`
5877
+ * holds the value that the server rendered, which the store of the browser takes on resume.
5878
+ */
5879
+ function readSignal(name, store, signal, own) {
5880
+ if (signal.kind === "memo") {
5881
+ const inputs = `${INPUTS}${name}`;
5882
+ return `const ${inputs} = ${READ}(${store}.i);\nconst ${name} = ${MEMO}(${signal.awaits ? "await " : ""}${store}.p(${inputs}));`;
5883
+ }
5884
+ return `${own && signal.kind === "signal" ? "let" : "const"} ${name} = ${READ}(${store});`;
5885
+ }
5886
+ /** The message of a write to a memo of a module. */
5887
+ function MEMO_WRITE(name) {
5888
+ return `Cannot assign to module memo "${name}". A memo is read-only`;
5889
+ }
5890
+ /** Type nodes hold names of types, which stay as they are. */
5891
+ const WRAPPERS$1 = /* @__PURE__ */ new Set([
5892
+ "TSAsExpression",
5893
+ "TSSatisfiesExpression",
5894
+ "TSNonNullExpression",
5895
+ "TSTypeAssertion",
5896
+ "TSInstantiationExpression"
5897
+ ]);
5898
+ /** The local names of the compile-time functions that a program imports. */
5899
+ function macroNames(program) {
5900
+ const names = /* @__PURE__ */ new Map();
5901
+ for (const statement of program.body) {
5902
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== "brumate/signals") continue;
5903
+ for (const specifier of statement.specifiers) {
5904
+ if (specifier.type !== "ImportSpecifier") continue;
5905
+ const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
5906
+ if (MACROS.has(imported)) names.set(specifier.local.name, imported);
5907
+ }
5908
+ }
5909
+ return names;
5910
+ }
5911
+ function isScope(node) {
5912
+ return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "ClassDeclaration" || node.type === "ClassExpression";
5913
+ }
5914
+ /** The error of a form that a module cannot compile. */
5915
+ function topLevelError(name, reason, fix, offset) {
5916
+ return new ModuleError(`${name} cannot be compiled in a module${reason}. ${fix}`, offset);
5917
+ }
5918
+ /** The message of a write through an import. */
5919
+ function importWrite(name, specifier) {
5920
+ return `Cannot assign to module signal "${name}". Export a function from ${specifier} that writes it, and call that function`;
5921
+ }
5922
+ /** The form that a top-level compile-time function can take instead. */
5923
+ function advice(macro) {
5924
+ switch (macro) {
5925
+ case "$signal": return "Declare a signal on its own, as in \"let count = $signal(0)\"";
5926
+ case "$memo": return "Declare a memo on its own, as in \"const double = $memo(count * 2)\"";
5927
+ case "$gate": return "Declare a gated value on its own, as in \"const query = $gate(input, (prev, next) => next.length >= 2)\"";
5928
+ case "$debounced":
5929
+ case "$throttled": return `Declare a timed value on its own, as in "const typed = ${macro}(input, 300)"`;
5930
+ case "$optimistic": return "Declare an optimistic value on its own, as in \"let shown = $optimistic(list)\"";
5931
+ default: return `Call ${macro} in a component, or in a module function that a component calls with const { … } = name()`;
5932
+ }
5933
+ }
5934
+ /** True when the identifier is a name in a type, not a value. */
5935
+ function inType(node, parents) {
5936
+ for (let at = parents.get(node); at; at = parents.get(at)) {
5937
+ if (at.type.startsWith("TS") && !WRAPPERS$1.has(at.type)) return true;
5938
+ if (at.type === "Program") return false;
5939
+ }
5940
+ return false;
5941
+ }
5942
+ /**
5943
+ * Plans the transform of the top level of a program. Returns undefined when the program declares
5944
+ * no signal or memo there. Throws a `ModuleError` for a form that the top level cannot take.
5945
+ */
5946
+ function planModuleSignals(program, source, scriptModule, path, resolve = resolveFromDisk) {
5947
+ if (path !== void 0) {
5948
+ if (planning.has(path)) return;
5949
+ planning.add(path);
5950
+ }
5951
+ try {
5952
+ return plan(program, source, scriptModule, path, resolve);
5953
+ } finally {
5954
+ if (path !== void 0) planning.delete(path);
5955
+ }
5956
+ }
5957
+ /** The modules that are being planned, so a cycle of imports stops. */
5958
+ const planning = /* @__PURE__ */ new Set();
5959
+ /** The functions that a program declares at its top level, by name. */
5960
+ function topLevelFunctions(program) {
5961
+ const functions = /* @__PURE__ */ new Map();
5962
+ for (const statement of program.body) {
5963
+ const declaration = statement.type === "ExportNamedDeclaration" && statement.declaration ? statement.declaration : statement;
5964
+ if (declaration.type === "FunctionDeclaration" && declaration.id) functions.set(declaration.id.name, declaration);
5965
+ else if (declaration.type === "VariableDeclaration") for (const declarator of declaration.declarations) {
5966
+ const init = declarator.init;
5967
+ if (declarator.id.type === "Identifier" && (init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression")) functions.set(declarator.id.name, init);
5968
+ }
5969
+ }
5970
+ return functions;
5971
+ }
5972
+ function importsOf(program) {
5973
+ const imports = /* @__PURE__ */ new Map();
5974
+ for (const statement of program.body) {
5975
+ if (statement.type !== "ImportDeclaration") continue;
5976
+ for (const item of statement.specifiers) if (item.type === "ImportSpecifier") imports.set(item.local.name, {
5977
+ specifier: statement.source.value,
5978
+ imported: item.imported.type === "Identifier" ? item.imported.name : item.imported.value
5979
+ });
5980
+ }
5981
+ return imports;
5982
+ }
5983
+ /** True for a name that is a write target of a pattern, as `other` in `[other] = values`. */
5984
+ function inPattern(node, parents) {
5985
+ const parent = parents.get(node);
5986
+ if (!parent) return false;
5987
+ switch (parent.type) {
5988
+ case "ArrayPattern":
5989
+ case "RestElement": return true;
5990
+ case "AssignmentPattern": return parent.left === node;
5991
+ case "Property": return parent.value === node && parents.get(parent)?.type === "ObjectPattern";
5992
+ case "ForOfStatement":
5993
+ case "ForInStatement": return parent.left === node;
5994
+ default: return false;
5995
+ }
5996
+ }
5997
+ /**
5998
+ * Rewrites a write of a signal in `edits`: an assignment, an update and `$produce`. Returns
5999
+ * undefined when the identifier is not written, and true when it uses `$produce`.
6000
+ */
6001
+ function rewriteWrite(identifier, store, context, edits) {
6002
+ const { source, parents, macros } = context;
6003
+ const parent = parents.get(identifier);
6004
+ if (parent?.type === "CallExpression" && parent.arguments[0] === identifier) {
6005
+ const callee = parent.callee;
6006
+ if (callee.type === "Identifier" && macros.get(callee.name) === "$produce") {
6007
+ edits.push({
6008
+ start: callee.start,
6009
+ end: identifier.end,
6010
+ text: `${store}.set(${PRODUCE}(${store}.get()`
6011
+ });
6012
+ edits.push({
6013
+ start: parent.end,
6014
+ end: parent.end,
6015
+ text: ")"
6016
+ });
6017
+ return true;
6018
+ }
6019
+ }
6020
+ if (parent?.type === "AssignmentExpression" && parent.left === identifier) {
6021
+ const between = source.slice(identifier.end, parent.right.start);
6022
+ const operator = parent.operator;
6023
+ const at = identifier.end + between.indexOf(operator) + operator.length;
6024
+ if (operator === "=") edits.push({
6025
+ start: identifier.start,
6026
+ end: at,
6027
+ text: `${store}.set(`
6028
+ });
6029
+ else {
6030
+ const binary = operator.slice(0, -1);
6031
+ edits.push({
6032
+ start: identifier.start,
6033
+ end: at,
6034
+ text: `${store}.set(${store}.get() ${binary} (`
6035
+ });
6036
+ edits.push({
6037
+ start: parent.end,
6038
+ end: parent.end,
6039
+ text: ")"
6040
+ });
6041
+ }
6042
+ edits.push({
6043
+ start: parent.end,
6044
+ end: parent.end,
6045
+ text: ")"
6046
+ });
6047
+ return false;
6048
+ }
6049
+ if (parent?.type === "UpdateExpression") {
6050
+ const step = parent.operator === "++" ? "+" : "-";
6051
+ const statement = parents.get(parent)?.type === "ExpressionStatement";
6052
+ edits.push({
6053
+ start: parent.start,
6054
+ end: parent.end,
6055
+ text: parent.prefix || statement ? `${store}.set(${store}.get() ${step} 1)` : `(($v) => (${store}.set($v ${step} 1), $v))(${store}.get())`
6056
+ });
6057
+ return false;
6058
+ }
6059
+ }
6060
+ function linkParents(root) {
6061
+ const parents = /* @__PURE__ */ new Map();
6062
+ function link(node) {
6063
+ for (const [, child] of children(node)) {
6064
+ parents.set(child, node);
6065
+ link(child);
6066
+ }
6067
+ }
6068
+ link(root);
6069
+ return parents;
6070
+ }
6071
+ function plan(program, source, scriptModule, path, resolve) {
6072
+ const macros = macroNames(program);
6073
+ const signals = /* @__PURE__ */ new Map();
6074
+ const ownImports = importsOf(program);
6075
+ if (path !== void 0) for (const [local, { specifier, imported }] of ownImports) {
6076
+ if (!specifier.startsWith(".") || !isReactiveModule(specifier)) continue;
6077
+ const module = resolve(specifier, path);
6078
+ const signal = module && findModuleSignals(module, resolve).get(imported);
6079
+ if (signal) signals.set(local, {
6080
+ kind: signal.kind,
6081
+ binding: local,
6082
+ from: {
6083
+ specifier,
6084
+ name: imported
6085
+ }
6086
+ });
6087
+ }
6088
+ function macroOf(node) {
6089
+ return node?.type === "CallExpression" && node.callee.type === "Identifier" ? macros.get(node.callee.name) : void 0;
6090
+ }
6091
+ function reject(node) {
6092
+ if (isScope(node)) return;
6093
+ const macro = macroOf(node);
6094
+ if (macro && macro !== "$untrack") throw topLevelError(macro, " at the top level, except in a declaration of a signal, a memo, a gate, a debounced or throttled value, or an optimistic value", advice(macro), node.start);
6095
+ for (const [, child] of children(node)) reject(child);
6096
+ }
6097
+ const declarations = [];
6098
+ for (const statement of program.body) {
6099
+ const declaration = statement.type === "ExportNamedDeclaration" && statement.declaration ? statement.declaration : statement;
6100
+ if (declaration.type !== "VariableDeclaration") {
6101
+ if (statement.type !== "ImportDeclaration" && statement.type !== "ExportAllDeclaration" && !(statement.type === "ExportNamedDeclaration" && !statement.declaration)) reject(statement);
6102
+ continue;
6103
+ }
6104
+ let found = false;
6105
+ let formMacro = "";
6106
+ for (const declarator of declaration.declarations) {
6107
+ const macro = macroOf(declarator.init);
6108
+ const made = macro === void 0 ? void 0 : FORMS.get(macro);
6109
+ if (macro === void 0 || made === void 0) {
6110
+ if (declarator.init) reject(declarator.init);
6111
+ continue;
6112
+ }
6113
+ formMacro = macro;
6114
+ if (declarator.id.type !== "Identifier") {
6115
+ if (macro !== "$signal" && macro !== "$memo") throw new ModuleError(`${macro} cannot be destructured`, declarator.id.start);
6116
+ throw topLevelError(macro, " at the top level with a pattern", advice(macro), declarator.start);
6117
+ }
6118
+ if (declaration.declarations.length > 1) throw topLevelError(macro, " at the top level beside other declarations", advice(macro), declaration.start);
6119
+ const expected = macro === "$optimistic" ? "let" : "const";
6120
+ if (macro !== "$signal" && declaration.kind !== expected) {
6121
+ if (macro !== "$memo") throw new ModuleError(`Declare ${macro} with ${expected}`, declaration.start);
6122
+ throw topLevelError(macro, ` at the top level with ${declaration.kind}`, advice(macro), declaration.start);
6123
+ }
6124
+ signals.set(declarator.id.name, {
6125
+ kind: made,
6126
+ form: macro,
6127
+ ...macro === "$optimistic" ? { optimistic: true } : {},
6128
+ binding: scriptModule ? `${PREFIX}${declarator.id.name}` : declarator.id.name,
6129
+ ...statement === declaration ? {} : { exported: declarator.id.name }
6130
+ });
6131
+ found = true;
6132
+ }
6133
+ if (found) declarations.push({
6134
+ declaration,
6135
+ exported: statement === declaration ? void 0 : statement,
6136
+ macro: formMacro
6137
+ });
6138
+ }
6139
+ if (signals.size === 0) return;
6140
+ for (const statement of program.body) if (statement.type === "ExportNamedDeclaration" && !statement.declaration && !statement.source) for (const specifier of statement.specifiers) {
6141
+ const local = specifier.local.type === "Identifier" ? specifier.local.name : "";
6142
+ const signal = signals.get(local);
6143
+ if (signal) signal.exported = specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value;
6144
+ }
6145
+ const parents = linkParents(program);
6146
+ const edits = [];
6147
+ let usesStore = false;
6148
+ let usesDerived = false;
6149
+ let usesProduce = false;
6150
+ let usesOptimistic = false;
6151
+ /** The imports of signals of other modules, by module and name, shared by every memo. */
6152
+ const dependencies = /* @__PURE__ */ new Map();
6153
+ const own = {
6154
+ path,
6155
+ signals,
6156
+ functions: topLevelFunctions(program),
6157
+ imports: ownImports
6158
+ };
6159
+ const contexts = /* @__PURE__ */ new Map();
6160
+ /** The context of another module, to follow the helpers that a memo calls in it. */
6161
+ function contextOf(specifier, name, from, at) {
6162
+ const module = from === void 0 ? void 0 : resolve(specifier, from);
6163
+ if (!module) throw topLevelError(name, " because the memo cannot follow it", "Pass the signals that it reads as arguments, as in \"$memo(total(items))\"", at);
6164
+ let context = contexts.get(module.path);
6165
+ if (!context) {
6166
+ const inner = parseModule(module).program;
6167
+ const innerPlan = planModuleSignals(inner, module.source, false, module.path, resolve);
6168
+ context = {
6169
+ path: module.path,
6170
+ signals: innerPlan?.signals ?? /* @__PURE__ */ new Map(),
6171
+ functions: topLevelFunctions(inner),
6172
+ imports: importsOf(inner)
6173
+ };
6174
+ contexts.set(module.path, context);
6175
+ }
6176
+ return context;
6177
+ }
6178
+ /** Finds the signals that an expression reads, through the functions that it calls. */
6179
+ function memoSources(argument, reads, stores) {
6180
+ const seen = /* @__PURE__ */ new Set();
6181
+ function add(context, name, at) {
6182
+ const signal = context.signals.get(name);
6183
+ if (context === own) {
6184
+ if (!reads.includes(name)) {
6185
+ reads.push(name);
6186
+ stores.push(signal.binding);
6187
+ }
6188
+ return;
6189
+ }
6190
+ let target;
6191
+ if (signal.from) target = {
6192
+ specifier: signal.from.specifier,
6193
+ name: signal.from.name
6194
+ };
6195
+ else if (signal.exported) target = {
6196
+ specifier: `./${context.path.split("/").pop()}`,
6197
+ name: signal.exported
6198
+ };
6199
+ if (!target) throw topLevelError(name, " because the memo cannot follow it", `Export it from ${context.path.split("/").pop()}, so this module can read it`, at);
6200
+ const specifier = relocate(target.specifier, context.path, path);
6201
+ const key = `${specifier}#${target.name}`;
6202
+ let dependency = dependencies.get(key);
6203
+ if (!dependency) {
6204
+ const local = `$$dep_${target.name}_${dependencies.size}`;
6205
+ dependency = {
6206
+ local,
6207
+ line: `import { ${target.name} as ${local} } from '${specifier}';`
6208
+ };
6209
+ dependencies.set(key, dependency);
6210
+ }
6211
+ if (!reads.includes(dependency.local)) {
6212
+ reads.push(dependency.local);
6213
+ stores.push(dependency.local);
6214
+ }
6215
+ }
6216
+ function walk(node, context) {
6217
+ forEachReference(node, (identifier) => {
6218
+ const name = identifier.name;
6219
+ if (context === own && isUntracked(identifier)) return;
6220
+ if (context.signals.has(name)) {
6221
+ add(context, name, identifier.start);
6222
+ return;
6223
+ }
6224
+ const helper = context.functions.get(name);
6225
+ if (helper) {
6226
+ if (!seen.has(helper)) {
6227
+ seen.add(helper);
6228
+ walk(helper, context);
6229
+ }
6230
+ return;
6231
+ }
6232
+ const from = context.imports.get(name);
6233
+ if (from && from.specifier.startsWith(".") && isReactiveModule(from.specifier)) {
6234
+ const inner = contextOf(from.specifier, name, context.path, identifier.start);
6235
+ const helperNode = inner.functions.get(from.imported);
6236
+ if (!helperNode) {
6237
+ if (!inner.signals.has(from.imported)) throw topLevelError(name, " because the memo cannot follow it", "Pass the signals that it reads as arguments, as in \"$memo(total(items))\"", identifier.start);
6238
+ return;
6239
+ }
6240
+ if (!seen.has(helperNode)) {
6241
+ seen.add(helperNode);
6242
+ walk(helperNode, inner);
6243
+ }
6244
+ }
6245
+ });
6246
+ }
6247
+ walk(argument, own);
6248
+ }
6249
+ const untracked = [];
6250
+ function findUntracked(node) {
6251
+ if (macroOf(node) === "$untrack") {
6252
+ const call = node;
6253
+ if (call.arguments.length !== 1 || call.arguments[0].type === "SpreadElement") throw topLevelError("$untrack", " with other than one expression", "Write one expression, as in \"$untrack(input.length)\"", call.start);
6254
+ untracked.push({
6255
+ start: call.start,
6256
+ end: call.end
6257
+ });
6258
+ edits.push({
6259
+ start: call.callee.start,
6260
+ end: call.callee.end,
6261
+ text: ""
6262
+ });
6263
+ }
6264
+ for (const [, child] of children(node)) findUntracked(child);
6265
+ }
6266
+ for (const statement of program.body) if (statement.type !== "ImportDeclaration") findUntracked(statement);
6267
+ function isUntracked(node) {
6268
+ for (const range of untracked) if (node.start >= range.start && node.end <= range.end) return true;
6269
+ return false;
6270
+ }
6271
+ const memoArguments = [];
6272
+ /** The names that each memo gets as parameters. */
6273
+ const memoReads = /* @__PURE__ */ new Map();
6274
+ for (const { declaration, exported, macro } of declarations) {
6275
+ const declarator = declaration.declarations[0];
6276
+ const call = declarator.init;
6277
+ const name = declarator.id.name;
6278
+ const signal = signals.get(name);
6279
+ edits.push({
6280
+ start: declaration.start,
6281
+ end: declaration.start + declaration.kind.length,
6282
+ text: "const"
6283
+ });
6284
+ if (scriptModule) {
6285
+ edits.push({
6286
+ start: declarator.id.start,
6287
+ end: declarator.id.end,
6288
+ text: signal.binding
6289
+ });
6290
+ if (exported) {
6291
+ edits.push({
6292
+ start: exported.start,
6293
+ end: declaration.start,
6294
+ text: ""
6295
+ });
6296
+ edits.push({
6297
+ start: declaration.end,
6298
+ end: declaration.end,
6299
+ text: ` export { ${signal.binding} as ${name} };`
6300
+ });
6301
+ }
6302
+ }
6303
+ if (macro === "$signal") {
6304
+ usesStore = true;
6305
+ edits.push({
6306
+ start: call.callee.start,
6307
+ end: call.callee.end,
6308
+ text: STORE
6309
+ });
6310
+ continue;
6311
+ }
6312
+ if (macro === "$optimistic") {
6313
+ const [source] = call.arguments;
6314
+ if (!source) throw new ModuleError(`${macro} needs a value`, call.start);
6315
+ if (call.arguments.length > 1) throw new ModuleError(`${macro} takes one argument`, call.start);
6316
+ if (source.type !== "Identifier") throw new ModuleError("$optimistic needs the name of a value, such as a memo", source.start);
6317
+ const followed = signals.get(source.name);
6318
+ if (followed?.kind === "signal") throw new ModuleError("$optimistic follows a memo, an action or a prop, not a signal", source.start);
6319
+ if (!followed) throw topLevelError("$optimistic", " with a source that is no memo of a module", "Follow a memo that the module declares or imports, as in \"let shown = $optimistic(list)\"", source.start);
6320
+ usesOptimistic = true;
6321
+ edits.push({
6322
+ start: call.callee.start,
6323
+ end: call.callee.end,
6324
+ text: OPTIMISTIC
6325
+ });
6326
+ edits.push({
6327
+ start: source.start,
6328
+ end: source.end,
6329
+ text: followed.binding
6330
+ });
6331
+ memoArguments.push(source);
6332
+ continue;
6333
+ }
6334
+ const [argument, extra] = call.arguments;
6335
+ const count = macro === "$memo" ? 1 : 2;
6336
+ if (macro === "$memo") {
6337
+ if (!argument || call.arguments.length !== 1 || argument.type === "SpreadElement") throw topLevelError(macro, " at the top level with other than one argument", advice(macro), call.start);
6338
+ } else if (macro === "$gate") {
6339
+ if (!argument || argument.type === "SpreadElement" || call.arguments.length !== count || extra?.type !== "ArrowFunctionExpression" && extra?.type !== "FunctionExpression") throw new ModuleError("$gate takes a value and a function, as in $gate(value, (prev, next) => next > prev)", call.start);
6340
+ } else {
6341
+ if (!argument || argument.type === "SpreadElement" || call.arguments.length !== count) throw new ModuleError(`${macro} takes a value and a wait in milliseconds`, call.start);
6342
+ const ms = extra?.type === "Literal" && typeof extra.value === "number" ? extra.value : NaN;
6343
+ if (!(ms >= 0 && ms <= 2147483647)) throw new ModuleError(`The wait of ${macro} must be a number of milliseconds, such as 300`, extra?.start ?? call.start);
6344
+ }
6345
+ let awaits = false;
6346
+ function findAwait(node) {
6347
+ if (node.type === "AwaitExpression") {
6348
+ if (macro === "$memo") {
6349
+ awaits = true;
6350
+ return;
6351
+ }
6352
+ if (macro === "$gate") throw new ModuleError("$gate takes a value that is ready. Use $memo for a promise or a server function", node.start);
6353
+ throw topLevelError(macro, " at the top level with await", "Keep the loaded value in a $signal, or read it in a component with $memo", node.start);
6354
+ }
6355
+ if (!isScope(node)) for (const [, child] of children(node)) findAwait(child);
6356
+ }
6357
+ findAwait(argument);
6358
+ memoArguments.push(argument);
6359
+ const reads = [];
6360
+ const stores = [];
6361
+ memoSources(argument, reads, stores);
6362
+ memoReads.set(argument, reads);
6363
+ const typed = call.typeArguments;
6364
+ const open = source.indexOf("(", typed?.end ?? call.callee.end);
6365
+ usesDerived = true;
6366
+ if (awaits) signal.awaits = true;
6367
+ edits.push({
6368
+ start: call.callee.start,
6369
+ end: open + 1,
6370
+ text: `${DERIVED}([${stores.join(", ")}], ${awaits ? "async " : ""}([${reads.join(", ")}]) => (`
6371
+ });
6372
+ const named = [];
6373
+ for (const read of reads) named.push(read.startsWith("$$dep_") ? read.slice(6, read.lastIndexOf("_")) : read);
6374
+ const sourceNames = JSON.stringify(named);
6375
+ if (macro === "$memo") edits.push({
6376
+ start: call.end - 1,
6377
+ end: call.end - 1,
6378
+ text: `), { n: ${sourceNames} }`
6379
+ });
6380
+ else {
6381
+ edits.push({
6382
+ start: argument.end,
6383
+ end: argument.end,
6384
+ text: ")"
6385
+ });
6386
+ const key = macro === "$gate" ? "g" : "m";
6387
+ edits.push({
6388
+ start: extra.start,
6389
+ end: extra.start,
6390
+ text: `{ ${key}: `
6391
+ });
6392
+ edits.push({
6393
+ start: extra.end,
6394
+ end: extra.end,
6395
+ text: `${macro === "$throttled" ? ", t: true" : ""}, n: ${sourceNames} }`
6396
+ });
6397
+ }
6398
+ }
6399
+ /** True where a parameter of the memo holds the value, so the name stays as it is. */
6400
+ function insideMemo(node) {
6401
+ for (const argument of memoArguments) if (node.start >= argument.start && node.end <= argument.end) return !isUntracked(node) || !!memoReads.get(argument)?.includes(node.name);
6402
+ return false;
6403
+ }
6404
+ function rewrite(identifier, shorthand) {
6405
+ const signal = signals.get(identifier.name);
6406
+ if (!signal || insideMemo(identifier) || inType(identifier, parents)) return;
6407
+ if (inPattern(identifier, parents)) throw topLevelError(identifier.name, " in a destructuring write", `Write it with an assignment of its own, as in "${identifier.name} = value"`, identifier.start);
6408
+ const store = signal.binding;
6409
+ const update = parents.get(identifier);
6410
+ if (signal.optimistic && update?.type === "UpdateExpression") throw new ModuleError(`Assign to "${identifier.name}" with = instead of ${update.operator}`, update.start);
6411
+ const written = rewriteWrite(identifier, store, {
6412
+ source,
6413
+ parents,
6414
+ macros
6415
+ }, edits);
6416
+ if (written !== void 0) {
6417
+ if (signal.from) throw new ModuleError(importWrite(identifier.name, signal.from.specifier), identifier.start);
6418
+ if (signal.kind === "memo") throw new ModuleError(MEMO_WRITE(identifier.name), identifier.start);
6419
+ usesProduce ||= written;
6420
+ return;
6421
+ }
6422
+ edits.push({
6423
+ start: identifier.start,
6424
+ end: identifier.end,
6425
+ text: shorthand ? `${identifier.name}: ${store}.get()` : `${store}.get()`
6426
+ });
6427
+ }
6428
+ for (const statement of program.body) {
6429
+ if (statement.type === "ImportDeclaration" || statement.type === "ExportAllDeclaration" || statement.type === "ExportNamedDeclaration" && !statement.declaration || statement.type.startsWith("TS")) continue;
6430
+ forEachReference(statement, rewrite);
6431
+ }
6432
+ const header = [];
6433
+ const names = [];
6434
+ if (usesStore) names.push(`store as ${STORE}`);
6435
+ if (usesDerived) names.push(`${HELD} as ${DERIVED}`);
6436
+ if (names.length > 0) header.push(`import { ${names.join(", ")} } from '${STORE_MODULE}';`);
6437
+ const client = [];
6438
+ if (usesProduce) client.push(`produce as ${PRODUCE}`);
6439
+ if (usesOptimistic) client.push(`optimisticStore as ${OPTIMISTIC}`);
6440
+ if (client.length > 0) header.push(`import { ${client.join(", ")} } from '${CLIENT_MODULE}';`);
6441
+ for (const { line } of dependencies.values()) header.push(line);
6442
+ return {
6443
+ edits,
6444
+ signals,
6445
+ header: header.join(" ")
6446
+ };
6447
+ }
6448
+ /** Applies edits to a source, and tells where each offset of the result comes from. */
6449
+ function applyEdits(source, edits) {
6450
+ const sorted = edits.toSorted((a, b) => a.start - b.start || a.end - b.end);
6451
+ const pieces = [];
6452
+ let text = "";
6453
+ let position = 0;
6454
+ for (const edit of sorted) {
6455
+ if (edit.start < position) continue;
6456
+ const kept = source.slice(position, edit.start);
6457
+ pieces.push({
6458
+ start: text.length,
6459
+ length: kept.length,
6460
+ from: position,
6461
+ linear: true
6462
+ });
6463
+ text += kept;
6464
+ pieces.push({
6465
+ start: text.length,
6466
+ length: edit.text.length,
6467
+ from: edit.start,
6468
+ linear: false
6469
+ });
6470
+ text += edit.text;
6471
+ position = edit.end;
6472
+ }
6473
+ const rest = source.slice(position);
6474
+ pieces.push({
6475
+ start: text.length,
6476
+ length: rest.length,
6477
+ from: position,
6478
+ linear: true
6479
+ });
6480
+ text += rest;
6481
+ return {
6482
+ text,
6483
+ origin(offset) {
6484
+ let low = 0;
6485
+ let high = pieces.length - 1;
6486
+ while (low < high) {
6487
+ const middle = low + high + 1 >> 1;
6488
+ if (pieces[middle].start <= offset) low = middle;
6489
+ else high = middle - 1;
6490
+ }
6491
+ const piece = pieces[low];
6492
+ return piece.linear ? piece.from + Math.min(offset - piece.start, piece.length) : piece.from;
6493
+ }
6494
+ };
6495
+ }
6496
+ function parseTypeScript(module) {
6497
+ const result = parseSync(module.path, module.source, {
6498
+ lang: "ts",
6499
+ preserveParens: false
6500
+ });
6501
+ const error = result.errors[0];
6502
+ if (error) throw new ModuleError(`${error.message} (${module.path})`, 0);
6503
+ return result.program;
6504
+ }
6505
+ const found = /* @__PURE__ */ new WeakMap();
6506
+ /**
6507
+ * The signals and memos that a module exports, by exported name. Empty for a module that has none,
6508
+ * and for one that does not parse.
6509
+ */
6510
+ function findModuleSignals(module, resolve = resolveFromDisk) {
6511
+ let result = found.get(module);
6512
+ if (!result) {
6513
+ result = /* @__PURE__ */ new Map();
6514
+ if (module.path.endsWith(".brm")) try {
6515
+ const file = parse$1(module.source, { filename: module.path });
6516
+ if (file.moduleScript) {
6517
+ const plan = planModuleSignals(file.moduleScript.program, module.source, true, module.path, resolve);
6518
+ for (const signal of plan?.signals.values() ?? []) if (signal.exported && !signal.from) result.set(signal.exported, signal);
6519
+ }
6520
+ } catch {}
6521
+ else if (module.source.includes("brumate/signals")) try {
6522
+ const plan = planModuleSignals(parseTypeScript(module), module.source, false, module.path, resolve);
6523
+ for (const signal of plan?.signals.values() ?? []) if (signal.exported && !signal.from) result.set(signal.exported, signal);
6524
+ } catch {}
6525
+ found.set(module, result);
6526
+ }
6527
+ return result;
6528
+ }
6529
+ /** The code of a module with its signals and memos compiled, or undefined when it has none. */
6530
+ function transformModuleSignals(module, resolve = resolveFromDisk) {
6531
+ if (!module.source.includes("brumate/signals")) return;
6532
+ const plan = planModuleSignals(parseTypeScript(module), module.source, false, module.path, resolve);
6533
+ if (!plan) return;
6534
+ const { text } = applyEdits(module.source, plan.edits);
6535
+ return `${plan.header}\n${text}`;
6536
+ }
6537
+ function escapePattern(name) {
6538
+ return name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6539
+ }
6540
+ /** The offset after the opening tag of a script. */
6541
+ function afterTag(source, start) {
6542
+ return start + source.slice(start).indexOf(">") + 1;
6543
+ }
6544
+ /**
6545
+ * Compiles the module signals of a component. Those of its `<script module>` get a store of their
6546
+ * own, and the instance script reads them like `$store`. The names that it imports from a module
6547
+ * with signals do the same. Returns undefined when it has none.
6548
+ */
6549
+ function expandSignals(file, path, resolve, fromModule = () => false) {
6550
+ const source = file.source;
6551
+ const edits = [];
6552
+ const names = /* @__PURE__ */ new Map();
6553
+ const modules = [];
6554
+ const declarations = [];
6555
+ const moduleScript = file.moduleScript;
6556
+ let own;
6557
+ if (moduleScript) own = planModuleSignals(moduleScript.program, source, true, path, resolve);
6558
+ if (moduleScript && own) {
6559
+ edits.push(...own.edits);
6560
+ if (own.header) edits.push({
6561
+ start: afterTag(source, moduleScript.start),
6562
+ end: afterTag(source, moduleScript.start),
6563
+ text: `\n${own.header}`
6564
+ });
6565
+ }
6566
+ const program = file.instanceScript?.program;
6567
+ const imported = [];
6568
+ if (program) for (const statement of program.body) {
6569
+ if (statement.type !== "ImportDeclaration") continue;
6570
+ const specifier = statement.source.value;
6571
+ if (!(isReactiveModule(specifier) || specifier.endsWith(".brm") || !specifier.startsWith(".") && specifier !== "brumate/signals" && isReactiveModule(resolve(specifier, path)?.path ?? ""))) continue;
6572
+ const module = resolve(specifier, path);
6573
+ if (!module) continue;
6574
+ const exports = findModuleSignals(module, resolve);
6575
+ for (const item of statement.specifiers) {
6576
+ if (item.type !== "ImportSpecifier") continue;
6577
+ const name = item.imported.type === "Identifier" ? item.imported.name : item.imported.value;
6578
+ const signal = exports.get(name);
6579
+ if (!signal) continue;
6580
+ if (!modules.includes(module)) modules.push(module);
6581
+ imported.push({
6582
+ local: item.local.name,
6583
+ imported: name,
6584
+ specifier,
6585
+ kind: signal.kind
6586
+ });
6587
+ names.set(item.local.name, {
6588
+ specifier,
6589
+ memo: signal.kind === "memo"
6590
+ });
6591
+ edits.push({
6592
+ start: item.start,
6593
+ end: item.end,
6594
+ text: `${name} as ${PREFIX}${item.local.name}`
6595
+ });
6596
+ declarations.push(readSignal(item.local.name, `${PREFIX}${item.local.name}`, signal, false));
6597
+ }
6598
+ }
6599
+ if (moduleScript && own) {
6600
+ const outside = source.slice(0, moduleScript.start) + source.slice(moduleScript.end);
6601
+ const taken = /* @__PURE__ */ new Set();
6602
+ for (const statement of program?.body ?? []) if (statement.type === "VariableDeclaration") for (const declarator of statement.declarations) for (const id of getPatternNames(declarator.id)) taken.add(id.name);
6603
+ else if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && statement.id) taken.add(statement.id.name);
6604
+ for (const [name, signal] of own.signals) {
6605
+ if (signal.from || taken.has(name) || !new RegExp(`(?<![\\w$.])${escapePattern(name)}(?![\\w$])`).test(outside)) continue;
6606
+ names.set(name, { memo: signal.kind === "memo" });
6607
+ declarations.push(readSignal(name, signal.binding, signal, true));
6608
+ }
6609
+ }
6610
+ const writable = /* @__PURE__ */ new Map();
6611
+ for (const item of imported) if (item.kind === "signal") writable.set(item.local, `${PREFIX}${item.local}`);
6612
+ if (writable.size > 0 && program) {
6613
+ const macros = macroNames(program);
6614
+ let produce = false;
6615
+ for (const script of scripts(file)) {
6616
+ const parents = linkParents(script);
6617
+ forEachReference(script, (identifier) => {
6618
+ const store = writable.get(identifier.name);
6619
+ if (!store || !fromModule(identifier.start) || inType(identifier, parents)) return;
6620
+ produce ||= rewriteWrite(identifier, store, {
6621
+ source,
6622
+ parents,
6623
+ macros
6624
+ }, edits) === true;
6625
+ });
6626
+ }
6627
+ if (produce) declarations.unshift(`import { produce as ${PRODUCE} } from '${CLIENT_MODULE}';`);
6628
+ }
6629
+ if (declarations.length === 0 && !(own && edits.length > 0)) return;
6630
+ if (declarations.length > 0) {
6631
+ const body = declarations.join("\n");
6632
+ const memo = body.includes(`${MEMO}(`) ? `, $memo as ${MEMO}` : "";
6633
+ const text = `import { $store as ${READ}${memo} } from '${SIGNALS_MODULE}';\n${body}`;
6634
+ if (file.instanceScript && program) {
6635
+ let at = afterTag(source, file.instanceScript.start);
6636
+ for (const statement of program.body) if (statement.type === "ImportDeclaration") at = Math.max(at, statement.end);
6637
+ edits.push({
6638
+ start: at,
6639
+ end: at,
6640
+ text: `\n${text}`
6641
+ });
6642
+ } else {
6643
+ const at = moduleScript?.end ?? 0;
6644
+ edits.push({
6645
+ start: at,
6646
+ end: at,
6647
+ text: `\n<script>\n${text}\n<\/script>\n`
6648
+ });
6649
+ }
6650
+ }
6651
+ const applied = applyEdits(source, edits);
6652
+ return {
6653
+ source: applied.text,
6654
+ origin: applied.origin,
6655
+ names,
6656
+ modules
6657
+ };
6658
+ }
6659
+ /**
6660
+ * The module signals that a script file imports from a module. A plain `.ts` file gets the store
6661
+ * object, while TypeScript says that the value is its type.
6662
+ */
6663
+ function findSignalImports(source, file, resolve) {
6664
+ if (!source.includes(".brm.")) return [];
6665
+ const result = parseSync(file, source, { lang: /\.[cm]?js$/.test(file) ? "js" : "ts" });
6666
+ if (result.errors.length > 0) return [];
6667
+ const imports = [];
6668
+ for (const statement of result.program.body) {
6669
+ if (statement.type !== "ImportDeclaration" || !isReactiveModule(statement.source.value)) continue;
6670
+ const module = resolve(statement.source.value, file);
6671
+ if (!module) continue;
6672
+ const exports = findModuleSignals(module, resolve);
6673
+ for (const item of statement.specifiers) {
6674
+ if (item.type !== "ImportSpecifier") continue;
6675
+ const name = item.imported.type === "Identifier" ? item.imported.name : item.imported.value;
6676
+ if (exports.has(name)) imports.push({
6677
+ name,
6678
+ start: item.start,
6679
+ end: item.end,
6680
+ specifier: statement.source.value
6681
+ });
6682
+ }
6683
+ }
6684
+ return imports;
6685
+ }
6686
+ //#endregion
5617
6687
  //#region src/codegen/primitive.ts
5618
6688
  /**
5619
6689
  * True if an expression always gives a primitive, so it is never a promise
@@ -5708,6 +6778,11 @@ var Patch = class {
5708
6778
  text
5709
6779
  });
5710
6780
  }
6781
+ /** Adds an argument after the last one of a call, before its closing parenthesis. */
6782
+ appendArgument(call, text) {
6783
+ const tail = this.source.slice(call.arguments.at(-1).end, call.end - 1).replace(/\/\*[^]*?\*\/|\/\/[^\n]*/g, "");
6784
+ this.insert(call.end - 1, /,\s*$/.test(tail) ? text : `, ${text}`);
6785
+ }
5711
6786
  insert(offset, text) {
5712
6787
  this.edits.push({
5713
6788
  start: offset,
@@ -6009,7 +7084,7 @@ function heldMemos(file, sites, inline, settled) {
6009
7084
  return true;
6010
7085
  }
6011
7086
  }
6012
- function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE__ */ new Set(), lazy = /* @__PURE__ */ new Set(), component) {
7087
+ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE__ */ new Set(), lazy = /* @__PURE__ */ new Set(), component, nameProduce = false) {
6013
7088
  const sitesByNode = /* @__PURE__ */ new Map();
6014
7089
  const propNames = /* @__PURE__ */ new Map();
6015
7090
  const restCalls = /* @__PURE__ */ new Set();
@@ -6135,6 +7210,7 @@ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE_
6135
7210
  }
6136
7211
  if (name === "$produce" && argument?.type === "Identifier") {
6137
7212
  patch.replace(node.start, argument.start, `(${argument.name} = $$b.produce(`);
7213
+ if (nameProduce && node.arguments.length === 2) patch.appendArgument(node, JSON.stringify(argument.name));
6138
7214
  patch.insert(node.end, ")");
6139
7215
  for (const rest of node.arguments.slice(1)) visit(rest);
6140
7216
  return;
@@ -6248,6 +7324,7 @@ function analyze(module) {
6248
7324
  const macros = /* @__PURE__ */ new Map();
6249
7325
  for (const [local, from] of info.imports) if (from.specifier === "brumate/signals" && MACROS.has(from.imported)) macros.set(local, from.imported);
6250
7326
  const sites = /* @__PURE__ */ new Map();
7327
+ const signals = planModuleSignals(info.program, module.source, false, module.path)?.signals;
6251
7328
  for (const fn of info.functions.values()) {
6252
7329
  const body = fn.body;
6253
7330
  if (body?.type !== "BlockStatement") continue;
@@ -6282,6 +7359,9 @@ function analyze(module) {
6282
7359
  for (const [, child] of children(current)) check(child);
6283
7360
  }
6284
7361
  check(node);
7362
+ if (signals) forEachReference(node, (identifier) => {
7363
+ if (signals.has(identifier.name) && !locals.has(identifier.name)) shareable = false;
7364
+ });
6285
7365
  if (!shareable) continue;
6286
7366
  const reads = /* @__PURE__ */ new Set();
6287
7367
  const writes = /* @__PURE__ */ new Set();
@@ -6631,7 +7711,7 @@ function scopeTarget(compound) {
6631
7711
  return target;
6632
7712
  }
6633
7713
  /**
6634
- * Adds the scope attribute to every compound selector, except inside
7714
+ * Adds the scope attribute, inside `:where(…)` so it adds no specificity, to every compound selector, except inside
6635
7715
  * `:global(…)`. Each scoped compound goes into `targets`. With `unscoped`, no
6636
7716
  * compound is scoped, and `:global(…)` is only unwrapped.
6637
7717
  */
@@ -6689,10 +7769,15 @@ function scopeSelector(attribute, targets, unscoped) {
6689
7769
  break;
6690
7770
  }
6691
7771
  }
6692
- const scope = selectorParser.attribute({
7772
+ const inner = selectorParser.selector({ value: "" });
7773
+ inner.append(selectorParser.attribute({
6693
7774
  attribute,
6694
7775
  value: void 0,
6695
7776
  raws: {}
7777
+ }));
7778
+ const scope = selectorParser.pseudo({
7779
+ value: ":where",
7780
+ nodes: [inner]
6696
7781
  });
6697
7782
  if (last) selector.insertAfter(last, scope);
6698
7783
  else selector.insertBefore(compound[0], scope);
@@ -7137,7 +8222,7 @@ function clientState(graph, file) {
7137
8222
  slots
7138
8223
  };
7139
8224
  }
7140
- function createPlan(file, graph, path, hideNames = false) {
8225
+ function createPlan(file, graph, path, hideNames = false, styleFiles = false) {
7141
8226
  const model = graph.model;
7142
8227
  const name = getComponentName(file.filename);
7143
8228
  const bodyScopes = /* @__PURE__ */ new Map();
@@ -7400,6 +8485,7 @@ function createPlan(file, graph, path, hideNames = false) {
7400
8485
  styles,
7401
8486
  liveBlocks,
7402
8487
  hideNames,
8488
+ styleFiles,
7403
8489
  scopes,
7404
8490
  bodyScopes,
7405
8491
  anchors,
@@ -7409,6 +8495,8 @@ function createPlan(file, graph, path, hideNames = false) {
7409
8495
  elementItems,
7410
8496
  symbols,
7411
8497
  childrenRenders,
8498
+ scripts: false,
8499
+ viewTransitions: false,
7412
8500
  blockHolders,
7413
8501
  clientSites,
7414
8502
  diagnostics
@@ -8049,13 +9137,14 @@ function cloneLines(emitter, hoist, fn = 0, owner) {
8049
9137
  lines.push(`${indent}${line}`);
8050
9138
  return;
8051
9139
  }
8052
- const key = `${memos.scope} ${memos.names.join(" ")}`;
9140
+ const key = `${memos.scope} ${memos.names.join(" ")}${memos.pend ? ` ${settled.size}` : ""}`;
8053
9141
  let group = settled.get(key);
8054
9142
  if (!group) {
8055
9143
  group = {
8056
9144
  scope: memos.scope,
8057
9145
  names: memos.names,
8058
- writes: []
9146
+ writes: [],
9147
+ pend: memos.pend
8059
9148
  };
8060
9149
  settled.set(key, group);
8061
9150
  }
@@ -8096,7 +9185,9 @@ function cloneLines(emitter, hoist, fn = 0, owner) {
8096
9185
  }
8097
9186
  for (const group of settled.values()) {
8098
9187
  const names = group.names.join(", ");
8099
- lines.push(`${indent}$$b.fillSettled(${group.scope}, [${names}], (${names}) => { ${group.writes.join(" ")} });`);
9188
+ const writes = group.writes.join(" ");
9189
+ const body = group.pend ? `$$b.fillPend(${group.scope}, () => { ${writes} });` : writes;
9190
+ lines.push(group.pend && names === "" ? `${indent}${body}` : `${indent}$$b.fillSettled(${group.scope}, [${names}], (${names}) => { ${body} });`);
8100
9191
  }
8101
9192
  if (missing) return false;
8102
9193
  const sizes = /* @__PURE__ */ new Map();
@@ -8531,6 +9622,26 @@ const PLAIN_METHODS = /* @__PURE__ */ new Set([
8531
9622
  "trimStart"
8532
9623
  ]);
8533
9624
  /**
9625
+ * True if a value of markup calls code that can read a memo that is still loading: a function
9626
+ * prop, or a function of the component that reads a memo, also through the functions it calls. The
9627
+ * browser render waits for the memo, as an update does.
9628
+ */
9629
+ function callsPending(site) {
9630
+ if (!site) return false;
9631
+ if (site.opaqueCalls) return true;
9632
+ const seen = /* @__PURE__ */ new Set();
9633
+ function reads(from) {
9634
+ if (seen.has(from)) return false;
9635
+ seen.add(from);
9636
+ if (from.opaqueCalls) return true;
9637
+ for (const read of from.reads) if (isMemo(read.declaration)) return true;
9638
+ for (const callee of from.calls) if (callee.kind === "function" && callee.site && reads(callee.site)) return true;
9639
+ return false;
9640
+ }
9641
+ for (const callee of site.calls) if (callee.kind === "function" && callee.site && reads(callee.site)) return true;
9642
+ return false;
9643
+ }
9644
+ /**
8534
9645
  * True if a value of markup can be a promise, which the browser writes once it settles: a call,
8535
9646
  * such as `{load(id)}` or `title=getTitle()`, or a read of a prop typed as a promise. A call of a
8536
9647
  * macro of brumate, such as `$isPending`, of `String` or of a method of strings and arrays, such
@@ -9157,6 +10268,14 @@ var Emitter = class {
9157
10268
  this.parts.push(part);
9158
10269
  }
9159
10270
  /**
10271
+ * In the browser, the code of a value of markup that calls code that can read a memo that is
10272
+ * still loading. The value is a promise then, which the clone waits for.
10273
+ */
10274
+ pended(code, expression, scope) {
10275
+ const promise = this.promiseScope(expression, scope);
10276
+ return promise && callsPending(this.sitesByNode.get(expression.ast)) ? `$$b.pend(() => (${code}), ${promise})` : code;
10277
+ }
10278
+ /**
9160
10279
  * In the browser, the scope of a value of markup that can be a promise: one that calls code,
9161
10280
  * such as `{load(id)}`, or reads a prop typed as a promise. The clone writes its value once it
9162
10281
  * settles, and a `#loading` around it shows its fallback until then.
@@ -9169,21 +10288,29 @@ var Emitter = class {
9169
10288
  * promise, such as an insert, the headers of a block or the props of a component. No update
9170
10289
  * writes them when the memos settle, so the clone holds back what reads them.
9171
10290
  */
9172
- settledMemos(expressions, scope) {
10291
+ settledMemos(expressions, scope, waits = true) {
9173
10292
  if (this.options.mode !== "client") return;
9174
10293
  const names = [];
10294
+ let pend = false;
9175
10295
  for (const expression of expressions) {
9176
10296
  const site = this.sitesByNode.get(expression.ast);
9177
10297
  if (!site || this.liveSites.has(site)) return;
10298
+ pend ||= waits && callsPending(site);
9178
10299
  for (const reference of site.reads) {
9179
10300
  const declaration = reference.declaration;
9180
10301
  if (isMemo(declaration) && !isNeverPromise(declaration) && !this.splitMemos.has(declaration) && !names.includes(declaration.name)) names.push(declaration.name);
9181
10302
  }
9182
10303
  }
9183
- return names.length > 0 ? {
10304
+ if (names.length === 0 && !pend) return;
10305
+ const own = this.scopeVar(instanceScope(this.plan, scope));
10306
+ return pend ? {
10307
+ names,
10308
+ scope: own,
10309
+ pend
10310
+ } : {
9184
10311
  names,
9185
- scope: this.scopeVar(instanceScope(this.plan, scope))
9186
- } : void 0;
10312
+ scope: own
10313
+ };
9187
10314
  }
9188
10315
  flush() {
9189
10316
  if (this.parts.length === 0) return;
@@ -9810,8 +10937,11 @@ var Emitter = class {
9810
10937
  emitComponentContent(setup) {
9811
10938
  const component = this.plan.graph.model.component;
9812
10939
  if (this.plan.styles.css) {
9813
- if (this.options.mode === "client") this.line(`${this.helper("style")}(${JSON.stringify(this.plan.id)}, $$css);`);
9814
- else this.code(`${this.helper("style")}(${JSON.stringify(this.plan.id)}, $$css)`);
10940
+ const id = JSON.stringify(this.plan.id);
10941
+ if (this.plan.styleFiles) {
10942
+ if (this.options.mode !== "client") this.code(`${this.helper("style")}(${id})`);
10943
+ } else if (this.options.mode === "client") this.line(`${this.helper("style")}(${id}, $$css);`);
10944
+ else this.code(`${this.helper("style")}(${id}, $$css)`);
9815
10945
  }
9816
10946
  this.emitStatements(setup, component);
9817
10947
  this.awaitMarkup(component, this.file.instanceScript?.program.end ?? 0);
@@ -9940,9 +11070,10 @@ var Emitter = class {
9940
11070
  let rest = server && spacer !== void 0 ? `, ${JSON.stringify(spacer)}` : "";
9941
11071
  if (server && anchor) rest = `${rest || ", undefined"}, ${anchor.index}`;
9942
11072
  const at = this.options.mode === "server" || readsProp || callsTemplate(site) ? `, ${this.ctxArgument}, ${this.scopeVar(instanceScope(this.plan, scope))}${rest}` : "";
9943
- const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${this.expression(node.expression)})` : this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
11073
+ const inner = this.pended(this.expression(node.expression), node.expression, scope);
11074
+ const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${inner})` : this.ready(`$$b.insert(${inner}${at})`);
9944
11075
  const text = literalText(node.expression.ast);
9945
- const settled = this.settledMemos([node.expression], scope);
11076
+ const settled = this.settledMemos([node.expression], scope, !this.promiseScope(node.expression, scope));
9946
11077
  const promise = this.promiseScope(node.expression, scope);
9947
11078
  const emitValue = () => text === void 0 ? this.code(value, settled, promise) : this.html(text);
9948
11079
  if (anchor && !this.plan.contents.has(node)) {
@@ -10155,16 +11286,48 @@ var Emitter = class {
10155
11286
  if (!declaration || slot === -1) return;
10156
11287
  return `\`\${${this.scopeVar(instanceScope(this.plan, declaration.scope))}}:${slot}\``;
10157
11288
  }
11289
+ /**
11290
+ * `viewTransition` and `viewTransitionName` on an element are written as `b-vt` and `b-vtn`,
11291
+ * which the runtime turns into `view-transition-*` styles while a transition runs. On a
11292
+ * component or a dynamic tag they stay props, which a spread onto an element renders as `b-vt`
11293
+ * and `b-vtn` in the runtime (`spread` of html.ts). Both set the feature. A spread of data that
11294
+ * the file does not write, such as `{...fromServer}`, does not, so the file that writes the
11295
+ * name on a component or an element must be in the app.
11296
+ */
11297
+ viewTransitionAttributes(attributes, rename = false) {
11298
+ let result = attributes;
11299
+ for (let index = 0; index < attributes.length; index++) {
11300
+ const attribute = attributes[index];
11301
+ if (attribute.kind !== "static" && attribute.kind !== "value") continue;
11302
+ let name;
11303
+ if (attribute.name === "viewTransition") name = "b-vt";
11304
+ else if (attribute.name === "viewTransitionName") name = "b-vtn";
11305
+ if (name === void 0) continue;
11306
+ this.plan.viewTransitions = true;
11307
+ if (!rename) continue;
11308
+ if (result === attributes) result = [...attributes];
11309
+ result[index] = {
11310
+ ...attribute,
11311
+ name
11312
+ };
11313
+ }
11314
+ return result;
11315
+ }
10158
11316
  emitElement(node, scope) {
11317
+ const script = node.script;
11318
+ if (script) this.plan.scripts = true;
11319
+ const plain = script !== void 0 && script.head && script.trigger === void 0 && this.options.mode === "server";
11320
+ const tag = script && !plain ? "template" : node.tag;
11321
+ const attributes = this.viewTransitionAttributes(script ? node.attributes.filter((attribute) => attribute.kind !== "static" || attribute.name !== "trigger" && attribute.name !== "inline") : node.attributes, true);
10159
11322
  const pageTitle = node.tag === "title" && this.headBlocks > 0;
10160
11323
  if (pageTitle && this.options.mode === "server") this.line(`${this.helper("title")}(${this.titleText(node)}, true);`);
10161
11324
  let spreadHandlers;
10162
- if (hasSpread(node.attributes)) {
11325
+ if (hasSpread(attributes)) {
10163
11326
  spreadHandlers = this.unique("on");
10164
11327
  this.line(`const ${spreadHandlers}: string[] = [];`);
10165
11328
  }
10166
- this.html(`<${node.tag}`);
10167
- for (const name of this.scopeAttributes(scope, node.tag, staticClasses(node.attributes))) this.html(` ${name}`);
11329
+ this.html(`<${tag}`);
11330
+ for (const name of script ? [] : this.scopeAttributes(scope, node.tag, staticClasses(attributes))) this.html(` ${name}`);
10168
11331
  const anchor = this.anchor(scope, node);
10169
11332
  if (anchor && spreadHandlers) {
10170
11333
  this.html(" b-b=\"");
@@ -10173,9 +11336,9 @@ var Emitter = class {
10173
11336
  }
10174
11337
  const variables = this.emitVariables(node, scope);
10175
11338
  const events = [];
10176
- const merged = hasSpread(node.attributes) ? [] : void 0;
11339
+ const merged = hasSpread(attributes) ? [] : void 0;
10177
11340
  let liveSpread = false;
10178
- for (const attribute of node.attributes) {
11341
+ for (const attribute of attributes) {
10179
11342
  const site = attribute.kind === "spread" ? this.sitesByNode.get(attribute.value.ast) : void 0;
10180
11343
  if (site !== void 0 && this.plan.clientSites.has(site)) {
10181
11344
  liveSpread = true;
@@ -10186,7 +11349,7 @@ var Emitter = class {
10186
11349
  if (liveSpread) return `, ${handlers ?? "undefined"}, true`;
10187
11350
  return handlers ? `, ${handlers}` : "";
10188
11351
  }
10189
- for (const attribute of node.attributes) {
11352
+ for (const attribute of attributes) {
10190
11353
  if (variables && !merged && (attribute.kind === "static" || attribute.kind === "value") && attribute.name === "style") continue;
10191
11354
  if (merged && this.mergedAttribute(node, attribute, scope, merged)) continue;
10192
11355
  switch (attribute.kind) {
@@ -10204,8 +11367,8 @@ var Emitter = class {
10204
11367
  this.emitClasses(classes);
10205
11368
  break;
10206
11369
  }
10207
- const call = `$$b.attribute(${JSON.stringify(attribute.name)}, ${this.expression(attribute.value)})`;
10208
- this.code(isPrimitive(attribute.value.ast) ? call : this.ready(call), this.settledMemos([attribute.value], scope), this.promiseScope(attribute.value, scope));
11370
+ const call = `$$b.attribute(${JSON.stringify(attribute.name)}, ${this.pended(this.expression(attribute.value), attribute.value, scope)})`;
11371
+ this.code(isPrimitive(attribute.value.ast) ? call : this.ready(call), this.settledMemos([attribute.value], scope, !this.promiseScope(attribute.value, scope)), this.promiseScope(attribute.value, scope));
10209
11372
  const bound = this.bindEntry(node, attribute, scope);
10210
11373
  if (bound) events.unshift(bound);
10211
11374
  break;
@@ -10223,11 +11386,11 @@ var Emitter = class {
10223
11386
  }
10224
11387
  }
10225
11388
  if (merged) {
10226
- const forwards = anchor !== void 0 && this.spreadsRest(node.attributes);
10227
- const attributes = `$$b.mergeAttributes([${merged.join(", ")}]${variables ? `, ${variables}` : ""})`;
11389
+ const forwards = anchor !== void 0 && this.spreadsRest(attributes);
11390
+ const mergedCall = `$$b.mergeAttributes([${merged.join(", ")}]${variables ? `, ${variables}` : ""})`;
10228
11391
  let promise;
10229
- for (const attribute of node.attributes) if (attribute.kind === "value" || attribute.kind === "spread") promise ??= this.promiseScope(attribute.value, scope);
10230
- this.code(this.ready(`$$b.spread(${forwards ? `${this.helper("restRef")}(${attributes}, ${anchor.scope}, ${anchor.index})` : attributes}${spreadArguments(spreadHandlers)})`), void 0, promise);
11392
+ for (const attribute of attributes) if (attribute.kind === "value" || attribute.kind === "spread") promise ??= this.promiseScope(attribute.value, scope);
11393
+ this.code(this.ready(`$$b.spread(${forwards ? `${this.helper("restRef")}(${mergedCall}, ${anchor.scope}, ${anchor.index})` : mergedCall}${spreadArguments(spreadHandlers)})`), void 0, promise);
10231
11394
  }
10232
11395
  if (anchor && !spreadHandlers) {
10233
11396
  this.html(" b-b=\"");
@@ -10239,6 +11402,18 @@ var Emitter = class {
10239
11402
  if (pageTitle) this.html(" b-t");
10240
11403
  if (spreadHandlers) this.code(`$$b.onAttribute(${spreadHandlers}, ${JSON.stringify(events.join(" "))})`);
10241
11404
  else if (events.length > 0) this.html(` b-on="${events.join(" ")}"`);
11405
+ if (script) {
11406
+ if (!plain) this.html(` b-script="${script.trigger ?? "load"}"`);
11407
+ if (this.options.mode === "server") this.code(`$$b.attribute('nonce', $$ctx.nonce)`);
11408
+ this.html(">");
11409
+ if (script.inline) {
11410
+ const [text] = node.children;
11411
+ const code = text?.kind === "text" ? text.value : "";
11412
+ this.html(plain ? code : `<script>${code}<\/script>`);
11413
+ }
11414
+ this.html(`</${tag}>`);
11415
+ return;
11416
+ }
10242
11417
  this.html(">");
10243
11418
  if (VOID_ELEMENTS.has(node.tag)) return;
10244
11419
  this.nesting++;
@@ -10463,6 +11638,7 @@ var Emitter = class {
10463
11638
  return code;
10464
11639
  }
10465
11640
  emitComponent(node, scope) {
11641
+ this.viewTransitionAttributes(node.attributes);
10466
11642
  const childrenName = this.emitChildren(node, scope);
10467
11643
  const props = this.props(node.attributes, scope, childrenName ? [`children: ${childrenName}`] : []);
10468
11644
  const anchor = this.anchor(scope, node);
@@ -10486,6 +11662,7 @@ var Emitter = class {
10486
11662
  this.code(`${this.wait}$$b.component(${node.name}, ${props}, ${this.ctxArgument}, ${owner}${link})`, this.settledMemos(values, scope));
10487
11663
  }
10488
11664
  emitDynamic(node, scope) {
11665
+ this.viewTransitionAttributes(node.attributes);
10489
11666
  const childrenName = this.emitChildren(node, scope);
10490
11667
  const extra = [];
10491
11668
  for (const name of this.scopeAttributes(scope, void 0, staticClasses(node.attributes))) extra.push(`${JSON.stringify(name)}: $$b.internal(true)`);
@@ -10716,12 +11893,17 @@ var Emitter = class {
10716
11893
  const anchor = fill && this.anchor(scope, block);
10717
11894
  if (!fill || !anchor) return false;
10718
11895
  let call;
11896
+ const headers = [];
10719
11897
  if (fill.kind === "if" && block.kind === "if") {
11898
+ for (const branch of block.branches) headers.push(branch.condition);
10720
11899
  let index = block.fallback ? String(block.branches.length) : "-1";
10721
11900
  for (let at = block.branches.length - 1; at >= 0; at--) index = `${this.expression(block.branches[at].condition)} ? ${at} : ${index}`;
10722
11901
  call = `$$b.fillBranch($$m, ${anchor.scope}, ${anchor.index}, ${index}, [${fill.renders.join(", ")}])`;
10723
- } else if (fill.kind === "for" && block.kind === "for") call = `$$b.fillList($$m, ${anchor.scope}, ${anchor.index}, $$b.toList(${this.expression(block.list)}), ${fill.render})`;
10724
- else return false;
11902
+ } else if (fill.kind === "for" && block.kind === "for") {
11903
+ headers.push(block.list);
11904
+ call = `$$b.fillList($$m, ${anchor.scope}, ${anchor.index}, $$b.toList(${this.expression(block.list)}), ${fill.render})`;
11905
+ } else return false;
11906
+ if (this.settledMemos(headers, scope)?.pend) call = `$$b.fillPend(${anchor.scope}, () => { ${call}; })`;
10725
11907
  this.open(scope, block, fill.kind === "if" ? "-1" : void 0);
10726
11908
  this.end(block);
10727
11909
  this.fills.set(`${anchor.scope}:${anchor.index}`, call);
@@ -11112,7 +12294,7 @@ function generateServer(file, plan) {
11112
12294
  const inline = plainValues(plan, blocking);
11113
12295
  const lazy = lazyMemos(blocking, inline);
11114
12296
  for (const declaration of bodyMemos(plan, blocking, inline)) lazy.add(declaration);
11115
- addValueEdits(patch, file, model.sites, "server", inline, lazy, model.component.id);
12297
+ addValueEdits(patch, file, model.sites, "server", inline, lazy, model.component.id, !plan.hideNames);
11116
12298
  addEventEdits(patch, model);
11117
12299
  function source(node) {
11118
12300
  return patch.slice(node.start, node.end);
@@ -11153,7 +12335,7 @@ function generateServer(file, plan) {
11153
12335
  for (const declaration of serverFunctions(plan)) exported.push(`${JSON.stringify(serverFunctionId(plan, declaration.name))}: ${declaration.name}`);
11154
12336
  moduleBody.push(`export const rpc = { ${exported.join(", ")} };`);
11155
12337
  for (const declaration of serverFunctions(plan)) moduleBody.push(`${declaration.name} = $$b.dedupe(${declaration.name}, ${JSON.stringify(serverFunctionId(plan, declaration.name))});`);
11156
- if (plan.styles.css) {
12338
+ if (plan.styles.css && !plan.styleFiles) {
11157
12339
  const css = plan.hideNames ? minifyCSS(plan.styles.css) : plan.styles.css;
11158
12340
  moduleBody.push(`const $$css = ${JSON.stringify(css)};`);
11159
12341
  }
@@ -11312,7 +12494,7 @@ function awaitsPromise(plan) {
11312
12494
  function generateRender(file, plan, getFill) {
11313
12495
  const model = plan.graph.model;
11314
12496
  const patch = new Patch(file.source);
11315
- addValueEdits(patch, file, model.sites, "render", void 0, void 0, model.component.id);
12497
+ addValueEdits(patch, file, model.sites, "render", void 0, void 0, model.component.id, !plan.hideNames);
11316
12498
  const names = componentNames(file.children);
11317
12499
  for (const template of file.templates) bodyNames(template.body, names);
11318
12500
  for (const site of model.sites) if (!SKIPPED_SITES.has(site.kind)) for (const read of site.reads) names.add(read.declaration.name);
@@ -11355,7 +12537,7 @@ function generateRender(file, plan, getFill) {
11355
12537
  }
11356
12538
  const setup = [];
11357
12539
  for (const statement of file.instanceScript?.program.body ?? []) if (statement.type !== "ImportDeclaration" && !TYPE_DECLARATIONS.has(statement.type)) setup.push(statement);
11358
- if (plan.styles.css) {
12540
+ if (plan.styles.css && !plan.styleFiles) {
11359
12541
  const css = plan.hideNames ? minifyCSS(plan.styles.css) : plan.styles.css;
11360
12542
  moduleBody.push(`const $$css = ${JSON.stringify(css)};`);
11361
12543
  }
@@ -11577,6 +12759,7 @@ var Rewriter = class {
11577
12759
  patch.replace(node.start, node.end, "undefined");
11578
12760
  return;
11579
12761
  } else patch.replace(node.start, target.end, `(${target.name} = $$b.produce(${target.name}`);
12762
+ if (!this.plan.hideNames && node.arguments.length === 2) patch.appendArgument(node, JSON.stringify(target.name));
11580
12763
  patch.insert(node.end, ")");
11581
12764
  for (const argument of node.arguments.slice(1)) visit(argument);
11582
12765
  }
@@ -11840,6 +13023,10 @@ const DEFERRED_SITES = /* @__PURE__ */ new Set([
11840
13023
  "effect",
11841
13024
  "client"
11842
13025
  ]);
13026
+ /** The core function that runs an effect: an `async` callback needs `asyncEffect`. */
13027
+ function effectCall(callback) {
13028
+ return callback.async ? "asyncEffect" : "effect";
13029
+ }
11843
13030
  /** Whether a scope is within any scope of the list. */
11844
13031
  function isWithinAny(scope, list) {
11845
13032
  for (const item of list) if (isWithin(scope, item)) return true;
@@ -11886,7 +13073,7 @@ var ClientGenerator = class {
11886
13073
  this.shared = shared;
11887
13074
  this.rewriter = new Rewriter(file, plan, this.diagnostics, shared);
11888
13075
  this.valuePatch = new Patch(file.source);
11889
- addValueEdits(this.valuePatch, file, plan.graph.model.sites, "client");
13076
+ addValueEdits(this.valuePatch, file, plan.graph.model.sites, "client", void 0, void 0, void 0, !plan.hideNames);
11890
13077
  for (const node of plan.graph.nodes) if (node.kind !== "source" && plan.graph.live.has(node)) this.live.set(node.site, node);
11891
13078
  }
11892
13079
  get model() {
@@ -12394,7 +13581,7 @@ var ClientGenerator = class {
12394
13581
  if (site.node.type === "FunctionExpression" && unmarked(code).trimStart().startsWith("(")) code = `function ${code}`;
12395
13582
  this.part = symbol;
12396
13583
  if (symbol.startsWith("t")) this.emitTemplateArgs(site, symbol);
12397
- if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.effect($$s, ${JSON.stringify(symbol)}, ${code}, 1);\n}`);
13584
+ if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.${effectCall(site.node)}($$s, ${JSON.stringify(symbol)}, ${code}, 1);\n}`);
12398
13585
  else this.emit(this.handlerExport(site, symbol, code, base));
12399
13586
  }
12400
13587
  }
@@ -12459,7 +13646,7 @@ var ClientGenerator = class {
12459
13646
  break;
12460
13647
  }
12461
13648
  case "effect":
12462
- this.emit(`export function ${name("e")}($$s) {\n $$b.effect($$s, ${JSON.stringify(`e${site.id}`)}, ${expression()});\n}`);
13649
+ this.emit(`export function ${name("e")}($$s) {\n $$b.${effectCall(site.node)}($$s, ${JSON.stringify(`e${site.id}`)}, ${expression()});\n}`);
12463
13650
  break;
12464
13651
  case "binding":
12465
13652
  this.emitBinding(node, site, expression, name, classes);
@@ -13260,10 +14447,11 @@ function expand(source, filename, path, resolve) {
13260
14447
  let origin = identity;
13261
14448
  const modules = /* @__PURE__ */ new Map();
13262
14449
  let calls = [];
13263
- for (let round = 0;; round++) {
14450
+ /** Compiles the module signals of the component, which the last round left. */
14451
+ function finishSignals() {
13264
14452
  let expansion;
13265
14453
  try {
13266
- expansion = expandModules(file, path, resolve);
14454
+ expansion = expandSignals(file, path, resolve, (offset) => origin(offset).module !== void 0);
13267
14455
  } catch (error) {
13268
14456
  if (error instanceof ModuleError) {
13269
14457
  const at = origin(error.offset);
@@ -13278,12 +14466,50 @@ function expand(source, filename, path, resolve) {
13278
14466
  }
13279
14467
  throw error;
13280
14468
  }
13281
- if (!expansion) return {
14469
+ const done = {
13282
14470
  file,
13283
14471
  origin,
13284
14472
  modules: [...modules.values()],
13285
- calls
14473
+ calls,
14474
+ signals: /* @__PURE__ */ new Map(),
14475
+ signalModules: []
13286
14476
  };
14477
+ if (!expansion) return done;
14478
+ const previous = origin;
14479
+ const next = expansion.origin;
14480
+ try {
14481
+ done.file = parse$1(expansion.source, { filename });
14482
+ } catch (error) {
14483
+ if (error instanceof BrumateError) {
14484
+ const at = previous(next(error.offset));
14485
+ throw new BrumateError(error.message.replace(/ \([^()]*:\d+:\d+\)$/, "").replace(/ \[BRM\d+\]$/, ""), source, at.call?.start ?? at.offset, filename);
14486
+ }
14487
+ throw error;
14488
+ }
14489
+ done.origin = (offset) => previous(next(offset));
14490
+ done.signals = expansion.names;
14491
+ done.signalModules = expansion.modules;
14492
+ return done;
14493
+ }
14494
+ for (let round = 0;; round++) {
14495
+ let expansion;
14496
+ try {
14497
+ expansion = expandModules(file, path, resolve);
14498
+ } catch (error) {
14499
+ if (error instanceof ModuleError) {
14500
+ const at = origin(error.offset);
14501
+ throw new CompileError(source, filename, [{
14502
+ severity: "error",
14503
+ message: error.message,
14504
+ range: at.call ?? {
14505
+ start: at.offset,
14506
+ end: at.offset + 1
14507
+ }
14508
+ }]);
14509
+ }
14510
+ throw error;
14511
+ }
14512
+ if (!expansion) return finishSignals();
13287
14513
  if (round === 0) calls = expansion.calls;
13288
14514
  if (round === MAX_EXPANSIONS) throw new CompileError(source, filename, [{
13289
14515
  severity: "error",
@@ -13359,7 +14585,7 @@ function sharedContext(origin, modules, calls, path) {
13359
14585
  }
13360
14586
  function compile(source, options = {}) {
13361
14587
  const filename = options.filename ?? "Component.brm";
13362
- const { file, origin, modules, calls } = expand(source, filename, options.path ?? filename, options.resolveModule ?? resolveFromDisk);
14588
+ const { file, origin, modules, calls, signals, signalModules } = expand(source, filename, options.path ?? filename, options.resolveModule ?? resolveFromDisk);
13363
14589
  function translate(diagnostic) {
13364
14590
  const start = origin(diagnostic.range.start);
13365
14591
  if (!start.module) {
@@ -13386,7 +14612,7 @@ function compile(source, options = {}) {
13386
14612
  for (const error of errors) translated.push(translate(error));
13387
14613
  throw new CompileError(source, filename, translated);
13388
14614
  }
13389
- const model = analyze$1(file);
14615
+ const model = analyze$1(file, signals);
13390
14616
  for (const declaration of model.declarations) if (declaration.imported && options.serverImport) {
13391
14617
  declaration.serverImport = options.serverImport(declaration.imported.source, declaration.imported.name);
13392
14618
  if (declaration.serverImport !== void 0) {
@@ -13420,7 +14646,11 @@ function compile(source, options = {}) {
13420
14646
  ];
13421
14647
  const errors = filterBySeverity(diagnostics, "error");
13422
14648
  if (errors.length > 0) fail(errors);
13423
- const plan = createPlan(file, graph, options.path, options.hideNames);
14649
+ const plan = createPlan(file, graph, options.path, options.hideNames, options.styleFiles);
14650
+ if (options.css !== void 0) plan.styles = {
14651
+ ...plan.styles,
14652
+ css: options.css
14653
+ };
13424
14654
  const styleErrors = filterBySeverity([...plan.styles.diagnostics, ...plan.diagnostics], "error");
13425
14655
  if (styleErrors.length > 0) fail(styleErrors);
13426
14656
  const captures = [...checkCaptures(file, plan, options.sendableClasses), ...options.envImport ? checkEnv(file, plan, options.envImport) : []];
@@ -13459,7 +14689,7 @@ function compile(source, options = {}) {
13459
14689
  const warnings = [];
13460
14690
  for (const warning of filterBySeverity(diagnostics, "warning")) warnings.push(translate(warning));
13461
14691
  const modulePaths = [];
13462
- for (const module of modules) modulePaths.push(module.path);
14692
+ for (const module of [...modules, ...signalModules]) modulePaths.push(module.path);
13463
14693
  const render = done(generateRender(file, plan, client.fillOf));
13464
14694
  return {
13465
14695
  server: server.code,
@@ -13679,6 +14909,6 @@ function inspect(source, options = {}) {
13679
14909
  };
13680
14910
  }
13681
14911
  //#endregion
13682
- export { analyzeProjectProps as A, isWithin as B, resolveFromDisk as C, entryClasses as D, unmarked as E, parse$1 as F, bridgeModuleId as G, resolveMacros as H, buildGraph as I, nameBridges as J, hasBridge as K, blockBodies as L, importedComponents as M, resolveRelative as N, refreshedNames as O, summarize as P, getLocation as Q, forEachNode as R, isReactiveModule as S, originalPosition as T, walk as U, lookup as V, BRIDGE_EXPORT as W, getPatternNames as X, scriptBridges as Y, BrumateError as Z, getComponentName as _, scopeLabel as a, generateShared as b, DEFAULT_MERGE as c, generateServer as d, instanceScope as f, functionId as g, createPlan as h, report as i, importSource as j, analyzeProject as k, generateClient as l, clientState as m, formatReport as n, CompileError as o, slotIndex as p, mayHaveBridge as q, inspect as r, compile as s, anchorLabel as t, generateRender as u, hash as v, builtin as w, sharedSites as x, SHARED_QUERY as y, analyze$1 as z };
14912
+ export { scriptBridges as $, unmarked as A, buildGraph as B, planModuleSignals as C, resolveFromDisk as D, isReactiveModule as E, importSource as F, lookup as G, forEachNode as H, importedComponents as I, BRIDGE_EXPORT as J, resolveMacros as K, resolveRelative as L, refreshedNames as M, analyzeProject as N, builtin as O, analyzeProjectProps as P, nameBridges as Q, summarize as R, findSignalImports as S, ModuleError as T, analyze$1 as U, blockBodies as V, isWithin as W, hasBridge as X, bridgeModuleId as Y, mayHaveBridge as Z, getComponentName as _, scopeLabel as a, generateShared as b, DEFAULT_MERGE as c, generateServer as d, getPatternNames as et, instanceScope as f, functionId as g, createPlan as h, report as i, entryClasses as j, originalPosition as k, generateClient as l, clientState as m, formatReport as n, getLocation as nt, CompileError as o, slotIndex as p, walk as q, inspect as r, withCode as rt, compile as s, anchorLabel as t, BrumateError as tt, generateRender as u, hash as v, transformModuleSignals as w, sharedSites as x, SHARED_QUERY as y, parse$1 as z };
13683
14913
 
13684
- //# sourceMappingURL=inspect-CGl5Y8q6.js.map
14914
+ //# sourceMappingURL=inspect-fpaBJ5pm.js.map