@deviltea/widget-core 0.0.6 → 0.1.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.
package/dist/index.mjs CHANGED
@@ -1,18 +1,18 @@
1
- import { a as runRuntimeOperation, i as invokeListenerIsolated, n as createEventPrimitive, o as writeDeferringFlush, r as createTrackedSubscription, t as buildEventEmitter } from "./event-BMif_vRJ.mjs";
2
- import { a as createWidgetPlugin, c as readWidgetPluginDefinition, i as WIDGET_CONFIG_JSON_SCHEMA_DIALECT, l as createReadonlyMap, o as createWidgetValueContract, r as runtimeInternals, s as isCoreWidgetPlugin } from "./internals-L391flXY.mjs";
1
+ import { C as EMPTY_DIAGNOSTICS, S as runOutsideCallbacks, T as WidgetSystemRuntimeReentrancyError, _ as setIsolatedErrorHandler, a as throwClosedCallbackMember, b as createCallbackOwner, c as createTrackedSubscription, d as invokeListenerIsolated, f as isEngineStackOverflow, g as runRuntimeWrite, h as runRuntimeOperation, i as assertSyncValue, l as deliverWhenIdle, m as readUntracked, n as createEventPrimitive, o as throwClosedCollector, p as isRuntimeIdle, r as createMethodEmitFragment, s as createDistinctTrackedSubscription, u as endBatchDeferringFlush, v as writeDeferringFlush, w as WidgetSystemRuntimeDisposedError, x as createRuntimeContext, y as callbackScope } from "./event-Bk-mkL1E.mjs";
2
+ import { a as createWidgetPlugin, c as readWidgetPluginDefinition, i as WIDGET_CONFIG_JSON_SCHEMA_DIALECT, l as createReadonlyMap, o as createWidgetValueContract, r as runtimeInternals, s as isCoreWidgetPlugin } from "./internals-CVKUQDIN.mjs";
3
3
  import { a as readCompiledBlueprint, n as compiledDependencyBrand, r as isCompiledDependency, t as blueprintInternals } from "./contract-CRpMqCY2.mjs";
4
- import { computed, endBatch, signal, startBatch } from "alien-signals";
5
- //#region src/diagnostic.ts
6
- const EMPTY_DIAGNOSTICS = Object.freeze([]);
7
- var WidgetSystemRuntimeDisposedError = class extends Error {
8
- name = "WidgetSystemRuntimeDisposedError";
9
- code = "runtime-disposed";
10
- constructor(message = "The widget system runtime has been disposed.") {
11
- super(message);
12
- }
13
- };
14
- //#endregion
4
+ import { computed, endBatch, getActiveSub, setActiveSub, signal, startBatch } from "alien-signals";
15
5
  //#region src/json.ts
6
+ /**
7
+ * The maximum JSON nesting depth of authored source and SourcePatch operands: the number of containers
8
+ * (objects and arrays) a value may be nested inside, counting the value's own container. A value nested
9
+ * deeper is outside the JSON domain (`json-incompatible-value`, reason `max-depth-exceeded`) and is never
10
+ * descended into, so arbitrarily deep input yields a diagnostic or an operation failure instead of exhausting
11
+ * the call stack. A widget node nests three containers per tree level (node, `slots`, slot Array), so the
12
+ * limit allows widget trees about 85 levels deep. The value leaves a wide margin below the call-stack limit of
13
+ * Node 22/24 and of smaller-stack embedded engines, and is part of the public contract.
14
+ */
15
+ const MAX_JSON_DEPTH = 256;
16
16
  function jsonDiagnostic(path, reason) {
17
17
  return {
18
18
  code: "json-incompatible-value",
@@ -31,9 +31,11 @@ function accessDiagnostic(path) {
31
31
  };
32
32
  }
33
33
  /**
34
- * `path` is one shared stack, pushed before and popped after each child visit; diagnostics copy it.
34
+ * `path` is one shared stack, pushed before and popped after each child visit; diagnostics copy it. With
35
+ * `firstOnly` the walk stops at the first diagnostic, so a caller that only needs to know whether (and where
36
+ * first) a value leaves the JSON domain never diagnoses the rest of it.
35
37
  */
36
- function inspectJsonValueAt(value, path, active, diagnostics) {
38
+ function inspectJsonValueAt(value, path, active, diagnostics, depth, firstOnly) {
37
39
  if (value === null || typeof value === "string" || typeof value === "boolean") return;
38
40
  if (typeof value === "number") {
39
41
  if (!Number.isFinite(value)) diagnostics.push(jsonDiagnostic(path, "non-finite-number"));
@@ -56,6 +58,10 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
56
58
  return;
57
59
  }
58
60
  if (typeof value !== "object") return;
61
+ if (depth >= 256) {
62
+ diagnostics.push(jsonDiagnostic(path, "max-depth-exceeded"));
63
+ return;
64
+ }
59
65
  let isArray;
60
66
  try {
61
67
  isArray = Array.isArray(value);
@@ -101,6 +107,7 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
101
107
  return;
102
108
  }
103
109
  for (const key of keys) {
110
+ if (firstOnly && diagnostics.length > 0) return;
104
111
  if (typeof key === "symbol") {
105
112
  diagnostics.push(jsonDiagnostic([...path, key], "symbol-key"));
106
113
  continue;
@@ -110,6 +117,7 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
110
117
  diagnostics.push(jsonDiagnostic([...path, key], "array-extra-property"));
111
118
  }
112
119
  for (let index = 0; index < length; index++) {
120
+ if (firstOnly && diagnostics.length > 0) return;
113
121
  let descriptor;
114
122
  try {
115
123
  descriptor = Object.getOwnPropertyDescriptor(value, String(index));
@@ -126,12 +134,13 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
126
134
  continue;
127
135
  }
128
136
  path.push(index);
129
- inspectJsonValueAt(descriptor.value, path, active, diagnostics);
137
+ inspectJsonValueAt(descriptor.value, path, active, diagnostics, depth + 1, firstOnly);
130
138
  path.pop();
131
139
  }
132
140
  return;
133
141
  }
134
142
  for (const key of keys) {
143
+ if (firstOnly && diagnostics.length > 0) return;
135
144
  if (typeof key === "symbol") {
136
145
  diagnostics.push(jsonDiagnostic([...path, key], "symbol-key"));
137
146
  continue;
@@ -152,7 +161,7 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
152
161
  continue;
153
162
  }
154
163
  path.push(key);
155
- inspectJsonValueAt(descriptor.value, path, active, diagnostics);
164
+ inspectJsonValueAt(descriptor.value, path, active, diagnostics, depth + 1, firstOnly);
156
165
  path.pop();
157
166
  }
158
167
  } finally {
@@ -166,14 +175,53 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
166
175
  */
167
176
  function inspectJsonValue(value) {
168
177
  const diagnostics = [];
169
- inspectJsonValueAt(value, [], /* @__PURE__ */ new Set(), diagnostics);
178
+ inspectJsonValueAt(value, [], /* @__PURE__ */ new Set(), diagnostics, 0, false);
170
179
  return {
171
180
  compatible: diagnostics.length === 0,
172
181
  diagnostics
173
182
  };
174
183
  }
184
+ /**
185
+ * The first diagnostic {@link inspectJsonValue} reports for `value`, found by the same walk, or `null` when
186
+ * `value` is inside the JSON domain. The walk stops there instead of diagnosing the rest of the value.
187
+ */
188
+ function findFirstJsonViolation(value) {
189
+ const diagnostics = [];
190
+ inspectJsonValueAt(value, [], /* @__PURE__ */ new Set(), diagnostics, 0, true);
191
+ return diagnostics[0] ?? null;
192
+ }
193
+ const JSON_PARSE_PROVEN = Object.freeze({
194
+ compatible: true,
195
+ diagnostics: Object.freeze([])
196
+ });
197
+ /**
198
+ * {@link inspectJsonValue} for a value Core itself produced with `JSON.parse` (no reviver). Such a value
199
+ * is made only of plain objects, arrays, strings, booleans, `null` and numbers, so the only way it can be
200
+ * outside the JSON domain is a non-finite number (`JSON.parse('1e400')` is `Infinity`) or nesting deeper
201
+ * than {@link MAX_JSON_DEPTH}. A cheap iterative scan therefore stands in for the full descriptor-level
202
+ * inspection; as soon as it finds anything the scan cannot prove, the full inspection supplies the exact
203
+ * diagnostics.
204
+ */
205
+ function inspectParsedJsonValue(value) {
206
+ const pending = [value];
207
+ const depths = [0];
208
+ while (pending.length > 0) {
209
+ const current = pending.pop();
210
+ const depth = depths.pop();
211
+ if (typeof current === "number") {
212
+ if (!Number.isFinite(current)) return inspectJsonValue(value);
213
+ } else if (typeof current === "object" && current !== null) {
214
+ if (depth >= 256) return inspectJsonValue(value);
215
+ for (const child of Array.isArray(current) ? current : Object.values(current)) {
216
+ pending.push(child);
217
+ depths.push(depth + 1);
218
+ }
219
+ }
220
+ }
221
+ return JSON_PARSE_PROVEN;
222
+ }
175
223
  function isJsonValue(value) {
176
- return inspectJsonValue(value).compatible;
224
+ return findFirstJsonViolation(value) === null;
177
225
  }
178
226
  /**
179
227
  * SameValueZero: `+0` equals `-0` and `NaN` equals `NaN`. Used only for SourcePatch comparisons
@@ -216,10 +264,12 @@ function jsonEqual(left, right, seen = /* @__PURE__ */ new Set()) {
216
264
  //#region src/source-patch.ts
217
265
  const PATCH_ERROR_MESSAGES = {
218
266
  "invalid-path": "The SourcePath is malformed.",
267
+ "invalid-operation": "The SourcePatch operation is malformed.",
219
268
  "path-not-found": "The SourcePath does not identify an existing location.",
220
269
  "path-not-traversable": "The SourcePath passes through a non-traversable value.",
221
270
  "invalid-array-index": "The SourcePath contains an invalid Array index.",
222
271
  "invalid-move-target": "The move destination is invalid relative to its source.",
272
+ "max-depth-exceeded": "The SourcePatch path or the addressed value is nested deeper than the maximum JSON depth.",
223
273
  "test-failed": "The test operation did not match the addressed value.",
224
274
  "json-incompatible-value": "The SourcePatch operand is outside the JSON value domain.",
225
275
  "source-access-failed": "The source could not be inspected safely."
@@ -233,7 +283,19 @@ function failure(code, message = PATCH_ERROR_MESSAGES[code]) {
233
283
  }
234
284
  };
235
285
  }
286
+ /**
287
+ * The most segments a SourcePatch path may have: the longest source path of a widget node a Blueprint
288
+ * materializes. Recovery stops at a node nested inside `MAX_JSON_DEPTH` or more containers, and that node is
289
+ * three segments (`slots`, slot name, index) below a parent nested inside fewer, so its path has at most
290
+ * `MAX_JSON_DEPTH + 2` segments. Removing or replacing exactly that node must stay possible.
291
+ */
292
+ const MAX_PATH_SEGMENTS = 258;
236
293
  function parsePath(path) {
294
+ const parsed = parsePathSegments(path);
295
+ if (parsed.ok && parsed.value.segments.length > MAX_PATH_SEGMENTS) return failure("max-depth-exceeded");
296
+ return parsed;
297
+ }
298
+ function parsePathSegments(path) {
237
299
  if (typeof path === "string") {
238
300
  if (path === "") return {
239
301
  ok: true,
@@ -527,12 +589,13 @@ function copyValue(value, canonicalizeNegativeZero = false) {
527
589
  value
528
590
  };
529
591
  const seen = /* @__PURE__ */ new WeakMap();
530
- function clone(current) {
592
+ function clone(current, depth) {
531
593
  const previous = seen.get(current);
532
594
  if (previous !== void 0) return {
533
595
  ok: true,
534
596
  value: previous
535
597
  };
598
+ if (depth > 256) return failure("max-depth-exceeded");
536
599
  const result = createContainer(current);
537
600
  if (!result.ok) return result;
538
601
  seen.set(current, result.value);
@@ -551,7 +614,7 @@ function copyValue(value, canonicalizeNegativeZero = false) {
551
614
  if (child !== null && typeof child === "object") {
552
615
  const childKind = inspectStructuralContainer(child);
553
616
  if (!childKind.ok) return childKind;
554
- if (childKind.value !== "opaque") copied = clone(child);
617
+ if (childKind.value !== "opaque") copied = clone(child, depth + 1);
555
618
  }
556
619
  if (!copied.ok) return copied;
557
620
  const defined = define(result.value, key, {
@@ -562,22 +625,23 @@ function copyValue(value, canonicalizeNegativeZero = false) {
562
625
  }
563
626
  return result;
564
627
  }
565
- return clone(value);
628
+ return clone(value, 1);
566
629
  }
567
630
  function structurallyEqual(left, right) {
568
631
  const matched = /* @__PURE__ */ new WeakMap();
569
- function equal(currentLeft, currentRight) {
632
+ function equal(currentLeft, currentRight, depth) {
570
633
  if (sameValueZero(currentLeft, currentRight)) return true;
571
634
  if (typeof currentLeft !== "object" || currentLeft === null || typeof currentRight !== "object" || currentRight === null) return false;
572
635
  const leftKind = inspectStructuralContainer(currentLeft);
573
636
  const rightKind = inspectStructuralContainer(currentRight);
574
637
  if (!leftKind.ok || !rightKind.ok) return false;
575
638
  if (leftKind.value === "opaque" || rightKind.value === "opaque") return false;
639
+ if (depth > 256) return false;
576
640
  const previous = matched.get(currentLeft);
577
641
  if (previous !== void 0) return previous === currentRight;
578
642
  matched.set(currentLeft, currentRight);
579
643
  try {
580
- if (Object.getPrototypeOf(currentLeft) !== Object.getPrototypeOf(currentRight)) return false;
644
+ if (leftKind.value !== rightKind.value) return false;
581
645
  const leftKeys = Reflect.ownKeys(currentLeft);
582
646
  const rightKeys = Reflect.ownKeys(currentRight);
583
647
  if (leftKeys.length !== rightKeys.length) return false;
@@ -589,7 +653,7 @@ function structurallyEqual(left, right) {
589
653
  const leftData = "value" in leftDescriptor;
590
654
  if (leftData !== "value" in rightDescriptor) return false;
591
655
  if (leftData) {
592
- if (!equal(leftDescriptor.value, rightDescriptor.value)) return false;
656
+ if (!equal(leftDescriptor.value, rightDescriptor.value, depth + 1)) return false;
593
657
  } else if (leftDescriptor.get !== rightDescriptor.get || leftDescriptor.set !== rightDescriptor.set) return false;
594
658
  }
595
659
  return true;
@@ -597,7 +661,7 @@ function structurallyEqual(left, right) {
597
661
  return false;
598
662
  }
599
663
  }
600
- return equal(left, right);
664
+ return equal(left, right, 1);
601
665
  }
602
666
  function samePathSegment(left, right) {
603
667
  return String(left) === String(right);
@@ -612,24 +676,48 @@ function operationError(index, error) {
612
676
  return Object.freeze({
613
677
  code: error.code,
614
678
  operationIndex: index,
615
- message: error.message
679
+ message: error.message,
680
+ ...error.path === void 0 ? {} : { path: error.path },
681
+ ...error.reason === void 0 ? {} : { reason: error.reason }
616
682
  });
617
683
  }
684
+ /**
685
+ * `null` when `value` is inside Core's JSON domain; otherwise the failure locating the first offending part
686
+ * of the operand (the same facts the Blueprint reports for the same code).
687
+ */
688
+ function operandFailure(value) {
689
+ const first = findFirstJsonViolation(value);
690
+ if (first === null) return null;
691
+ return {
692
+ code: "json-incompatible-value",
693
+ message: PATCH_ERROR_MESSAGES["json-incompatible-value"],
694
+ path: Object.freeze([...first.path]),
695
+ ...first.code === "json-incompatible-value" ? { reason: first.reason } : {}
696
+ };
697
+ }
698
+ const PATCH_OPERATIONS = /* @__PURE__ */ new Set([
699
+ "add",
700
+ "remove",
701
+ "replace",
702
+ "move",
703
+ "copy",
704
+ "test"
705
+ ]);
618
706
  function applySourcePatch(source, patch) {
619
707
  if (!Array.isArray(patch)) return {
620
708
  ok: false,
621
709
  failure: operationError(0, {
622
- code: "invalid-path",
710
+ code: "invalid-operation",
623
711
  message: "SourcePatch must be an array."
624
712
  })
625
713
  };
626
714
  let working = source;
627
715
  for (let operationIndex = 0; operationIndex < patch.length; operationIndex++) {
628
716
  const operation = patch[operationIndex];
629
- if (typeof operation !== "object" || operation === null || !("op" in operation)) return {
717
+ if (typeof operation !== "object" || operation === null || !("op" in operation) || !PATCH_OPERATIONS.has(operation.op)) return {
630
718
  ok: false,
631
719
  failure: operationError(operationIndex, {
632
- code: "invalid-path",
720
+ code: "invalid-operation",
633
721
  message: "SourcePatch operation is malformed."
634
722
  })
635
723
  };
@@ -645,12 +733,10 @@ function applySourcePatch(source, patch) {
645
733
  case "add":
646
734
  case "replace": {
647
735
  const value = operation.value;
648
- if (!isJsonValue(value)) return {
736
+ const operandProblem = operandFailure(value);
737
+ if (operandProblem !== null) return {
649
738
  ok: false,
650
- failure: operationError(operationIndex, {
651
- code: "json-incompatible-value",
652
- message: PATCH_ERROR_MESSAGES["json-incompatible-value"]
653
- })
739
+ failure: operationError(operationIndex, operandProblem)
654
740
  };
655
741
  const copied = copyValue(value, true);
656
742
  if (!copied.ok) return {
@@ -673,12 +759,10 @@ function applySourcePatch(source, patch) {
673
759
  break;
674
760
  case "test": {
675
761
  const value = operation.value;
676
- if (!isJsonValue(value)) return {
762
+ const operandProblem = operandFailure(value);
763
+ if (operandProblem !== null) return {
677
764
  ok: false,
678
- failure: operationError(operationIndex, {
679
- code: "json-incompatible-value",
680
- message: PATCH_ERROR_MESSAGES["json-incompatible-value"]
681
- })
765
+ failure: operationError(operationIndex, operandProblem)
682
766
  };
683
767
  const actual = readAt(working, path);
684
768
  if (!actual.ok) return {
@@ -745,7 +829,7 @@ function applySourcePatch(source, patch) {
745
829
  default: return {
746
830
  ok: false,
747
831
  failure: operationError(operationIndex, {
748
- code: "invalid-path",
832
+ code: "invalid-operation",
749
833
  message: "SourcePatch operation is malformed."
750
834
  })
751
835
  };
@@ -815,14 +899,20 @@ function createWidgetDocument(options) {
815
899
  changed: false
816
900
  };
817
901
  const nextBlueprint = options.system.createBlueprint(result.value.source);
902
+ const previous = snapshot;
818
903
  blueprint = nextBlueprint;
819
904
  snapshot = Object.freeze({
820
905
  revision: snapshot.revision + 1,
821
906
  blueprint: nextBlueprint
822
907
  });
908
+ const committed = snapshot;
909
+ const commit = Object.freeze({
910
+ previous,
911
+ patch
912
+ });
823
913
  phase = "notifying";
824
914
  const audience = subscribers.slice();
825
- for (const subscriber of audience) invokeListenerIsolated(subscriber.listener, snapshot);
915
+ for (const subscriber of audience) invokeListenerIsolated(() => subscriber.listener(committed, commit), void 0);
826
916
  return {
827
917
  ok: true,
828
918
  changed: true
@@ -971,39 +1061,146 @@ function copyRecoveryValue(value) {
971
1061
  function diagnosticPath(path, key) {
972
1062
  return [...path, key];
973
1063
  }
1064
+ /** The own keys of an authored widget node; everything else cannot be carried by the separated representation. */
1065
+ const SOURCE_WIDGET_FIELDS = /* @__PURE__ */ new Set([
1066
+ "id",
1067
+ "type",
1068
+ "config",
1069
+ "slots",
1070
+ "meta"
1071
+ ]);
974
1072
  /**
975
1073
  * Projects canonical nested authored source into the explicit separated representation.
1074
+ *
1075
+ * The input is `unknown`: projection never throws on malformed input. Everything it cannot project
1076
+ * faithfully (a malformed shape, a duplicate id, a non-JSON `config`/`meta`, a cyclic or too deep tree, an
1077
+ * unrecognized field) is reported as a diagnostic located by its path in the input (`area: 'source'`), and
1078
+ * the unprojectable part is left out of the best-effort result. When `diagnostics` is empty,
1079
+ * `normalizeSeparatedWidgetSource(separated).source` is structurally equal to `source`.
1080
+ *
976
1081
  * Projection preserves nested slot order and emits flat data in deterministic depth-first order.
977
1082
  */
978
1083
  function separateWidgetSource(source) {
1084
+ const diagnostics = [];
979
1085
  const widgets = [];
980
- function projectNode(node) {
981
- const value = node;
982
- const id = value.id;
983
- const data = {
984
- id,
985
- type: value.type
986
- };
987
- if (Object.hasOwn(value, "config")) data.config = cloneJsonValue(value.config);
988
- widgets.push(Object.freeze(data));
989
- const structure = { id };
990
- if (Object.hasOwn(value, "slots")) {
991
- const slotsValue = value.slots;
992
- const slots = Object.create(null);
993
- const slotNames = ownStringKeys(slotsValue);
994
- if (slotNames === null) throw new TypeError("WidgetSource slots could not be inspected safely.");
995
- for (const slot of slotNames) {
996
- const children = slotsValue[slot];
997
- slots[slot] = Object.freeze(children.map(projectNode));
1086
+ const seenIds = /* @__PURE__ */ new Set();
1087
+ const activeNodes = /* @__PURE__ */ new Set();
1088
+ const addDiagnostic = (code, path, message, fields) => {
1089
+ diagnostics.push(freezeDiagnostic(code, {
1090
+ area: "source",
1091
+ path
1092
+ }, message, fields));
1093
+ };
1094
+ function readJsonField(node, key, path, reason) {
1095
+ const property = readDataProperty(node, key);
1096
+ if (!property.found) return { present: false };
1097
+ if (!property.accessible || !isJsonValue(property.value)) {
1098
+ addDiagnostic("invalid-separated-widget", diagnosticPath(path, key), `Widget "${key}" must be an accessible JSON value.`, { reason });
1099
+ return { present: false };
1100
+ }
1101
+ try {
1102
+ return {
1103
+ present: true,
1104
+ value: cloneJsonValue(property.value)
1105
+ };
1106
+ } catch {
1107
+ addDiagnostic("invalid-separated-widget", diagnosticPath(path, key), `Widget "${key}" must be an accessible JSON value.`, { reason });
1108
+ return { present: false };
1109
+ }
1110
+ }
1111
+ function projectNode(value, path) {
1112
+ if (!isPlainObject(value)) {
1113
+ addDiagnostic("invalid-separated-structure", path, "Widget source must be a plain object.", { reason: "invalid-node" });
1114
+ return null;
1115
+ }
1116
+ if (path.length >= 256) {
1117
+ addDiagnostic("invalid-separated-structure", path, `Widget source is nested deeper than the maximum supported depth (256).`, { reason: "max-depth-exceeded" });
1118
+ return null;
1119
+ }
1120
+ if (activeNodes.has(value)) {
1121
+ addDiagnostic("invalid-separated-structure", path, "Widget source contains a cyclic reference; the repeated node was omitted.", { reason: "invalid-node" });
1122
+ return null;
1123
+ }
1124
+ const idProperty = readDataProperty(value, "id");
1125
+ if (!idProperty.found || !idProperty.accessible || typeof idProperty.value !== "string") {
1126
+ addDiagnostic("invalid-separated-widget", diagnosticPath(path, "id"), "Widget source must have a string id.", { reason: "invalid-id" });
1127
+ return null;
1128
+ }
1129
+ const id = idProperty.value;
1130
+ activeNodes.add(value);
1131
+ try {
1132
+ const typeProperty = readDataProperty(value, "type");
1133
+ const hasType = typeProperty.found && typeProperty.accessible && typeof typeProperty.value === "string";
1134
+ if (!hasType) addDiagnostic("invalid-separated-widget", diagnosticPath(path, "type"), "Widget source must have a string type.", { reason: "invalid-type" });
1135
+ const duplicate = seenIds.has(id);
1136
+ if (duplicate) addDiagnostic("duplicate-widget-id", diagnosticPath(path, "id"), `Widget source id "${id}" occurs more than once.`, { widgetId: id });
1137
+ seenIds.add(id);
1138
+ let keys;
1139
+ try {
1140
+ keys = Reflect.ownKeys(value);
1141
+ } catch {
1142
+ keys = [];
1143
+ }
1144
+ for (const key of keys) if (!SOURCE_WIDGET_FIELDS.has(key)) addDiagnostic("invalid-separated-widget", diagnosticPath(path, key), `Widget field "${String(key)}" cannot be carried by the separated representation.`, { reason: "unexpected-field" });
1145
+ const config = readJsonField(value, "config", path, "invalid-config");
1146
+ const meta = readJsonField(value, "meta", path, "invalid-meta");
1147
+ if (hasType && !duplicate) {
1148
+ const data = {
1149
+ id,
1150
+ type: typeProperty.value
1151
+ };
1152
+ if (config.present) data.config = config.value;
1153
+ if (meta.present) data.meta = meta.value;
1154
+ widgets.push(Object.freeze(data));
1155
+ }
1156
+ const structure = { id };
1157
+ const slotsProperty = readDataProperty(value, "slots");
1158
+ const slotsPath = diagnosticPath(path, "slots");
1159
+ if (slotsProperty.found) {
1160
+ if (!slotsProperty.accessible || !isPlainObject(slotsProperty.value)) addDiagnostic("invalid-separated-structure", slotsPath, "Widget slots must be an accessible plain object.", { reason: "invalid-slots" });
1161
+ else {
1162
+ const slotNames = ownStringKeys(slotsProperty.value);
1163
+ if (slotNames === null) addDiagnostic("invalid-separated-structure", slotsPath, "Widget slots could not be inspected safely.", { reason: "invalid-slots" });
1164
+ else {
1165
+ const slots = Object.create(null);
1166
+ for (const slot of slotNames) {
1167
+ const slotPath = diagnosticPath(slotsPath, slot);
1168
+ const slotProperty = readDataProperty(slotsProperty.value, slot);
1169
+ const slotArray = readArrayInfo$1(slotProperty.value);
1170
+ if (!slotProperty.found || !slotProperty.accessible || !slotArray.isArray || !slotArray.accessible) {
1171
+ addDiagnostic("invalid-separated-structure", slotPath, "Widget slot must be an Array.", { reason: "invalid-slot-children" });
1172
+ continue;
1173
+ }
1174
+ const children = [];
1175
+ const childArray = slotProperty.value;
1176
+ for (let index = 0; index < slotArray.length; index++) {
1177
+ const childPath = diagnosticPath(slotPath, index);
1178
+ const childProperty = readDataProperty(childArray, String(index));
1179
+ if (!childProperty.found || !childProperty.accessible) {
1180
+ addDiagnostic("invalid-separated-structure", childPath, "Widget slot child could not be inspected safely.", { reason: "invalid-slot-children" });
1181
+ continue;
1182
+ }
1183
+ const child = projectNode(childProperty.value, childPath);
1184
+ if (child !== null) children.push(child);
1185
+ }
1186
+ slots[slot] = Object.freeze(children);
1187
+ }
1188
+ structure.slots = slots;
1189
+ }
1190
+ }
998
1191
  }
999
- structure.slots = slots;
1192
+ return Object.freeze(structure);
1193
+ } finally {
1194
+ activeNodes.delete(value);
1000
1195
  }
1001
- return Object.freeze(structure);
1002
1196
  }
1003
- const structure = projectNode(source);
1197
+ const structure = projectNode(source, []);
1004
1198
  return Object.freeze({
1005
- structure,
1006
- widgets: Object.freeze(widgets)
1199
+ separated: structure === null ? null : Object.freeze({
1200
+ structure,
1201
+ widgets: Object.freeze(widgets)
1202
+ }),
1203
+ diagnostics: Object.freeze(diagnostics)
1007
1204
  });
1008
1205
  }
1009
1206
  /**
@@ -1032,12 +1229,9 @@ function normalizeSeparatedWidgetSource(input) {
1032
1229
  if (envelope === null || !structureProperty.found || !structureProperty.accessible) addDiagnostic("invalid-separated-source", {
1033
1230
  area: "structure",
1034
1231
  path: []
1035
- }, " separated source must contain an accessible structure root.", { reason: "missing-structure" });
1232
+ }, "separated source must contain an accessible structure root.", { reason: "missing-structure" });
1036
1233
  const widgetsArray = readArrayInfo$1(widgetsProperty.value);
1037
- if (!widgetsProperty.found || !widgetsProperty.accessible || !widgetsArray.isArray || !widgetsArray.accessible) addDiagnostic("invalid-separated-source", {
1038
- area: "widgets",
1039
- index: 0
1040
- }, " separated source widgets must be an Array.", { reason: "invalid-widgets" });
1234
+ if (!widgetsProperty.found || !widgetsProperty.accessible || !widgetsArray.isArray || !widgetsArray.accessible) addDiagnostic("invalid-separated-source", { area: "widgets" }, "separated source widgets must be an Array.", { reason: "invalid-widgets" });
1041
1235
  if (widgetsArray.isArray && widgetsArray.accessible) {
1042
1236
  const widgets = widgetsProperty.value;
1043
1237
  for (let index = 0; index < widgetsArray.length; index++) {
@@ -1085,6 +1279,13 @@ function normalizeSeparatedWidgetSource(input) {
1085
1279
  }, "structure entry must be an object.", { reason: "invalid-node" });
1086
1280
  return value;
1087
1281
  }
1282
+ if (path.length >= 256) {
1283
+ addDiagnostic("invalid-separated-structure", {
1284
+ area: "structure",
1285
+ path
1286
+ }, `structure is nested deeper than the maximum supported depth (256); the node was omitted.`, { reason: "max-depth-exceeded" });
1287
+ return Object.create(null);
1288
+ }
1088
1289
  const objectValue = value;
1089
1290
  if (activeStructureNodes.has(objectValue)) {
1090
1291
  addDiagnostic("invalid-separated-structure", {
@@ -1133,6 +1334,13 @@ function normalizeSeparatedWidgetSource(input) {
1133
1334
  index: data.index,
1134
1335
  path: ["config"]
1135
1336
  }, "flat Widget data config could not be inspected safely.", { reason: "invalid-entry" });
1337
+ const metaProperty = readDataProperty(data.value, "meta");
1338
+ if (metaProperty.found && metaProperty.accessible) output.meta = copyRecoveryValue(metaProperty.value);
1339
+ else if (metaProperty.found && !metaProperty.accessible) addDiagnostic("invalid-separated-widget", {
1340
+ area: "widgets",
1341
+ index: data.index,
1342
+ path: ["meta"]
1343
+ }, "flat Widget data meta could not be inspected safely.", { reason: "invalid-entry" });
1136
1344
  }
1137
1345
  }
1138
1346
  const slotsProperty = readDataProperty(value, "slots");
@@ -1209,10 +1417,18 @@ function freezeArray(value) {
1209
1417
  function freezeObject(value) {
1210
1418
  if (typeof value === "object" && value !== null) Object.freeze(value);
1211
1419
  }
1420
+ /**
1421
+ * `related` arrays this module has already frozen together with their entries. Diagnostics may share one
1422
+ * `related` array (every diagnostic of one dependency cycle does), and walking a shared array once per
1423
+ * diagnostic is quadratic in the cycle length. An array frozen by someone else is not enough to skip the
1424
+ * walk: its entries may still be unfrozen.
1425
+ */
1426
+ const deeplyFrozenRelated = /* @__PURE__ */ new WeakSet();
1212
1427
  function freezeRelated(related) {
1213
- if (!Array.isArray(related)) return;
1428
+ if (!Array.isArray(related) || deeplyFrozenRelated.has(related)) return;
1214
1429
  for (const item of related) freezeObject(item);
1215
1430
  Object.freeze(related);
1431
+ deeplyFrozenRelated.add(related);
1216
1432
  }
1217
1433
  function freezeDependency(dependency) {
1218
1434
  if (typeof dependency !== "object" || dependency === null) return;
@@ -1221,7 +1437,17 @@ function freezeDependency(dependency) {
1221
1437
  freezeObject(record.operation);
1222
1438
  Object.freeze(dependency);
1223
1439
  }
1224
- /** Freeze the framework-owned diagnostic record without executing or freezing arbitrary payload objects. */
1440
+ /**
1441
+ * Freeze the framework-owned diagnostic record without executing or freezing arbitrary payload objects.
1442
+ *
1443
+ * A diagnostic's `cause` is not walked again. Only a wrapped dependency failure carries one, and its cause
1444
+ * is always a diagnostic of the dependency's own finalized snapshot (`wrapTargetFailure` in `./deps`), which
1445
+ * was deep-frozen when that snapshot was created: every State, Property and Method snapshot passes through
1446
+ * {@link freezeDiagnosticSnapshot}. Diagnostic records are only ever created and frozen here, and a record
1447
+ * is frozen after its parts, so a frozen cause is a deep-frozen cause. Re-walking it on every wrap cost
1448
+ * O(depth) per dependent and recursed once per level of a failing dependency chain (quadratic work, and a
1449
+ * stack overflow for a long chain).
1450
+ */
1225
1451
  function deepFreezeDiagnostic(diagnostic) {
1226
1452
  if (typeof diagnostic !== "object" || diagnostic === null) return diagnostic;
1227
1453
  const record = diagnostic;
@@ -1229,8 +1455,7 @@ function deepFreezeDiagnostic(diagnostic) {
1229
1455
  freezeArray(record.path);
1230
1456
  freezeRelated(record.related);
1231
1457
  freezeDependency(record.dependency);
1232
- if (record.cause !== void 0) deepFreezeDiagnostic(record.cause);
1233
- Object.freeze(diagnostic);
1458
+ Object.freeze(record);
1234
1459
  return diagnostic;
1235
1460
  }
1236
1461
  function freezeDiagnosticSnapshot(diagnostics) {
@@ -1406,9 +1631,9 @@ function buildWidgetDiagnosticSnapshot(entry) {
1406
1631
  /**
1407
1632
  * Builds the live-gated `getDiagnostics`/`subscribeDiagnostics` pair one `RuntimeWidget` exposes, composing
1408
1633
  * {@link buildWidgetDiagnosticSnapshot} the same way {@link createRuntimeAggregate} composes it for every
1409
- * widget at the Runtime level.
1634
+ * widget at the Runtime level. `widgetId` names the widget in the report of the subscription limit.
1410
1635
  */
1411
- function createRuntimeWidgetDiagnosticsAggregate(context, entry) {
1636
+ function createRuntimeWidgetDiagnosticsAggregate(context, entry, widgetId) {
1412
1637
  const snapshot = () => buildWidgetDiagnosticSnapshot(entry);
1413
1638
  return {
1414
1639
  getDiagnostics() {
@@ -1417,21 +1642,77 @@ function createRuntimeWidgetDiagnosticsAggregate(context, entry) {
1417
1642
  },
1418
1643
  subscribeDiagnostics(listener) {
1419
1644
  context.assertActive();
1420
- return createTrackedSubscription(context, snapshot, listener);
1645
+ return createTrackedSubscription(context, snapshot, listener, "the diagnostics of widget", widgetId);
1421
1646
  }
1422
1647
  };
1423
1648
  }
1649
+ /** Index of the first element of the ascending `positions` that is `>= position`. */
1650
+ function lowerBound(positions, position) {
1651
+ let low = 0;
1652
+ let high = positions.length;
1653
+ while (low < high) {
1654
+ const middle = low + high >>> 1;
1655
+ if (positions[middle] < position) low = middle + 1;
1656
+ else high = middle;
1657
+ }
1658
+ return low;
1659
+ }
1660
+ /**
1661
+ * Builds the Runtime-level aggregate. Created before the primitives (they need {@link
1662
+ * RuntimeAggregate.commitHookFor}); `registry` is only read once a snapshot is requested.
1663
+ */
1424
1664
  function createRuntimeAggregate(context, compiled, registry, runtimeLevelDiagnostics) {
1425
- let previousChildren;
1426
- let previousSnapshot;
1427
- const snapshot = () => {
1428
- const children = compiled.semanticOrder.map((nodeId) => registry.get(nodeId)).filter((entry) => entry !== void 0).map((entry) => buildWidgetDiagnosticSnapshot(entry));
1429
- if (previousSnapshot !== void 0 && previousChildren !== void 0 && previousChildren.length === children.length && previousChildren.every((child, index) => child === children[index])) return previousSnapshot;
1665
+ const { semanticOrder } = compiled;
1666
+ const positionByNodeId = new Int32Array(compiled.nodes.length).fill(-1);
1667
+ for (let position = 0; position < semanticOrder.length; position++) positionByNodeId[semanticOrder[position]] = position;
1668
+ const widgetSnapshots = Array.from({ length: semanticOrder.length }).fill(EMPTY_DIAGNOSTICS);
1669
+ const nonEmptyPositions = [];
1670
+ let dirtyPositions = [];
1671
+ const isDirty = new Uint8Array(semanticOrder.length);
1672
+ let needsFullScan = true;
1673
+ let cached = null;
1674
+ let revision = 0;
1675
+ const revisionSignal = signal(revision);
1676
+ function markDirty(position) {
1677
+ if (isDirty[position] === 1) return;
1678
+ isDirty[position] = 1;
1679
+ dirtyPositions.push(position);
1680
+ }
1681
+ /** Re-aggregates one widget; returns whether its snapshot identity changed. */
1682
+ function refreshWidget(position) {
1683
+ const entry = registry.get(semanticOrder[position]);
1684
+ const next = entry === void 0 ? EMPTY_DIAGNOSTICS : buildWidgetDiagnosticSnapshot(entry);
1685
+ const previous = widgetSnapshots[position];
1686
+ if (next === previous) return false;
1687
+ widgetSnapshots[position] = next;
1688
+ if (previous.length === 0 !== (next.length === 0)) {
1689
+ const index = lowerBound(nonEmptyPositions, position);
1690
+ if (next.length === 0) nonEmptyPositions.splice(index, 1);
1691
+ else nonEmptyPositions.splice(index, 0, position);
1692
+ }
1693
+ return true;
1694
+ }
1695
+ function refreshDirtyWidgets() {
1696
+ let changed = false;
1697
+ if (needsFullScan) {
1698
+ needsFullScan = false;
1699
+ for (let position = 0; position < semanticOrder.length; position++) changed = refreshWidget(position) || changed;
1700
+ } else for (const position of dirtyPositions) changed = refreshWidget(position) || changed;
1701
+ for (const position of dirtyPositions) isDirty[position] = 0;
1702
+ dirtyPositions = [];
1703
+ return changed;
1704
+ }
1705
+ function compose() {
1706
+ if (nonEmptyPositions.length === 0) return runtimeLevelDiagnostics.length === 0 ? EMPTY_DIAGNOSTICS : runtimeLevelDiagnostics;
1430
1707
  const result = [...runtimeLevelDiagnostics];
1431
- for (const child of children) result.push(...child);
1432
- previousChildren = children;
1433
- previousSnapshot = toDiagnosticSnapshot(result);
1434
- return previousSnapshot;
1708
+ for (const position of nonEmptyPositions) for (const diagnostic of widgetSnapshots[position]) result.push(diagnostic);
1709
+ return toDiagnosticSnapshot(result);
1710
+ }
1711
+ const snapshot = () => {
1712
+ revisionSignal();
1713
+ if (cached !== null && !needsFullScan && dirtyPositions.length === 0) return cached;
1714
+ if (readUntracked(refreshDirtyWidgets) || cached === null) cached = compose();
1715
+ return cached;
1435
1716
  };
1436
1717
  return {
1437
1718
  getDiagnostics() {
@@ -1440,7 +1721,14 @@ function createRuntimeAggregate(context, compiled, registry, runtimeLevelDiagnos
1440
1721
  },
1441
1722
  subscribeDiagnostics(listener) {
1442
1723
  context.assertActive();
1443
- return createTrackedSubscription(context, snapshot, listener);
1724
+ return createDistinctTrackedSubscription(context, snapshot, listener, readUntracked(snapshot));
1725
+ },
1726
+ commitHookFor(nodeId) {
1727
+ const position = positionByNodeId[nodeId] ?? -1;
1728
+ return () => {
1729
+ if (position !== -1) markDirty(position);
1730
+ revisionSignal(++revision);
1731
+ };
1444
1732
  }
1445
1733
  };
1446
1734
  }
@@ -1458,73 +1746,58 @@ function buildBlueprintView(blueprint) {
1458
1746
  return Object.freeze(view);
1459
1747
  }
1460
1748
  //#endregion
1461
- //#region src/runtime/context.ts
1462
- function createRuntimeContext() {
1463
- let disposed = false;
1464
- let activeCollector = null;
1465
- const owned = /* @__PURE__ */ new Set();
1466
- function assertActive() {
1467
- if (disposed) throw new WidgetSystemRuntimeDisposedError();
1468
- }
1749
+ //#region src/runtime/collector.ts
1750
+ function createOperationCollector() {
1751
+ let entries = null;
1752
+ let seenAnchorsByScope = null;
1753
+ let closed = false;
1469
1754
  return {
1470
- isDisposed: () => disposed,
1471
- assertActive,
1472
- withActiveCollector(collector, fn) {
1473
- const previous = activeCollector;
1474
- activeCollector = collector;
1475
- try {
1476
- return fn();
1477
- } finally {
1478
- activeCollector = previous;
1755
+ addDiagnostic(input) {
1756
+ if (closed) throwClosedCollector("addDiagnostic");
1757
+ (entries ??= []).push({
1758
+ kind: "relative",
1759
+ input
1760
+ });
1761
+ },
1762
+ addFinalizedDiagnostic(diagnostic, dedupe) {
1763
+ if (dedupe !== void 0) {
1764
+ seenAnchorsByScope ??= /* @__PURE__ */ new Map();
1765
+ let seenAnchors = seenAnchorsByScope.get(dedupe.scope);
1766
+ if (seenAnchors === void 0) {
1767
+ seenAnchors = /* @__PURE__ */ new Set();
1768
+ seenAnchorsByScope.set(dedupe.scope, seenAnchors);
1769
+ }
1770
+ if (seenAnchors.has(dedupe.anchor)) return;
1771
+ seenAnchors.add(dedupe.anchor);
1479
1772
  }
1773
+ (entries ??= []).push({
1774
+ kind: "final",
1775
+ diagnostic
1776
+ });
1480
1777
  },
1481
- getActiveCollector: () => activeCollector,
1482
- registerSubscription(rawDispose) {
1483
- let unsubscribed = false;
1484
- const handle = () => {
1485
- if (unsubscribed) return;
1486
- unsubscribed = true;
1487
- owned.delete(handle);
1488
- rawDispose();
1489
- };
1490
- owned.add(handle);
1491
- return handle;
1778
+ hasAnyDiagnostic() {
1779
+ if (closed) throwClosedCollector("hasAnyDiagnostic");
1780
+ return entries !== null;
1781
+ },
1782
+ finalize(toFinalDiagnostic) {
1783
+ if (entries === null) return EMPTY_DIAGNOSTICS;
1784
+ return freezeDiagnosticSnapshot(entries.map((entry) => entry.kind === "relative" ? toFinalDiagnostic(entry.input) : entry.diagnostic));
1492
1785
  },
1493
- dispose() {
1494
- if (disposed) return;
1495
- disposed = true;
1496
- for (const handle of [...owned]) handle();
1497
- owned.clear();
1786
+ close() {
1787
+ closed = true;
1498
1788
  }
1499
1789
  };
1500
1790
  }
1501
1791
  //#endregion
1502
- //#region src/runtime/sync.ts
1503
- /**
1504
- * Synchronous semantic-boundary guard.
1505
- *
1506
- * Normative source: diagnostic #10 amendment "synchronous core boundary and future async seams" /
1507
- * consolidated handoff §16: a semantic callback returning a thenable is an implementation-contract
1508
- * violation, not a Blueprint/Runtime Diagnostic and not an `ExecutionResult.failure`, so it throws.
1509
- *
1510
- * `PromiseLike` is a structural (duck-typed) contract, not a nominal one, and its `then` method may
1511
- * live on an object *or* on a callable (a function value with a `.then` property is still thenable).
1512
- * Checking `typeof value === 'object'` alone misses that callable case, so both representations are
1513
- * treated as thenable candidates before inspecting `.then`.
1514
- */
1515
- function assertSyncValue(value, description) {
1516
- if ((typeof value === "object" && value !== null || typeof value === "function") && "then" in value && typeof value.then === "function") throw new TypeError(`${description} returned a thenable. The widget-core semantic boundary is synchronous only.`);
1517
- }
1792
+ //#region src/runtime/deps.ts
1518
1793
  /**
1519
- * Callback-context lifetime guard: a callback's `addDiagnostic` / `hasAnyDiagnostic` belong to the
1520
- * synchronous call that received them. Calling one after that callback returned or threw is an
1521
- * implementation-contract violation (the operation's diagnostics are already final), so it throws.
1794
+ * The guard every materialized callable runs before anything else: disposal first (the established
1795
+ * post-dispose error surface), then the callback-context lifetime.
1522
1796
  */
1523
- function throwClosedCollector(method) {
1524
- throw new TypeError(`${method} was called after its callback returned. Diagnostics must be reported synchronously while the callback runs.`);
1797
+ function assertCallableOpen(params) {
1798
+ params.context.assertActive();
1799
+ if (callbackScope.owner !== params.owner) throwClosedCallbackMember("deps");
1525
1800
  }
1526
- //#endregion
1527
- //#region src/runtime/deps.ts
1528
1801
  function consumerDependencyDiagnostic(params, dependency, message, received, related, cause) {
1529
1802
  const base = {
1530
1803
  widgetId: params.ownerWidgetId,
@@ -1538,7 +1811,7 @@ function consumerDependencyDiagnostic(params, dependency, message, received, rel
1538
1811
  return params.consumer === "property" ? buildPropertyDependencyDiagnostic(base) : buildMethodDependencyDiagnostic(base);
1539
1812
  }
1540
1813
  function reportDependencyDiagnostic(params, diagnostic, dedupe) {
1541
- params.context.getActiveCollector()?.addFinalizedDiagnostic(diagnostic, dedupe);
1814
+ params.owner.sink?.addFinalizedDiagnostic(diagnostic, dedupe);
1542
1815
  }
1543
1816
  /**
1544
1817
  * Per-dependency-leaf unique id, assigned once when a leaf's callable is materialized and closed over
@@ -1576,20 +1849,29 @@ function dependencyDedupeDescriptor(leafId, failureAnchor) {
1576
1849
  * is captured as `unknown` and passed through the sync-boundary guard *before* being interpreted as a
1577
1850
  * boolean — a `Promise.resolve(false)` escape hatch is truthy and would otherwise make a rejection look
1578
1851
  * like an accepted refinement.
1852
+ *
1853
+ * A refinement owns no dependency or `emit` callables, so no callback is open while it runs (see
1854
+ * `callbackScope`): not even the consumer whose dependency read invoked it.
1579
1855
  */
1580
1856
  function applyRefinements(value, refinements) {
1581
- for (const refine of refinements) {
1582
- const accepted = refine(value);
1583
- assertSyncValue(accepted, "A dependency .validate() refinement");
1584
- if (!accepted) return {
1585
- ok: false,
1586
- received: value
1857
+ const previousOwner = callbackScope.owner;
1858
+ callbackScope.owner = null;
1859
+ try {
1860
+ for (const refine of refinements) {
1861
+ const accepted = refine(value);
1862
+ assertSyncValue(accepted, "A dependency .validate() refinement");
1863
+ if (!accepted) return {
1864
+ ok: false,
1865
+ received: value
1866
+ };
1867
+ }
1868
+ return {
1869
+ ok: true,
1870
+ value
1587
1871
  };
1872
+ } finally {
1873
+ callbackScope.owner = previousOwner;
1588
1874
  }
1589
- return {
1590
- ok: true,
1591
- value
1592
- };
1593
1875
  }
1594
1876
  function locationOf(operation, widgetId) {
1595
1877
  switch (operation.type) {
@@ -1616,21 +1898,30 @@ function resolveTargetWidgetId(nodes, nodeId) {
1616
1898
  if (node === void 0 || !node.resolved) throw new Error(`widget-core: internal error — dependency target node ${nodeId} is not a resolved node.`);
1617
1899
  return node.id;
1618
1900
  }
1619
- function materializeAbsentLeaf(operation) {
1901
+ function materializeAbsentLeaf(operation, params) {
1620
1902
  switch (operation.type) {
1621
- case "state-set": return (candidate) => ({
1622
- ok: true,
1623
- value: candidate
1624
- });
1625
- case "method-invoke": return (..._args) => ({
1626
- ok: true,
1627
- value: null
1628
- });
1903
+ case "state-set": return (candidate) => {
1904
+ assertCallableOpen(params);
1905
+ return {
1906
+ ok: true,
1907
+ value: candidate
1908
+ };
1909
+ };
1910
+ case "method-invoke": return (..._args) => {
1911
+ assertCallableOpen(params);
1912
+ return {
1913
+ ok: true,
1914
+ value: null
1915
+ };
1916
+ };
1629
1917
  case "state-get":
1630
- case "property-get": return () => ({
1631
- ok: true,
1632
- value: null
1633
- });
1918
+ case "property-get": return () => {
1919
+ assertCallableOpen(params);
1920
+ return {
1921
+ ok: true,
1922
+ value: null
1923
+ };
1924
+ };
1634
1925
  }
1635
1926
  }
1636
1927
  function missingRegistryEntry(targetNodeId) {
@@ -1654,6 +1945,7 @@ function materializeResolvedLeaf(leaf, params) {
1654
1945
  case "state-get": {
1655
1946
  let target;
1656
1947
  return () => {
1948
+ assertCallableOpen(params);
1657
1949
  target ??= resolveEntry(params, leaf.targetNodeId).state.get(operation.key);
1658
1950
  if (target === void 0) throw new Error(`widget-core: internal error — resolved state-get target "${operation.key}" is missing.`);
1659
1951
  const raw = target.internal.get();
@@ -1678,6 +1970,7 @@ function materializeResolvedLeaf(leaf, params) {
1678
1970
  };
1679
1971
  }
1680
1972
  case "state-set": return (candidate) => {
1973
+ assertCallableOpen(params);
1681
1974
  const target = resolveEntry(params, leaf.targetNodeId).state.get(operation.key);
1682
1975
  if (target === void 0) throw new Error(`widget-core: internal error — resolved state-set target "${operation.key}" is missing.`);
1683
1976
  const result = target.internal.attemptSet(candidate);
@@ -1692,10 +1985,12 @@ function materializeResolvedLeaf(leaf, params) {
1692
1985
  };
1693
1986
  case "property-get": {
1694
1987
  let target;
1988
+ const fromProperty = params.consumer === "property";
1695
1989
  return () => {
1990
+ assertCallableOpen(params);
1696
1991
  target ??= resolveEntry(params, leaf.targetNodeId).properties.get(operation.name);
1697
1992
  if (target === void 0) throw new Error(`widget-core: internal error — resolved property-get target "${operation.name}" is missing.`);
1698
- const targetResult = target.internal.getResult();
1993
+ const targetResult = fromProperty ? target.internal.readFromProperty() : target.internal.getResult();
1699
1994
  if (!targetResult.ok) return {
1700
1995
  ok: false,
1701
1996
  failure: { diagnostics: wrapTargetFailure(params, reference, targetResult.failure.diagnostics, related, leafId) }
@@ -1721,6 +2016,7 @@ function materializeResolvedLeaf(leaf, params) {
1721
2016
  };
1722
2017
  }
1723
2018
  case "method-invoke": return (...args) => {
2019
+ assertCallableOpen(params);
1724
2020
  const target = resolveEntry(params, leaf.targetNodeId).methods.get(operation.name);
1725
2021
  if (target === void 0) throw new Error(`widget-core: internal error — resolved method-invoke target "${operation.name}" is missing.`);
1726
2022
  const targetResult = target.public(...args);
@@ -1760,7 +2056,7 @@ function wrapTargetFailure(params, reference, targetDiagnostics, related, leafId
1760
2056
  return wrapped;
1761
2057
  }
1762
2058
  function materializeLeaf(leaf, params) {
1763
- if (leaf.status === "absent") return materializeAbsentLeaf(leaf.reference.operation);
2059
+ if (leaf.status === "absent") return materializeAbsentLeaf(leaf.reference.operation, params);
1764
2060
  if (leaf.status === "invalid") throw new Error("widget-core: internal error — an invalid dependency reached Runtime materialization; Runtime must only be created from a valid Blueprint.");
1765
2061
  return materializeResolvedLeaf(leaf, params);
1766
2062
  }
@@ -1772,49 +2068,6 @@ function materializeDependencyTree(tree, params) {
1772
2068
  return result;
1773
2069
  }
1774
2070
  //#endregion
1775
- //#region src/runtime/collector.ts
1776
- function createOperationCollector() {
1777
- let entries = null;
1778
- let seenAnchorsByScope = null;
1779
- let closed = false;
1780
- return {
1781
- addDiagnostic(input) {
1782
- if (closed) throwClosedCollector("addDiagnostic");
1783
- (entries ??= []).push({
1784
- kind: "relative",
1785
- input
1786
- });
1787
- },
1788
- addFinalizedDiagnostic(diagnostic, dedupe) {
1789
- if (dedupe !== void 0) {
1790
- seenAnchorsByScope ??= /* @__PURE__ */ new Map();
1791
- let seenAnchors = seenAnchorsByScope.get(dedupe.scope);
1792
- if (seenAnchors === void 0) {
1793
- seenAnchors = /* @__PURE__ */ new Set();
1794
- seenAnchorsByScope.set(dedupe.scope, seenAnchors);
1795
- }
1796
- if (seenAnchors.has(dedupe.anchor)) return;
1797
- seenAnchors.add(dedupe.anchor);
1798
- }
1799
- (entries ??= []).push({
1800
- kind: "final",
1801
- diagnostic
1802
- });
1803
- },
1804
- hasAnyDiagnostic() {
1805
- if (closed) throwClosedCollector("hasAnyDiagnostic");
1806
- return entries !== null;
1807
- },
1808
- finalize(toFinalDiagnostic) {
1809
- if (entries === null) return EMPTY_DIAGNOSTICS;
1810
- return freezeDiagnosticSnapshot(entries.map((entry) => entry.kind === "relative" ? toFinalDiagnostic(entry.input) : entry.diagnostic));
1811
- },
1812
- close() {
1813
- closed = true;
1814
- }
1815
- };
1816
- }
1817
- //#endregion
1818
2071
  //#region src/runtime/method.ts
1819
2072
  function createMethodPrimitive(context, params) {
1820
2073
  const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
@@ -1822,13 +2075,14 @@ function createMethodPrimitive(context, params) {
1822
2075
  function commitDiagnostics(next) {
1823
2076
  if (next === committedDiagnostics) return;
1824
2077
  committedDiagnostics = next;
1825
- writeDeferringFlush(() => diagnosticsSignal(next));
1826
- }
1827
- function invoke(...args) {
1828
- context.assertActive();
1829
- return runRuntimeOperation(() => invokeWithinOperation(...args));
2078
+ writeDeferringFlush(() => {
2079
+ diagnosticsSignal(next);
2080
+ params.onDiagnosticsCommitted();
2081
+ });
1830
2082
  }
1831
- function invokeWithinOperation(...args) {
2083
+ let deps;
2084
+ let emitFragment;
2085
+ function invokeWithinOperation(args) {
1832
2086
  startBatch();
1833
2087
  try {
1834
2088
  const argsCollector = createOperationCollector();
@@ -1839,11 +2093,14 @@ function createMethodPrimitive(context, params) {
1839
2093
  };
1840
2094
  let validArgs;
1841
2095
  let hasArgsDiagnostic;
2096
+ const previousArgsOwner = callbackScope.owner;
2097
+ callbackScope.owner = null;
1842
2098
  try {
1843
2099
  validArgs = params.definition.validateArgs(args, argsCtx);
1844
- assertSyncValue(validArgs, `Method "${params.name}"'s validateArgs`);
2100
+ assertSyncValue(validArgs, "Method", params.name, "validateArgs");
1845
2101
  hasArgsDiagnostic = argsCollector.hasAnyDiagnostic();
1846
2102
  } finally {
2103
+ callbackScope.owner = previousArgsOwner;
1847
2104
  argsCollector.close();
1848
2105
  }
1849
2106
  if (!validArgs || hasArgsDiagnostic) {
@@ -1855,25 +2112,42 @@ function createMethodPrimitive(context, params) {
1855
2112
  failure: { diagnostics }
1856
2113
  });
1857
2114
  }
2115
+ deps ??= materializeDependencyTree(params.depsTree, {
2116
+ consumer: "method",
2117
+ ownerWidgetId: params.widgetId,
2118
+ ownerName: params.name,
2119
+ registry: params.registry,
2120
+ nodes: params.nodes,
2121
+ context,
2122
+ owner: params.owner
2123
+ });
2124
+ emitFragment ??= createMethodEmitFragment(context, params.owner, params.pluginType, params.eventDefinitions, params.events, params.definition.emits);
1858
2125
  const execCollector = createOperationCollector();
1859
2126
  const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => execCollector.addFinalizedDiagnostic(diagnostic, dedupe) };
1860
2127
  const executeCtx = {
1861
2128
  args,
1862
2129
  widget: params.selfNode,
1863
2130
  blueprint: params.blueprintView,
1864
- deps: params.deps,
1865
- ...params.emitFragment,
2131
+ deps,
2132
+ ...emitFragment,
1866
2133
  ...params.buildConfigFragment(),
1867
2134
  addDiagnostic: execCollector.addDiagnostic,
1868
2135
  hasAnyDiagnostic: execCollector.hasAnyDiagnostic
1869
2136
  };
2137
+ const { owner } = params;
2138
+ const previousOwner = callbackScope.owner;
2139
+ const previousSink = owner.sink;
2140
+ callbackScope.owner = owner;
2141
+ owner.sink = sink;
1870
2142
  let value;
1871
2143
  try {
1872
- value = context.withActiveCollector(sink, () => params.definition.execute(executeCtx));
2144
+ value = params.definition.execute(executeCtx);
1873
2145
  } finally {
2146
+ callbackScope.owner = previousOwner;
2147
+ owner.sink = previousSink;
1874
2148
  execCollector.close();
1875
2149
  }
1876
- assertSyncValue(value, `Method "${params.name}"'s execute`);
2150
+ assertSyncValue(value, "Method", params.name, "execute");
1877
2151
  const diagnostics = execCollector.finalize((input) => buildMethodResultDiagnostic(params.widgetId, params.name, value, input));
1878
2152
  commitDiagnostics(toDiagnosticSnapshot(diagnostics));
1879
2153
  const result = diagnostics.length > 0 ? {
@@ -1885,10 +2159,13 @@ function createMethodPrimitive(context, params) {
1885
2159
  };
1886
2160
  return Object.freeze(result);
1887
2161
  } finally {
1888
- endBatch();
2162
+ endBatchDeferringFlush();
1889
2163
  }
1890
2164
  }
1891
- const callable = ((...args) => invoke(...args));
2165
+ const callable = ((...args) => {
2166
+ context.assertActive();
2167
+ return runRuntimeOperation(invokeWithinOperation, args);
2168
+ });
1892
2169
  Object.assign(callable, {
1893
2170
  getDiagnostics() {
1894
2171
  context.assertActive();
@@ -1896,7 +2173,7 @@ function createMethodPrimitive(context, params) {
1896
2173
  },
1897
2174
  subscribeDiagnostics(listener) {
1898
2175
  context.assertActive();
1899
- return createTrackedSubscription(context, () => diagnosticsSignal(), listener);
2176
+ return createTrackedSubscription(context, () => diagnosticsSignal(), listener, "the diagnostics of Method", params);
1900
2177
  }
1901
2178
  });
1902
2179
  return {
@@ -1958,61 +2235,466 @@ function resolveStateOverrides(compiled, overrideStateDefaults) {
1958
2235
  //#region src/runtime/property.ts
1959
2236
  /** The frozen singleton every Property inspection channel starts at and returns to before first evaluation. */
1960
2237
  const NEVER_EVALUATED_SNAPSHOT = Object.freeze({ status: "never-evaluated" });
1961
- function createPropertyPrimitive(context, params) {
1962
- const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
1963
- let committedDiagnostics = EMPTY_DIAGNOSTICS;
1964
- let inspectionSnapshot = NEVER_EVALUATED_SNAPSHOT;
1965
- let inspectionListeners = null;
1966
- let lastPublishedResult = null;
1967
- function readInspectionSnapshot() {
1968
- return inspectionSnapshot ??= Object.freeze({
1969
- status: "completed",
1970
- result: lastPublishedResult
1971
- });
1972
- }
1973
- function publishInspectionCompletion() {
1974
- inspectionSnapshot = null;
1975
- if (inspectionListeners === null || inspectionListeners.length === 0) return;
1976
- const snapshot = readInspectionSnapshot();
1977
- const listenersSnapshot = inspectionListeners.slice();
1978
- for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, snapshot);
2238
+ const computeExceptionKey = Symbol("@deviltea/widget-core:compute-exception");
2239
+ /** alien-signals@3.2.1 `ReactiveFlags.Dirty`. */
2240
+ const ALIEN_DIRTY = 16;
2241
+ /**
2242
+ * Makes the evaluation running for `node`, which is abandoned, leave the computed dirty, so that its next read
2243
+ * evaluates it again, and keep every dependency link it had, also those it has not read again (alien-signals
2244
+ * would drop them when the getter returns), so that nothing it depends on is torn down. See ALIEN-SIGNALS
2245
+ * COUPLING 2 and 3.
2246
+ */
2247
+ function keepAbandoned(node) {
2248
+ node.flags |= ALIEN_DIRTY;
2249
+ let last = node.depsTail ?? node.deps;
2250
+ if (last === void 0) return;
2251
+ while (last.nextDep !== void 0) last = last.nextDep;
2252
+ node.depsTail = last;
2253
+ }
2254
+ /**
2255
+ * How many Property evaluations may nest on one stack segment (see {@link segment}) before the evaluation
2256
+ * that would nest deeper is abandoned and completed later from a shallower stack. Internal: not API, not
2257
+ * configurable, and it may change.
2258
+ *
2259
+ * The figure that bounds it is the smallest stack Core has to run on. Older QuickJS builds default to a
2260
+ * smaller stack than quickjs-ng's 1 MiB, so it is 256 KB: there quickjs-ng 0.18.0 reads the head of a chain
2261
+ * of trivial `compute`s cold, without this limit, only up to 31 nested evaluations (63 at 512 KB, 128 at
2262
+ * 1 MiB: about 8 KB of stack per evaluation). Core's read path nests a little more stack per evaluation than
2263
+ * that measurement's: in V8 without its JIT (an interpreter like QuickJS) a chain read cold without the limit
2264
+ * reached 942 evaluations against 1 072, so about 27 at 256 KB. 12 leaves more than twice that margin, for
2265
+ * real `compute` bodies (refinements, diagnostics, helper calls), the host's own stack below the read,
2266
+ * listener and flush frames, and further segments a read can open on top of this one (a Method a `compute`
2267
+ * depends on reads its own Properties on a new segment), even if QuickJS's frames turn out an eighth larger
2268
+ * than that estimate.
2269
+ *
2270
+ * A smaller limit only adds driver rounds, hardly `compute` calls: a chain whose every link is evaluated
2271
+ * (read cold, or re-read with every link stale) costs about two `compute` calls per Property whatever the
2272
+ * limit, since each link nested beyond it runs `compute` once until it is abandoned and once to completion.
2273
+ * Measured on the differential test's graphs that the unmodified Core can read (cold reads, and State writes
2274
+ * under subscriptions) against the unmodified Core's 446 and 447 calls: 8 cost 606 and 461, 12 cost 542 and
2275
+ * 447, 15 and 16 cost 491 to 494 and 447, 32 cost 446 and 447; on a Property reading 250 or 1 000 chains of
2276
+ * 40 links, a cold read costs 2.0x (8), 1.9x (12), 1.75x (15) and 1.8x (16 and 32) the unmodified Core's
2277
+ * calls, writes the same at every limit. A 300-link chain whose every link reads its own State, or one shared
2278
+ * State, first, re-read with every link stale, costs 1.96x the unmodified Core's calls at 12; a write that
2279
+ * leaves one link stale at a time (re-evaluated without nesting) costs the same.
2280
+ */
2281
+ const EVALUATION_NESTING_LIMIT = 12;
2282
+ /**
2283
+ * Thrown by a Property's dependency read through `compute` to abandon the evaluation in progress (see
2284
+ * {@link evaluate}). Internal: plugin code must not rely on it. A `compute` that catches it has its return
2285
+ * value discarded anyway; one that keeps it and throws it in a later evaluation throws an ordinary compute
2286
+ * exception, cached and rethrown by `get()` like any other. An `Error` only so that code which logs what it
2287
+ * caught says what it is.
2288
+ */
2289
+ const ABANDONMENT = Object.freeze(/* @__PURE__ */ new Error("widget-core: internal — this Property evaluation was abandoned to be completed from a shallower stack; do not catch it."));
2290
+ /**
2291
+ * The cached outcome of an abandoned evaluation: like an engine stack overflow it is an outcome that is not
2292
+ * kept. The computed that caches it stays dirty (see `keepAbandoned`), so its next read evaluates it again.
2293
+ * One shared object, recognized by identity: an ABANDONMENT that plugin code keeps and throws later is cached
2294
+ * as an ordinary compute exception.
2295
+ */
2296
+ const ABANDONED_OUTCOME = Object.freeze({ [computeExceptionKey]: ABANDONMENT });
2297
+ /**
2298
+ * Evaluation-nesting bookkeeping of the current stack segment. A segment is the stretch of the stack between
2299
+ * one boundary read and the next: every read of a Property other than a Property's own dependency read (the
2300
+ * public `get()`, a subscription effect, a Method's dependency read, ...) is a boundary, which saves these
2301
+ * three fields, starts the segment from zero and restores them when it returns. The abandonment therefore
2302
+ * only ever travels through Property `compute` frames: it never reaches a Method's failure handling,
2303
+ * listener isolation, the isolated-exception reporting or the host.
2304
+ *
2305
+ * A mutable holder updated with plain assignments, like `callbackScope`, so the bookkeeping survives an
2306
+ * exhausted stack, and realm-wide, since segments follow the stack, not a Runtime. Its fields are read on
2307
+ * every warm read, which costs less than reading module `let` bindings from inside closures.
2308
+ */
2309
+ const segment = {
2310
+ nesting: 0,
2311
+ abandonedAt: null,
2312
+ recordedTarget: null
2313
+ };
2314
+ /** Numbers the driver loops, for their no-progress guard. */
2315
+ let drives = 0;
2316
+ /**
2317
+ * How many times one drive may find a Property it already completed abandoned again. Without a write
2318
+ * during the drive this never happens (completed outcomes stay cached and the dependency graph is acyclic);
2319
+ * code that keeps invalidating what the drive completes (a `compute` writing by closure, say) would otherwise
2320
+ * make it spin.
2321
+ */
2322
+ const MAX_DRIVE_STALLS = 256;
2323
+ /**
2324
+ * Completes a boundary read whose attempt was abandoned: a loop over an explicit stack of Properties, which
2325
+ * evaluates the recorded target first (itself possibly abandoned further down, which pushes the next
2326
+ * target) and then attempts the waiting Property again, until the read's own Property completes. Runs
2327
+ * inside the boundary's Runtime operation, so the diagnostic propagations deferred by every attempt are
2328
+ * released once, after the read's own result has been committed, as for any other outermost read.
2329
+ *
2330
+ * Every attempt runs with no active subscriber (the boundary read cleared it, see
2331
+ * `getResultWithInspectionPublish`). A completed target publishes no inspection completion here: its reader,
2332
+ * attempted again, reads it as any reader does, and publishes it then, exactly when a read without the limit
2333
+ * would have. A target whose evaluation ends in an engine stack overflow (the host called from an already
2334
+ * deep stack) ends the read with that overflow, as an overflowing read always did: the overflow is not
2335
+ * cached for good (see `getResultWithInspectionPublish`), and the waiting Properties stay abandoned, so a
2336
+ * later read evaluates them again. Disposal during the loop ends it with the post-dispose error: a `compute`
2337
+ * that catches what its dependency reads throw after the disposal could otherwise complete the read with
2338
+ * values computed from a disposed Runtime.
2339
+ */
2340
+ function driveAbandonedRead(root) {
2341
+ const drive = ++drives;
2342
+ const pending = [];
2343
+ let current = root;
2344
+ let outcome = ABANDONED_OUTCOME;
2345
+ let stalls = 0;
2346
+ for (;;) {
2347
+ if (outcome === ABANDONED_OUTCOME) {
2348
+ const target = segment.recordedTarget;
2349
+ if (target === null || target === current || target.pendingIn === drive) throw new Error("widget-core: internal error — an abandoned Property evaluation did not record a deeper evaluation to complete first.");
2350
+ if (target.completedBy === drive && ++stalls > MAX_DRIVE_STALLS) throw new Error("widget-core: internal error — completing an abandoned Property evaluation made no progress.");
2351
+ current.pendingIn = drive;
2352
+ pending.push(current);
2353
+ current = target;
2354
+ } else {
2355
+ if (current === root || computeExceptionKey in outcome && isEngineStackOverflow(outcome[computeExceptionKey])) return outcome;
2356
+ current.completedBy = drive;
2357
+ current = pending.pop();
2358
+ current.pendingIn = 0;
2359
+ }
2360
+ root.context.assertActive();
2361
+ segment.nesting = 0;
2362
+ segment.abandonedAt = null;
2363
+ segment.recordedTarget = null;
2364
+ outcome = current.attempt();
1979
2365
  }
1980
- const resultComputed = computed(() => {
1981
- const collector = createOperationCollector();
1982
- const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => collector.addFinalizedDiagnostic(diagnostic, dedupe) };
1983
- const ctx = {
1984
- widget: params.selfNode,
1985
- blueprint: params.blueprintView,
1986
- deps: params.deps,
1987
- ...params.buildConfigFragment(),
1988
- addDiagnostic: collector.addDiagnostic,
1989
- hasAnyDiagnostic: collector.hasAnyDiagnostic
1990
- };
1991
- let value;
2366
+ }
2367
+ function createPropertyPrimitive(context, params) {
2368
+ const { owner } = params;
2369
+ const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
2370
+ let committedDiagnostics = EMPTY_DIAGNOSTICS;
2371
+ let inspectionSnapshot = NEVER_EVALUATED_SNAPSHOT;
2372
+ let inspectionListeners = null;
2373
+ let lastPublishedResult = null;
2374
+ function readInspectionSnapshot() {
2375
+ return inspectionSnapshot ??= Object.freeze({
2376
+ status: "completed",
2377
+ result: lastPublishedResult
2378
+ });
2379
+ }
2380
+ /**
2381
+ * Commits the completion as the retained fact at once (`getSnapshot()` returns it from now on) and delivers
2382
+ * it to the listeners registered now once no Runtime operation is in progress (see `deliverWhenIdle`), so
2383
+ * that a listener never runs while alien-signals is evaluating, checking or flushing (issue #198). Each
2384
+ * completion is delivered with its own snapshot, in completion order. A listener unsubscribed before the
2385
+ * delivery is skipped, one subscribed after the completion does not receive it, and nothing is delivered
2386
+ * once the Runtime is disposed (its subscriptions are detached without a final call).
2387
+ */
2388
+ function publishInspectionCompletion() {
2389
+ inspectionSnapshot = null;
2390
+ if (inspectionListeners === null || inspectionListeners.length === 0) return;
2391
+ const snapshot = readInspectionSnapshot();
2392
+ const listenersSnapshot = inspectionListeners.slice();
2393
+ deliverWhenIdle(() => {
2394
+ if (context.isDisposed()) return;
2395
+ for (const entry of listenersSnapshot) if (entry.active) invokeListenerIsolated(entry.listener, snapshot);
2396
+ });
2397
+ }
2398
+ let evaluations = 0;
2399
+ let deps;
2400
+ let retries = 0;
2401
+ let retrySignal = null;
2402
+ let currentNode = null;
2403
+ let cachedAbandoned = false;
2404
+ let inProgress = 0;
2405
+ let linksCompleted = false;
2406
+ /**
2407
+ * Whether the computed whose alien-signals node is `target` has dependency links left by an evaluation that
2408
+ * completed: it is neither new nor torn down (ALIEN-SIGNALS COUPLING 4). A reader links such a computed at
2409
+ * once; any other one it reads without linking until it has completed (see `readFromProperty`).
2410
+ */
2411
+ function hasCompletedLinks(target) {
2412
+ return linksCompleted && target.deps !== void 0;
2413
+ }
2414
+ const node = {
2415
+ attempt,
2416
+ context,
2417
+ completedBy: 0,
2418
+ pendingIn: 0
2419
+ };
2420
+ /**
2421
+ * The computed's getter. Besides a completed result or a cached compute exception, an evaluation can yield
2422
+ * the abandoned outcome (see {@link ABANDONED_OUTCOME}), which is never kept; it then leaves the computed dirty
2423
+ * with every dependency link it had (see `keepAbandoned`):
2424
+ *
2425
+ * - one that would start with {@link EVALUATION_NESTING_LIMIT} evaluations already in progress on the
2426
+ * segment does not run `compute`: it records itself as where the unwinding started ({@link segment}) and
2427
+ * yields it. The dependency read in the enclosing `compute` then throws the internal
2428
+ * {@link ABANDONMENT} (see `readFromProperty`), so the enclosing evaluation finishes too;
2429
+ * - one that finishes while the segment unwinds yields it whatever its `compute` did (returned a fallback
2430
+ * after catching the abandonment, or threw anything else), and commits no diagnostics;
2431
+ * - one that would start while the segment unwinds yields it without running `compute`.
2432
+ *
2433
+ * The getter itself never throws, also not the abandonment: it returns the abandoned outcome instead. The
2434
+ * outermost evaluation of the segment ends the unwinding and hands the target to the segment's driver.
2435
+ *
2436
+ * `this` is the alien-signals node of the computed this evaluation runs for (see `currentNode`). A computed
2437
+ * replaced while it ran drops every dependency link when it finishes, so nothing evaluates it again; one
2438
+ * alien-signals would still evaluate (only reachable after an engine stack overflow; not covered by a
2439
+ * deterministic test) reads nothing and yields the abandoned outcome without running `compute`.
2440
+ * A plain function rather than a closure per computed: no extra call frame per nesting level.
2441
+ */
2442
+ function evaluate() {
2443
+ if (currentNode !== this && !claimCurrentNode(this)) return ABANDONED_OUTCOME;
2444
+ ++evaluations;
2445
+ if (!hasCompletedLinks(this)) linksCompleted = false;
2446
+ (retrySignal ??= signal(0))();
2447
+ if (segment.abandonedAt !== null) return abandonAtStart(this);
2448
+ if (segment.nesting >= EVALUATION_NESTING_LIMIT) {
2449
+ segment.abandonedAt = node;
2450
+ return abandonAtStart(this);
2451
+ }
2452
+ ++segment.nesting;
2453
+ ++inProgress;
2454
+ let abandoned = false;
1992
2455
  try {
1993
- value = context.withActiveCollector(sink, () => params.definition.compute(ctx));
2456
+ deps ??= materializeDependencyTree(params.depsTree, {
2457
+ consumer: "property",
2458
+ ownerWidgetId: params.widgetId,
2459
+ ownerName: params.name,
2460
+ registry: params.registry,
2461
+ nodes: params.nodes,
2462
+ context,
2463
+ owner
2464
+ });
2465
+ const collector = createOperationCollector();
2466
+ const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => collector.addFinalizedDiagnostic(diagnostic, dedupe) };
2467
+ const ctx = {
2468
+ widget: params.selfNode,
2469
+ blueprint: params.blueprintView,
2470
+ deps,
2471
+ ...params.buildConfigFragment(),
2472
+ addDiagnostic: collector.addDiagnostic,
2473
+ hasAnyDiagnostic: collector.hasAnyDiagnostic
2474
+ };
2475
+ const previousOwner = callbackScope.owner;
2476
+ const previousSink = owner.sink;
2477
+ callbackScope.owner = owner;
2478
+ owner.sink = sink;
2479
+ let value;
2480
+ try {
2481
+ value = params.definition.compute(ctx);
2482
+ } finally {
2483
+ callbackScope.owner = previousOwner;
2484
+ owner.sink = previousSink;
2485
+ collector.close();
2486
+ }
2487
+ if (segment.abandonedAt !== null) {
2488
+ abandoned = true;
2489
+ return ABANDONED_OUTCOME;
2490
+ }
2491
+ assertSyncValue(value, "Property", params.name, "compute");
2492
+ const diagnostics = collector.finalize((input) => buildPropertyResultDiagnostic(params.widgetId, params.name, value, input));
2493
+ const snapshot = toDiagnosticSnapshot(diagnostics);
2494
+ if (snapshot !== committedDiagnostics) {
2495
+ committedDiagnostics = snapshot;
2496
+ writeDeferringFlush(() => {
2497
+ diagnosticsSignal(snapshot);
2498
+ params.onDiagnosticsCommitted();
2499
+ });
2500
+ }
2501
+ const result = diagnostics.length > 0 ? {
2502
+ ok: false,
2503
+ failure: { diagnostics }
2504
+ } : {
2505
+ ok: true,
2506
+ value
2507
+ };
2508
+ return Object.freeze(result);
2509
+ } catch (error) {
2510
+ if (segment.abandonedAt !== null) {
2511
+ abandoned = true;
2512
+ return ABANDONED_OUTCOME;
2513
+ }
2514
+ return { [computeExceptionKey]: error };
1994
2515
  } finally {
1995
- collector.close();
2516
+ if (--segment.nesting === 0 && segment.abandonedAt !== null) {
2517
+ segment.recordedTarget = segment.abandonedAt;
2518
+ segment.abandonedAt = null;
2519
+ }
2520
+ if (this !== currentNode) this.depsTail = void 0;
2521
+ else if (abandoned) {
2522
+ const links = this;
2523
+ links.flags |= ALIEN_DIRTY;
2524
+ let last = links.depsTail ?? links.deps;
2525
+ if (last !== void 0) {
2526
+ while (last.nextDep !== void 0) last = last.nextDep;
2527
+ links.depsTail = last;
2528
+ }
2529
+ }
2530
+ if (this === currentNode) {
2531
+ --inProgress;
2532
+ cachedAbandoned = abandoned;
2533
+ if (!abandoned) linksCompleted = true;
2534
+ }
1996
2535
  }
1997
- assertSyncValue(value, `Property "${params.name}"'s compute`);
1998
- const diagnostics = collector.finalize((input) => buildPropertyResultDiagnostic(params.widgetId, params.name, value, input));
1999
- const snapshot = toDiagnosticSnapshot(diagnostics);
2000
- if (snapshot !== committedDiagnostics) {
2001
- committedDiagnostics = snapshot;
2002
- writeDeferringFlush(() => diagnosticsSignal(snapshot));
2536
+ }
2537
+ /**
2538
+ * An evaluation abandoned before running `compute` (see {@link evaluate}): leaves the computed dirty with its
2539
+ * links (see `keepAbandoned`) and yields an abandoned outcome.
2540
+ */
2541
+ function abandonAtStart(target) {
2542
+ cachedAbandoned = true;
2543
+ keepAbandoned(target);
2544
+ return ABANDONED_OUTCOME;
2545
+ }
2546
+ /**
2547
+ * Records `candidate` as the current computed's node if none is recorded yet (the first evaluation after a
2548
+ * replacement); returns whether it is now the current one.
2549
+ */
2550
+ function claimCurrentNode(candidate) {
2551
+ if (currentNode !== null) return false;
2552
+ currentNode = candidate;
2553
+ return true;
2554
+ }
2555
+ let resultComputed = computed(evaluate);
2556
+ /**
2557
+ * Replaces the result computed by a fresh one that has not evaluated yet. Used for a computed that has no
2558
+ * outcome at all (see `getResultWithInspectionPublish`), and for one whose cached outcome is abandoned while
2559
+ * an evaluation of it is still in progress further up the stack: code run during that evaluation reads this
2560
+ * Property again through the public surface (a `compute`, refinement or `validateArgs` reading by closure, or
2561
+ * an Event listener of an emit made by a Method a Property depends on; not supported, but recovered here.
2562
+ * Inspection listeners no longer run there). Making that computed evaluate again would re-enter an
2563
+ * evaluation alien-signals has not finished; the fresh one evaluates on its own instead, exactly as a
2564
+ * re-entrant read of a Property whose first evaluation is in progress always did. The replaced computed
2565
+ * finishes its evaluation in progress for its own readers and never evaluates again (see {@link evaluate}).
2566
+ */
2567
+ function replaceComputed() {
2568
+ inProgress = 0;
2569
+ cachedAbandoned = false;
2570
+ linksCompleted = false;
2571
+ currentNode = null;
2572
+ resultComputed = computed(evaluate);
2573
+ }
2574
+ /**
2575
+ * Makes the computed evaluate again although no dependency changed, for a cached engine stack overflow: it
2576
+ * depends on how deep the stack was when the evaluation ran, not on the compute's inputs. The write marks
2577
+ * this Property (and through it its dependents) stale; its propagation is held until the enclosing Runtime
2578
+ * operation leaves, like any write made while an evaluation may run. A computed no write reaches any more
2579
+ * is replaced instead (see {@link isUnreachable}; only reachable after an engine stack overflow; not covered
2580
+ * by a deterministic test).
2581
+ */
2582
+ function reevaluate() {
2583
+ if (isUnreachable()) replaceComputed();
2584
+ else {
2585
+ const signal = retrySignal;
2586
+ writeDeferringFlush(() => signal(++retries));
2003
2587
  }
2004
- const result = diagnostics.length > 0 ? {
2005
- ok: false,
2006
- failure: { diagnostics }
2007
- } : {
2008
- ok: true,
2009
- value
2010
- };
2011
- return Object.freeze(result);
2012
- });
2588
+ return resultComputed();
2589
+ }
2590
+ /**
2591
+ * Whether the current computed has no dependency link, so that the write that makes a computed evaluate
2592
+ * again would not reach it: an engine stack overflow at the very start of an evaluation (when alien-signals
2593
+ * calls the getter) leaves the computed marked clean, with its previous outcome and with every link purged
2594
+ * (`deps`, its alien-signals@3.2.1 dependency list, is empty), so nothing would ever evaluate it again.
2595
+ */
2596
+ function isUnreachable() {
2597
+ return currentNode?.deps === void 0;
2598
+ }
2599
+ /** See {@link EvaluationNode.attempt}. Runs inside the boundary's Runtime operation with no active subscriber. */
2600
+ function attempt() {
2601
+ const evaluationsBefore = evaluations;
2602
+ const result = resultComputed();
2603
+ if (result === void 0) {
2604
+ replaceComputed();
2605
+ return resultComputed();
2606
+ }
2607
+ if (computeExceptionKey in result && evaluations === evaluationsBefore) {
2608
+ if (result === ABANDONED_OUTCOME) return readAbandonedAgain();
2609
+ if (isEngineStackOverflow(result[computeExceptionKey])) return reevaluate();
2610
+ }
2611
+ return result;
2612
+ }
2013
2613
  /**
2014
- * Reads the computed result through the exact same call every existing consumer already makes, then
2015
- * publishes the inspection fact only *after* that call has returned.
2614
+ * A boundary read's own Property, read with no active subscriber: attempted, completed by the driver loop
2615
+ * when abandoned, and only then read once more by `subscriber` (when there is one) to link it, so that a
2616
+ * running subscriber is linked to the outcome the read completed, never to an abandoned one. The link read
2617
+ * evaluates nothing unless foreign code changed this Property after it completed; that evaluation is driven
2618
+ * like the first.
2619
+ *
2620
+ * A completed result not published yet is published here, still inside the boundary's Runtime operation, so
2621
+ * that its delivery is queued behind the completions this read produced and runs when the outermost
2622
+ * operation leaves (see `publishInspectionCompletion`), never from the caller's frame after it returned.
2623
+ */
2624
+ function readAtBoundary(subscriber) {
2625
+ const evaluationsBefore = evaluations;
2626
+ let outcome = resultComputed();
2627
+ if (outcome === void 0 || computeExceptionKey in outcome) outcome = completeBoundaryOutcome(outcome, evaluationsBefore);
2628
+ if (subscriber !== void 0) outcome = linkSubscriber(subscriber, outcome);
2629
+ if (outcome !== lastPublishedResult && !(computeExceptionKey in outcome)) {
2630
+ lastPublishedResult = outcome;
2631
+ publishInspectionCompletion();
2632
+ }
2633
+ return outcome;
2634
+ }
2635
+ /**
2636
+ * Whether the current computed, whose cached outcome is abandoned, would not evaluate again when read,
2637
+ * although an abandoned computed is left dirty (see `keepAbandoned`): its evaluation is still in progress
2638
+ * further up the stack (code run by that evaluation reads this Property again, see {@link replaceComputed};
2639
+ * alien-signals returns the cached outcome of a
2640
+ * computed it is evaluating), or, only reachable after an engine stack overflow and not covered by a
2641
+ * deterministic test, an overflow inside alien-signals' own bookkeeping left it marked clean.
2642
+ */
2643
+ function abandonedWithoutReevaluation() {
2644
+ return inProgress > 0 || ((currentNode?.flags ?? 0) & ALIEN_DIRTY) === 0;
2645
+ }
2646
+ /**
2647
+ * A read found a cached abandonment it did not produce, and evaluated nothing (see
2648
+ * {@link abandonedWithoutReevaluation}): the computed is replaced (see {@link replaceComputed}), and the
2649
+ * fresh one read.
2650
+ */
2651
+ function readAbandonedAgain() {
2652
+ replaceComputed();
2653
+ return resultComputed();
2654
+ }
2655
+ /**
2656
+ * The outcome of a boundary read's first read that is not a completed result: no outcome at all, an engine
2657
+ * stack overflow this read did not produce, or an abandonment, each completed as {@link attempt} and the
2658
+ * driver loop do; a compute exception is returned as it is.
2659
+ */
2660
+ function completeBoundaryOutcome(outcome, evaluationsBefore) {
2661
+ if (outcome === void 0) {
2662
+ replaceComputed();
2663
+ outcome = resultComputed();
2664
+ } else if (evaluations === evaluationsBefore) {
2665
+ if (outcome === ABANDONED_OUTCOME) outcome = readAbandonedAgain();
2666
+ else if (isEngineStackOverflow(outcome[computeExceptionKey])) outcome = reevaluate();
2667
+ }
2668
+ return outcome === ABANDONED_OUTCOME ? driveAbandonedRead(node) : outcome;
2669
+ }
2670
+ /**
2671
+ * Links `subscriber` to the computed whose `outcome` the boundary read just produced, by reading it once more
2672
+ * with `subscriber` active (see {@link readAtBoundary}).
2673
+ */
2674
+ function linkSubscriber(subscriber, outcome) {
2675
+ for (let rounds = 0;; rounds++) {
2676
+ setActiveSub(subscriber);
2677
+ let linked;
2678
+ try {
2679
+ linked = resultComputed();
2680
+ } finally {
2681
+ setActiveSub(void 0);
2682
+ }
2683
+ if (linked === outcome) return outcome;
2684
+ if (linked !== void 0 && linked !== ABANDONED_OUTCOME) return linked;
2685
+ if (outcome !== ABANDONED_OUTCOME && computeExceptionKey in outcome) return outcome;
2686
+ if (rounds >= MAX_DRIVE_STALLS) throw new Error("widget-core: internal error — a Property read made no progress.");
2687
+ outcome = attempt();
2688
+ if (outcome === ABANDONED_OUTCOME) outcome = driveAbandonedRead(node);
2689
+ }
2690
+ }
2691
+ /**
2692
+ * The boundary read (see {@link segment}): starts a new segment, reads the computed result through the
2693
+ * exact same call every existing consumer already makes — completing it in the driver loop when its
2694
+ * evaluation was abandoned (see {@link driveAbandonedRead}) — then publishes the inspection fact only after
2695
+ * that call has returned (in {@link readAtBoundary}, still inside this read's Runtime operation). Publishing
2696
+ * commits the fact; its listeners are notified once the outermost Runtime operation has left (see
2697
+ * `publishInspectionCompletion`): for a top-level read, when this read's own operation leaves.
2016
2698
  *
2017
2699
  * In pinned alien-signals@3.2.1 a computed's cache assignment happens as `c.value = c.getter(...)`:
2018
2700
  * the getter runs to completion *before* the assignment to `c.value` takes effect. Publishing from
@@ -2026,9 +2708,90 @@ function createPropertyPrimitive(context, params) {
2026
2708
  * made. Every actual recompute produces a brand-new frozen `ExecutionResult` literal (see above), so
2027
2709
  * comparing by reference — never by value — still notifies twice for two equal-value completions while
2028
2710
  * never re-publishing a merely-re-read, already-cached result.
2711
+ *
2712
+ * A cached {@link ComputeException} is rethrown here, after the computed read has linked the caller
2713
+ * (an enclosing evaluation or a subscription effect) to this Property, and is never published.
2714
+ *
2715
+ * Three outcomes are not kept, because they depend on the stack depth of an earlier read rather than on
2716
+ * the Property's inputs, and a later read from a shallower stack must be able to succeed:
2717
+ *
2718
+ * - a cached engine stack overflow that this read did not just produce is evaluated again (see
2719
+ * {@link reevaluate}); one this read produced is thrown, since retrying at the same depth would only
2720
+ * overflow again. The engine's own overflow stays the last line of defence, for example when the host
2721
+ * itself calls from an already deep stack;
2722
+ * - a cached abandonment (see {@link evaluate}) that this read did not just produce is evaluated again
2723
+ * too (its computed is dirty): an evaluation alien-signals started on its own during a flush (an effect's
2724
+ * dirty check) can be abandoned with no driver above it. One this read produced is completed by the
2725
+ * driver loop;
2726
+ * - a computed with no outcome at all: the stack ran out inside alien-signals' own bookkeeping or at the
2727
+ * very start of the first evaluation, so the exception escaped the computed and left it marked clean
2728
+ * without a value. Nothing ever linked to a computed whose evaluation never completed (alien-signals
2729
+ * links the reader only after a read returns), so it is replaced by a fresh one.
2029
2730
  */
2030
2731
  function getResultWithInspectionPublish() {
2031
- const result = runRuntimeOperation(resultComputed);
2732
+ const subscriber = getActiveSub();
2733
+ if (subscriber !== void 0) setActiveSub(void 0);
2734
+ const savedNesting = segment.nesting;
2735
+ const savedAbandonedAt = segment.abandonedAt;
2736
+ const outerTarget = savedNesting === 0 ? null : segment.recordedTarget;
2737
+ segment.nesting = 0;
2738
+ segment.abandonedAt = null;
2739
+ segment.recordedTarget = null;
2740
+ let result;
2741
+ try {
2742
+ result = runRuntimeOperation(readAtBoundary, subscriber);
2743
+ } finally {
2744
+ segment.nesting = savedNesting;
2745
+ segment.abandonedAt = savedAbandonedAt;
2746
+ segment.recordedTarget = outerTarget;
2747
+ if (subscriber !== void 0) setActiveSub(subscriber);
2748
+ }
2749
+ if (computeExceptionKey in result) throw result[computeExceptionKey];
2750
+ return result;
2751
+ }
2752
+ /**
2753
+ * {@link getResultWithInspectionPublish} for a Property's own dependency callable, nested in the reading
2754
+ * Property's evaluation on the same segment. An abandoned outcome is thrown as the internal
2755
+ * {@link ABANDONMENT}, through the reader's `compute`, to the reader's evaluation. A cached abandonment is
2756
+ * evaluated again by the read itself (the computed is dirty, see `keepAbandoned`), unless it would not be
2757
+ * (see {@link abandonedWithoutReevaluation}): it is then replaced first (see {@link replaceComputed}), rather
2758
+ * than abandoning the reader and being replaced only when the driver loop attempts it.
2759
+ */
2760
+ function readFromProperty() {
2761
+ if (cachedAbandoned && abandonedWithoutReevaluation()) replaceComputed();
2762
+ let result;
2763
+ if (hasCompletedLinks(currentNode)) {
2764
+ const evaluationsBefore = evaluations;
2765
+ const read = resultComputed;
2766
+ result = runRuntimeOperation(read);
2767
+ if (result !== void 0) {
2768
+ if (computeExceptionKey in result && evaluations === evaluationsBefore && isEngineStackOverflow(result[computeExceptionKey])) result = runRuntimeOperation(reevaluate);
2769
+ else if (resultComputed !== read) result = runRuntimeOperation(resultComputed);
2770
+ return finishReadFromProperty(result);
2771
+ }
2772
+ replaceComputed();
2773
+ }
2774
+ const reader = setActiveSub(void 0);
2775
+ try {
2776
+ const evaluationsBefore = evaluations;
2777
+ result = runRuntimeOperation(resultComputed);
2778
+ if (result === void 0) {
2779
+ replaceComputed();
2780
+ result = runRuntimeOperation(resultComputed);
2781
+ } else if (computeExceptionKey in result && evaluations === evaluationsBefore && isEngineStackOverflow(result[computeExceptionKey])) result = runRuntimeOperation(reevaluate);
2782
+ } finally {
2783
+ setActiveSub(reader);
2784
+ }
2785
+ if (result !== ABANDONED_OUTCOME) result = runRuntimeOperation(resultComputed);
2786
+ return finishReadFromProperty(result);
2787
+ }
2788
+ /** Throws an abandonment or a compute exception, or publishes a completed result unless already published. */
2789
+ function finishReadFromProperty(result) {
2790
+ if (result === ABANDONED_OUTCOME) {
2791
+ segment.abandonedAt ??= segment.recordedTarget ?? node;
2792
+ throw ABANDONMENT;
2793
+ }
2794
+ if (computeExceptionKey in result) throw result[computeExceptionKey];
2032
2795
  if (result !== lastPublishedResult) {
2033
2796
  lastPublishedResult = result;
2034
2797
  publishInspectionCompletion();
@@ -2037,14 +2800,19 @@ function createPropertyPrimitive(context, params) {
2037
2800
  }
2038
2801
  const internal = {
2039
2802
  getResult: getResultWithInspectionPublish,
2803
+ readFromProperty,
2040
2804
  getDiagnostics: () => diagnosticsSignal(),
2041
2805
  inspection: {
2042
2806
  getSnapshot: readInspectionSnapshot,
2043
2807
  subscribe: (listener) => {
2044
- const entry = { listener };
2808
+ const entry = {
2809
+ listener,
2810
+ active: true
2811
+ };
2045
2812
  if (inspectionListeners === null) inspectionListeners = [];
2046
2813
  inspectionListeners.push(entry);
2047
2814
  return () => {
2815
+ entry.active = false;
2048
2816
  if (inspectionListeners === null) return;
2049
2817
  const index = inspectionListeners.indexOf(entry);
2050
2818
  if (index !== -1) inspectionListeners.splice(index, 1);
@@ -2052,6 +2820,14 @@ function createPropertyPrimitive(context, params) {
2052
2820
  }
2053
2821
  }
2054
2822
  };
2823
+ /**
2824
+ * Creates a subscription to this Property's result. Called inside a Runtime operation (see `subscribe`): the
2825
+ * subscription's first read can evaluate Properties, and the inspection completions it produces must reach
2826
+ * their listeners after the subscription exists (see `createTrackedSubscription`).
2827
+ */
2828
+ function subscribeWithinOperation(listener) {
2829
+ return createTrackedSubscription(context, internal.getResult, listener, "Property", params);
2830
+ }
2055
2831
  return {
2056
2832
  internal,
2057
2833
  public: {
@@ -2061,7 +2837,7 @@ function createPropertyPrimitive(context, params) {
2061
2837
  },
2062
2838
  subscribe(listener) {
2063
2839
  context.assertActive();
2064
- return createTrackedSubscription(context, internal.getResult, listener);
2840
+ return runRuntimeOperation(subscribeWithinOperation, listener);
2065
2841
  },
2066
2842
  getDiagnostics() {
2067
2843
  context.assertActive();
@@ -2069,28 +2845,98 @@ function createPropertyPrimitive(context, params) {
2069
2845
  },
2070
2846
  subscribeDiagnostics(listener) {
2071
2847
  context.assertActive();
2072
- return createTrackedSubscription(context, internal.getDiagnostics, listener);
2848
+ return createTrackedSubscription(context, internal.getDiagnostics, listener, "the diagnostics of Property", params);
2073
2849
  }
2074
2850
  }
2075
2851
  };
2076
2852
  }
2077
2853
  //#endregion
2078
2854
  //#region src/runtime/state.ts
2855
+ function createStateLedger(stateCount) {
2856
+ return {
2857
+ dirty: new Uint32Array(stateCount + 31 >>> 5),
2858
+ states: []
2859
+ };
2860
+ }
2861
+ /**
2862
+ * Restores the captured initialization outcome of the State members whose ordinals lie in
2863
+ * `[first, end)` and that may have changed since — the shared implementation of
2864
+ * `WidgetSystemRuntime.resetState()` (every State) and `RuntimeWidget.resetState()` (one widget's
2865
+ * contiguous range). `validate` does not run again, all writes form one batch so dependents recompute and
2866
+ * subscribers are notified once, and Property/Method diagnostic snapshots are left untouched.
2867
+ *
2868
+ * Called from outside every Runtime operation, alien batch and reactive scope, the scan only visits the
2869
+ * set bits: restoring a State nothing wrote is then a no-op nobody can observe. In ascending ordinal order,
2870
+ * i.e. the order a scan over every State would restore them in, it re-reads the bitset word at every step,
2871
+ * so a State a listener writes during the reset is restored exactly when the scan has not passed it yet.
2872
+ * From anywhere else (a listener, a `compute`, a Method, an open batch) every State of the range is
2873
+ * restored, in order, because a restore also reads the State's signal: that read is tracked by an active
2874
+ * computed or effect and commits a value an enclosing write has not committed yet. Such a restore leaves
2875
+ * the marks set, since its own write may still be uncommitted when it returns; the next top-level reset
2876
+ * visits those States again, exactly as a full scan would, and clears the marks.
2877
+ *
2878
+ * Like `set()`, a restore made while another Runtime operation is in progress does not flush on its own: the
2879
+ * outermost operation notifies the subscribers (see `runRuntimeWrite`).
2880
+ */
2881
+ function restoreInitialState(context, ledger, first, end) {
2882
+ context.assertActive();
2883
+ const writtenOnly = isRuntimeIdle();
2884
+ runRuntimeWrite(() => {
2885
+ startBatch();
2886
+ try {
2887
+ const { dirty, states } = ledger;
2888
+ let ordinal = first;
2889
+ if (!writtenOnly) {
2890
+ for (; ordinal < end; ordinal++) states[ordinal].restoreInitial(false);
2891
+ return;
2892
+ }
2893
+ while (ordinal < end) {
2894
+ const remaining = dirty[ordinal >>> 5] >>> (ordinal & 31);
2895
+ if (remaining === 0) {
2896
+ ordinal = (ordinal | 31) + 1;
2897
+ continue;
2898
+ }
2899
+ ordinal += 31 - Math.clz32(remaining & -remaining);
2900
+ if (ordinal >= end) break;
2901
+ states[ordinal].restoreInitial(true);
2902
+ ++ordinal;
2903
+ }
2904
+ } finally {
2905
+ endBatch();
2906
+ }
2907
+ });
2908
+ }
2909
+ /**
2910
+ * Clears the dirty bit of `ordinal`, now that its initial outcome was captured or is being restored. Writing NaN
2911
+ * over NaN counts as a change, so restoring a NaN initial value notifies even an unwritten State: that bit
2912
+ * stays set.
2913
+ */
2914
+ function markCleanUnlessNaN(dirty, ordinal, initialValue) {
2915
+ if (Number.isNaN(initialValue)) dirty[ordinal >>> 5] |= 1 << (ordinal & 31);
2916
+ else dirty[ordinal >>> 5] &= ~(1 << (ordinal & 31));
2917
+ }
2079
2918
  function createStatePrimitive(context, params) {
2919
+ const { dirty, states } = params.ledger;
2920
+ const ordinal = states.length;
2080
2921
  const valueSignal = signal(null);
2081
2922
  const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
2082
- let inspectionSnapshot = Object.freeze({ value: null });
2923
+ let inspectionValue = null;
2924
+ let inspectionSnapshot = null;
2083
2925
  let inspectionListeners = null;
2926
+ function readInspectionSnapshot() {
2927
+ return inspectionSnapshot ??= Object.freeze({ value: inspectionValue });
2928
+ }
2084
2929
  function publishInspectionSnapshot(value) {
2085
- inspectionSnapshot = Object.freeze({ value });
2930
+ inspectionValue = value;
2931
+ inspectionSnapshot = null;
2086
2932
  if (inspectionListeners === null) return;
2087
2933
  const listenersSnapshot = inspectionListeners.slice();
2088
- for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, inspectionSnapshot);
2934
+ for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, readInspectionSnapshot());
2089
2935
  }
2090
2936
  /**
2091
2937
  * The value write below is what makes the whole dependent Property graph recompute, and those
2092
2938
  * recomputes commit their own diagnostic snapshots from inside their evaluators. Wrapping the pipeline in
2093
- * `runRuntimeOperation` is only what tells `writeDeferringFlush` when those evaluators are all back
2939
+ * `runRuntimeWrite` is only what tells `writeDeferringFlush` when those evaluators are all back
2094
2940
  * out of the graph, so the propagations they deferred are released here: still inside the very `set()`
2095
2941
  * call that caused them, before its `ExecutionResult` reaches the caller.
2096
2942
  */
@@ -2098,12 +2944,28 @@ function createStatePrimitive(context, params) {
2098
2944
  function commitDiagnostics(next) {
2099
2945
  if (next === committedDiagnostics) return;
2100
2946
  committedDiagnostics = next;
2101
- writeDeferringFlush(() => diagnosticsSignal(next));
2947
+ writeDeferringFlush(() => {
2948
+ diagnosticsSignal(next);
2949
+ params.onDiagnosticsCommitted();
2950
+ });
2102
2951
  }
2103
2952
  function attemptSet(candidate) {
2104
- return runRuntimeOperation(() => attemptSetWithinOperation(candidate));
2953
+ return runRuntimeWrite(attemptSetWithinOperation, candidate);
2105
2954
  }
2955
+ /**
2956
+ * A rejected attempt changes the diagnostic snapshot, so every attempt marks the State: on entry, and once
2957
+ * more after its last mutation, because that mutation flushes listeners that may reset the State
2958
+ * (clearing its mark) before the attempt has finished writing.
2959
+ */
2106
2960
  function attemptSetWithinOperation(candidate) {
2961
+ dirty[ordinal >>> 5] |= 1 << (ordinal & 31);
2962
+ try {
2963
+ return attemptSetUnmarked(candidate);
2964
+ } finally {
2965
+ dirty[ordinal >>> 5] |= 1 << (ordinal & 31);
2966
+ }
2967
+ }
2968
+ function attemptSetUnmarked(candidate) {
2107
2969
  const collector = createOperationCollector();
2108
2970
  const ctx = {
2109
2971
  ...params.buildConfigFragment(),
@@ -2112,11 +2974,14 @@ function createStatePrimitive(context, params) {
2112
2974
  };
2113
2975
  let isValid;
2114
2976
  let hasDiagnostic;
2977
+ const previousOwner = callbackScope.owner;
2978
+ callbackScope.owner = null;
2115
2979
  try {
2116
2980
  isValid = params.definition.validate(candidate, ctx);
2117
- assertSyncValue(isValid, `State "${params.key}"'s validate`);
2981
+ assertSyncValue(isValid, "State", params.key, "validate");
2118
2982
  hasDiagnostic = collector.hasAnyDiagnostic();
2119
2983
  } finally {
2984
+ callbackScope.owner = previousOwner;
2120
2985
  collector.close();
2121
2986
  }
2122
2987
  if (!isValid || hasDiagnostic) {
@@ -2128,7 +2993,7 @@ function createStatePrimitive(context, params) {
2128
2993
  failure: { diagnostics }
2129
2994
  };
2130
2995
  }
2131
- assertSyncValue(candidate, `State "${params.key}"'s value`);
2996
+ assertSyncValue(candidate, "State", params.key, "value");
2132
2997
  const previous = valueSignal();
2133
2998
  valueSignal(candidate);
2134
2999
  commitDiagnostics(EMPTY_DIAGNOSTICS);
@@ -2144,8 +3009,10 @@ function createStatePrimitive(context, params) {
2144
3009
  captureInitial() {
2145
3010
  initialValue = valueSignal();
2146
3011
  initialDiagnostics = committedDiagnostics;
3012
+ markCleanUnlessNaN(dirty, ordinal, initialValue);
2147
3013
  },
2148
- restoreInitial() {
3014
+ restoreInitial(clearMark) {
3015
+ if (clearMark) markCleanUnlessNaN(dirty, ordinal, initialValue);
2149
3016
  const previous = valueSignal();
2150
3017
  valueSignal(initialValue);
2151
3018
  commitDiagnostics(initialDiagnostics);
@@ -2155,7 +3022,7 @@ function createStatePrimitive(context, params) {
2155
3022
  getDiagnostics: () => diagnosticsSignal(),
2156
3023
  attemptSet,
2157
3024
  inspection: {
2158
- getSnapshot: () => inspectionSnapshot,
3025
+ getSnapshot: readInspectionSnapshot,
2159
3026
  subscribe: (listener) => {
2160
3027
  const entry = { listener };
2161
3028
  if (inspectionListeners === null) inspectionListeners = [];
@@ -2168,77 +3035,100 @@ function createStatePrimitive(context, params) {
2168
3035
  }
2169
3036
  }
2170
3037
  };
3038
+ const publicState = {
3039
+ get() {
3040
+ context.assertActive();
3041
+ return internal.get();
3042
+ },
3043
+ set(value) {
3044
+ context.assertActive();
3045
+ return internal.attemptSet(value);
3046
+ },
3047
+ subscribe(listener) {
3048
+ context.assertActive();
3049
+ return createTrackedSubscription(context, internal.get, listener, "State", params);
3050
+ },
3051
+ getDiagnostics() {
3052
+ context.assertActive();
3053
+ return internal.getDiagnostics();
3054
+ },
3055
+ subscribeDiagnostics(listener) {
3056
+ context.assertActive();
3057
+ return createTrackedSubscription(context, internal.getDiagnostics, listener, "the diagnostics of State", params);
3058
+ }
3059
+ };
3060
+ states.push(internal);
2171
3061
  return {
2172
3062
  internal,
2173
- public: {
2174
- get() {
2175
- context.assertActive();
2176
- return internal.get();
2177
- },
2178
- set(value) {
2179
- context.assertActive();
2180
- return internal.attemptSet(value);
2181
- },
2182
- subscribe(listener) {
2183
- context.assertActive();
2184
- return createTrackedSubscription(context, internal.get, listener);
2185
- },
2186
- getDiagnostics() {
2187
- context.assertActive();
2188
- return internal.getDiagnostics();
2189
- },
2190
- subscribeDiagnostics(listener) {
2191
- context.assertActive();
2192
- return createTrackedSubscription(context, internal.getDiagnostics, listener);
2193
- }
2194
- }
3063
+ public: publicState
2195
3064
  };
2196
3065
  }
2197
3066
  //#endregion
2198
3067
  //#region src/runtime/widget.ts
2199
- function buildRuntimeWidget(context, node, entry) {
2200
- const diagnosticsAggregate = createRuntimeWidgetDiagnosticsAggregate(context, entry);
3068
+ /** `stateStart` and `stateEnd` bound the ledger ordinals of this widget's State members. */
3069
+ function buildRuntimeWidget(context, node, entry, ledger, stateStart, stateEnd) {
3070
+ const diagnosticsAggregate = createRuntimeWidgetDiagnosticsAggregate(context, entry, node.id);
2201
3071
  const widget = {
2202
3072
  id: node.id,
2203
3073
  type: node.type,
2204
- blueprint: node.publicNode,
3074
+ blueprintNode: node.publicNode,
2205
3075
  getDiagnostics: diagnosticsAggregate.getDiagnostics,
2206
3076
  subscribeDiagnostics: diagnosticsAggregate.subscribeDiagnostics
2207
3077
  };
2208
3078
  const definition = readWidgetPluginDefinition(node.plugin);
2209
3079
  if (definition.state !== null) {
2210
3080
  const stateSurface = Object.create(null);
2211
- for (const [key, primitive] of entry.state) stateSurface[key] = primitive.public;
3081
+ for (const key of entry.state.keys()) stateSurface[key] = entry.state.get(key).public;
2212
3082
  widget.state = Object.freeze(stateSurface);
3083
+ widget.resetState = () => restoreInitialState(context, ledger, stateStart, stateEnd);
2213
3084
  }
2214
3085
  if (definition.properties !== null) {
2215
3086
  const propertiesSurface = Object.create(null);
2216
- for (const [name, primitive] of entry.properties) propertiesSurface[name] = primitive.public;
3087
+ for (const name of entry.properties.keys()) propertiesSurface[name] = entry.properties.get(name).public;
2217
3088
  widget.properties = Object.freeze(propertiesSurface);
2218
3089
  }
2219
3090
  if (definition.methods !== null) {
2220
3091
  const methodsSurface = Object.create(null);
2221
- for (const [name, primitive] of entry.methods) methodsSurface[name] = primitive.public;
3092
+ for (const name of entry.methods.keys()) methodsSurface[name] = entry.methods.get(name).public;
2222
3093
  widget.methods = Object.freeze(methodsSurface);
2223
3094
  }
2224
3095
  if (definition.events !== null) {
2225
3096
  const eventsSurface = Object.create(null);
2226
- for (const [name, primitive] of entry.events) eventsSurface[name] = primitive.public;
3097
+ for (const name of entry.events.keys()) eventsSurface[name] = entry.events.get(name).public;
2227
3098
  widget.events = Object.freeze(eventsSurface);
2228
3099
  }
2229
3100
  return Object.freeze(widget);
2230
3101
  }
2231
3102
  //#endregion
2232
3103
  //#region src/runtime/index.ts
3104
+ /**
3105
+ * Adds `key` to `record` as an own, enumerable, writable, configurable data property. Plain assignment
3106
+ * does exactly that unless the key exists on `Object.prototype` (`__proto__` is a setter there), so only
3107
+ * those keys pay for `defineProperty`.
3108
+ */
3109
+ function defineOwnValue(record, key, value) {
3110
+ if (key in Object.prototype) Object.defineProperty(record, key, {
3111
+ value,
3112
+ enumerable: true,
3113
+ writable: true,
3114
+ configurable: true
3115
+ });
3116
+ else record[key] = value;
3117
+ }
2233
3118
  function createWidgetSystemRuntime(blueprint, options) {
2234
3119
  const compiled = readCompiledBlueprint(blueprint);
2235
3120
  const context = createRuntimeContext();
2236
3121
  const blueprintView = buildBlueprintView(blueprint);
2237
3122
  const registry = /* @__PURE__ */ new Map();
2238
- function buildConfigFragmentFor(node) {
2239
- const fragment = readWidgetPluginDefinition(node.plugin).config === null ? Object.freeze({}) : Object.freeze({ config: node.config });
2240
- return () => fragment;
2241
- }
3123
+ const overrideResolution = resolveStateOverrides(compiled, options?.overrideStateDefaults);
3124
+ const aggregate = createRuntimeAggregate(context, compiled, registry, overrideResolution.runtimeLevelDiagnostics);
3125
+ const commitHooks = [];
3126
+ const configFragments = [];
3127
+ let stateCount = 0;
3128
+ for (const node of compiled.nodes) if (node !== void 0 && node.resolved) stateCount += node.state.size;
3129
+ const stateLedger = createStateLedger(stateCount);
3130
+ const stateStart = [];
3131
+ const stateEnd = [];
2242
3132
  for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2243
3133
  const node = compiled.nodes[nodeId];
2244
3134
  if (node === void 0 || !node.resolved) continue;
@@ -2251,26 +3141,35 @@ function createWidgetSystemRuntime(blueprint, options) {
2251
3141
  registry.set(nodeId, entry);
2252
3142
  const definition = readWidgetPluginDefinition(node.plugin);
2253
3143
  if (definition.events !== null) for (const name of definition.events.keys()) entry.events.set(name, createEventPrimitive(context));
2254
- const buildConfigFragment = buildConfigFragmentFor(node);
2255
- for (const [key, member] of node.state) {
3144
+ const fragment = definition.config === null ? Object.freeze({}) : Object.freeze({ config: node.config });
3145
+ const buildConfigFragment = () => fragment;
3146
+ configFragments[nodeId] = buildConfigFragment;
3147
+ const onDiagnosticsCommitted = aggregate.commitHookFor(nodeId);
3148
+ commitHooks[nodeId] = onDiagnosticsCommitted;
3149
+ stateStart[nodeId] = stateLedger.states.length;
3150
+ for (const member of node.state.values()) {
3151
+ const { key } = member;
2256
3152
  const primitive = createStatePrimitive(context, {
2257
3153
  widgetId: node.id,
2258
3154
  key,
2259
3155
  definition: member.definition,
2260
- buildConfigFragment
3156
+ buildConfigFragment,
3157
+ onDiagnosticsCommitted,
3158
+ ledger: stateLedger
2261
3159
  });
2262
3160
  entry.state.set(key, primitive);
2263
3161
  }
3162
+ stateEnd[nodeId] = stateLedger.states.length;
2264
3163
  }
2265
- const overrideResolution = resolveStateOverrides(compiled, options?.overrideStateDefaults);
2266
3164
  for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2267
3165
  const node = compiled.nodes[nodeId];
2268
3166
  if (node === void 0 || !node.resolved) continue;
2269
3167
  const entry = registry.get(nodeId);
2270
3168
  if (entry === void 0) continue;
2271
- const buildConfigFragment = buildConfigFragmentFor(node);
3169
+ const buildConfigFragment = configFragments[nodeId];
2272
3170
  const overrides = overrideResolution.candidatesByNodeId.get(nodeId);
2273
- for (const [key, member] of node.state) {
3171
+ for (const member of node.state.values()) {
3172
+ const { key } = member;
2274
3173
  const primitive = entry.state.get(key);
2275
3174
  if (primitive === void 0) continue;
2276
3175
  let hasCandidate = false;
@@ -2279,8 +3178,14 @@ function createWidgetSystemRuntime(blueprint, options) {
2279
3178
  candidate = overrides.get(key);
2280
3179
  hasCandidate = true;
2281
3180
  } else if (member.definition.default) {
2282
- candidate = member.definition.default({ ...buildConfigFragment() });
2283
- assertSyncValue(candidate, `State "${key}"'s default`);
3181
+ const previousOwner = callbackScope.owner;
3182
+ callbackScope.owner = null;
3183
+ try {
3184
+ candidate = member.definition.default({ ...buildConfigFragment() });
3185
+ } finally {
3186
+ callbackScope.owner = previousOwner;
3187
+ }
3188
+ assertSyncValue(candidate, "State", key, "default");
2284
3189
  hasCandidate = true;
2285
3190
  }
2286
3191
  if (hasCandidate) primitive.internal.attemptSet(candidate);
@@ -2292,17 +3197,12 @@ function createWidgetSystemRuntime(blueprint, options) {
2292
3197
  if (node === void 0 || !node.resolved) continue;
2293
3198
  const entry = registry.get(nodeId);
2294
3199
  if (entry === void 0) continue;
2295
- const buildConfigFragment = buildConfigFragmentFor(node);
2296
- const emitFragment = readWidgetPluginDefinition(node.plugin).events === null ? Object.freeze({}) : Object.freeze({ emit: buildEventEmitter(entry.events) });
2297
- for (const [name, member] of node.properties) {
2298
- const deps = materializeDependencyTree(member.deps, {
2299
- consumer: "property",
2300
- ownerWidgetId: node.id,
2301
- ownerName: name,
2302
- registry,
2303
- nodes: compiled.nodes,
2304
- context
2305
- });
3200
+ const buildConfigFragment = configFragments[nodeId];
3201
+ const onDiagnosticsCommitted = commitHooks[nodeId];
3202
+ const definition = readWidgetPluginDefinition(node.plugin);
3203
+ for (const member of node.properties.values()) {
3204
+ const { name } = member;
3205
+ const owner = createCallbackOwner(null, null);
2306
3206
  const primitive = createPropertyPrimitive(context, {
2307
3207
  widgetId: node.id,
2308
3208
  name,
@@ -2310,19 +3210,17 @@ function createWidgetSystemRuntime(blueprint, options) {
2310
3210
  buildConfigFragment,
2311
3211
  selfNode: node.publicNode,
2312
3212
  blueprintView,
2313
- deps
2314
- });
2315
- entry.properties.set(name, primitive);
2316
- }
2317
- for (const [name, member] of node.methods) {
2318
- const deps = materializeDependencyTree(member.deps, {
2319
- consumer: "method",
2320
- ownerWidgetId: node.id,
2321
- ownerName: name,
3213
+ depsTree: member.deps,
2322
3214
  registry,
2323
3215
  nodes: compiled.nodes,
2324
- context
3216
+ owner,
3217
+ onDiagnosticsCommitted
2325
3218
  });
3219
+ entry.properties.set(name, primitive);
3220
+ }
3221
+ for (const member of node.methods.values()) {
3222
+ const { name } = member;
3223
+ const owner = createCallbackOwner(node.id, name, member.definition.emits);
2326
3224
  const primitive = createMethodPrimitive(context, {
2327
3225
  widgetId: node.id,
2328
3226
  name,
@@ -2330,22 +3228,28 @@ function createWidgetSystemRuntime(blueprint, options) {
2330
3228
  buildConfigFragment,
2331
3229
  selfNode: node.publicNode,
2332
3230
  blueprintView,
2333
- deps,
2334
- emitFragment
3231
+ depsTree: member.deps,
3232
+ registry,
3233
+ nodes: compiled.nodes,
3234
+ pluginType: node.type,
3235
+ eventDefinitions: definition.events,
3236
+ events: definition.events === null ? null : entry.events,
3237
+ owner,
3238
+ onDiagnosticsCommitted
2335
3239
  });
2336
3240
  entry.methods.set(name, primitive);
2337
3241
  }
2338
3242
  }
2339
3243
  const runtimeWidgetsByNodeId = /* @__PURE__ */ new Map();
2340
3244
  const nodeIdByRuntimeWidget = /* @__PURE__ */ new Map();
2341
- for (const [nodeId, entry] of registry) {
3245
+ for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2342
3246
  const node = compiled.nodes[nodeId];
2343
- if (node === void 0 || !node.resolved) continue;
2344
- const runtimeWidget = buildRuntimeWidget(context, node, entry);
3247
+ const entry = registry.get(nodeId);
3248
+ if (node === void 0 || !node.resolved || entry === void 0) continue;
3249
+ const runtimeWidget = buildRuntimeWidget(context, node, entry, stateLedger, stateStart[nodeId], stateEnd[nodeId]);
2345
3250
  runtimeWidgetsByNodeId.set(nodeId, runtimeWidget);
2346
3251
  nodeIdByRuntimeWidget.set(runtimeWidget, nodeId);
2347
3252
  }
2348
- const aggregate = createRuntimeAggregate(context, compiled, registry, overrideResolution.runtimeLevelDiagnostics);
2349
3253
  function getWidget(id) {
2350
3254
  context.assertActive();
2351
3255
  const publicNode = blueprint.getWidget(id);
@@ -2355,15 +3259,23 @@ function createWidgetSystemRuntime(blueprint, options) {
2355
3259
  return runtimeWidgetsByNodeId.get(nodeId) ?? null;
2356
3260
  }
2357
3261
  function resetState() {
3262
+ restoreInitialState(context, stateLedger, 0, stateLedger.states.length);
3263
+ }
3264
+ function snapshotState() {
2358
3265
  context.assertActive();
2359
- runRuntimeOperation(() => {
2360
- startBatch();
2361
- try {
2362
- for (const entry of registry.values()) for (const primitive of entry.state.values()) primitive.internal.restoreInitial();
2363
- } finally {
2364
- endBatch();
3266
+ const snapshot = {};
3267
+ for (const nodeId of compiled.semanticOrder) {
3268
+ const node = compiled.nodes[nodeId];
3269
+ const entry = registry.get(nodeId);
3270
+ if (node === void 0 || !node.resolved || entry === void 0) continue;
3271
+ let values = null;
3272
+ for (const key of entry.state.keys()) {
3273
+ const value = entry.state.get(key).internal.get();
3274
+ if (value !== null) defineOwnValue(values ??= {}, key, value);
2365
3275
  }
2366
- });
3276
+ if (values !== null) defineOwnValue(snapshot, node.id, values);
3277
+ }
3278
+ return snapshot;
2367
3279
  }
2368
3280
  const runtime = {
2369
3281
  blueprint,
@@ -2372,8 +3284,10 @@ function createWidgetSystemRuntime(blueprint, options) {
2372
3284
  },
2373
3285
  getWidget,
2374
3286
  resetState,
3287
+ snapshotState,
2375
3288
  getDiagnostics: aggregate.getDiagnostics,
2376
3289
  subscribeDiagnostics: aggregate.subscribeDiagnostics,
3290
+ subscribeDisposal: context.subscribeDisposal,
2377
3291
  dispose: () => context.dispose()
2378
3292
  };
2379
3293
  runtime[runtimeInternals] = {
@@ -2403,12 +3317,13 @@ function readDepExpression(expression) {
2403
3317
  return expression[depExpressionBrand];
2404
3318
  }
2405
3319
  function createDepExpression(internals, readable) {
2406
- const expression = { [depExpressionBrand]: internals };
2407
- if (readable) expression.validate = (refinement) => createDepExpression({
2408
- reference: internals.reference,
2409
- refinements: [...internals.refinements, refinement]
2410
- }, true);
2411
- return expression;
3320
+ return readable ? {
3321
+ validate: (refinement) => createDepExpression({
3322
+ reference: internals.reference,
3323
+ refinements: [...internals.refinements, refinement]
3324
+ }, true),
3325
+ [depExpressionBrand]: internals
3326
+ } : { [depExpressionBrand]: internals };
2412
3327
  }
2413
3328
  function createTargetOperations(target) {
2414
3329
  const leaf = (operation, readable) => createDepExpression({
@@ -2501,6 +3416,20 @@ function widgetLocation(node) {
2501
3416
  node
2502
3417
  };
2503
3418
  }
3419
+ const sharedWidgetLocations = /* @__PURE__ */ new WeakMap();
3420
+ /**
3421
+ * The one frozen `widget` location of a node, for `related` lists that mention many nodes (duplicate ids and
3422
+ * ambiguous dependency targets build K lists of K-1 locations each). Every list that names the node holds this
3423
+ * same object, so a location is built and frozen once per node instead of once per list entry.
3424
+ */
3425
+ function sharedWidgetLocation(node) {
3426
+ let location = sharedWidgetLocations.get(node);
3427
+ if (location === void 0) {
3428
+ location = Object.freeze(widgetLocation(node));
3429
+ sharedWidgetLocations.set(node, location);
3430
+ }
3431
+ return location;
3432
+ }
2504
3433
  function slotLocation(node, slot) {
2505
3434
  return {
2506
3435
  type: "slot",
@@ -2580,28 +3509,42 @@ function dedupeBy(items, key) {
2580
3509
  }
2581
3510
  //#endregion
2582
3511
  //#region src/blueprint/deps.ts
3512
+ function createMemberIds(nodes, semanticOrder) {
3513
+ const offsetsByDefinition = /* @__PURE__ */ new Map();
3514
+ const baseByNodeId = [];
3515
+ const offsetsByNodeId = [];
3516
+ let count = 0;
3517
+ for (const nodeId of semanticOrder) {
3518
+ const node = nodes[nodeId];
3519
+ if (!node.resolved || node.plugin === null) continue;
3520
+ const definition = readWidgetPluginDefinition(node.plugin);
3521
+ let offsets = offsetsByDefinition.get(definition);
3522
+ if (offsets === void 0) {
3523
+ const properties = /* @__PURE__ */ new Map();
3524
+ const methods = /* @__PURE__ */ new Map();
3525
+ let size = 0;
3526
+ for (const name of definition.properties?.keys() ?? []) properties.set(name, size++);
3527
+ for (const name of definition.methods?.keys() ?? []) methods.set(name, size++);
3528
+ offsets = {
3529
+ properties,
3530
+ methods,
3531
+ size
3532
+ };
3533
+ offsetsByDefinition.set(definition, offsets);
3534
+ }
3535
+ baseByNodeId[nodeId] = count;
3536
+ offsetsByNodeId[nodeId] = offsets;
3537
+ count += offsets.size;
3538
+ }
3539
+ return {
3540
+ baseByNodeId,
3541
+ offsetsByNodeId,
3542
+ count
3543
+ };
3544
+ }
2583
3545
  function configFragment$1(node) {
2584
3546
  return node.plugin !== null && readWidgetPluginDefinition(node.plugin).config !== null ? { config: node.config } : {};
2585
3547
  }
2586
- /**
2587
- * `WidgetMemberKey = string` is an arbitrary finite string domain (member names may themselves
2588
- * contain `:` / `->`), so naive template-literal concatenation of the six identity components is not
2589
- * injective: e.g. a from-name of `"a->method:0:b"` paired with a to-name of `"c"` serializes to the
2590
- * same string as a from-name of `"a"` paired with a to-name of `"b->property:0:c"`. `JSON.stringify`
2591
- * of the component tuple is injective over strings/numbers (it round-trips exactly through
2592
- * `JSON.parse`), so two distinct tuples can never collide regardless of what characters member names
2593
- * contain.
2594
- */
2595
- function edgeKey(fromKind, fromNodeId, fromName, toKind, toNodeId, toName) {
2596
- return JSON.stringify([
2597
- fromKind,
2598
- fromNodeId,
2599
- fromName,
2600
- toKind,
2601
- toNodeId,
2602
- toName
2603
- ]);
2604
- }
2605
3548
  function walkDeps(value, resolveLeaf) {
2606
3549
  if (isDepExpression(value)) return resolveLeaf(value);
2607
3550
  if (Array.isArray(value)) return Object.freeze(value.map((item) => walkDeps(item, resolveLeaf)));
@@ -2619,25 +3562,34 @@ function describeMissingTarget(target) {
2619
3562
  default: return "Dependency target does not exist.";
2620
3563
  }
2621
3564
  }
2622
- function resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member, leaf, finalDiagnostics, edges, directWriteSeeds) {
2623
- const { reference, refinements } = readDepExpression(leaf);
2624
- const { target, operation } = reference;
2625
- const owner = nodes[ownerNodeId];
2626
- const ownerPublicNode = owner.publicNode;
2627
- if (operation.type === "state-set" && member.type === "property") throw new TypeError("registerDeps() produced a state-set dependency owned by a Property; Property members must remain side-effect free. This is a plugin implementation bug.");
2628
- const absent = () => ({
2629
- [compiledDependencyBrand]: true,
3565
+ function absentDependency(reference, refinements) {
3566
+ return {
2630
3567
  status: "absent",
2631
3568
  reference,
2632
- refinements
2633
- });
2634
- const invalid = (targetNodeId) => ({
2635
- [compiledDependencyBrand]: true,
3569
+ refinements,
3570
+ [compiledDependencyBrand]: true
3571
+ };
3572
+ }
3573
+ function invalidDependency(reference, refinements, targetNodeId) {
3574
+ return targetNodeId === void 0 ? {
2636
3575
  status: "invalid",
2637
3576
  reference,
2638
3577
  refinements,
2639
- ...targetNodeId === void 0 ? {} : { targetNodeId }
2640
- });
3578
+ [compiledDependencyBrand]: true
3579
+ } : {
3580
+ status: "invalid",
3581
+ reference,
3582
+ refinements,
3583
+ targetNodeId,
3584
+ [compiledDependencyBrand]: true
3585
+ };
3586
+ }
3587
+ function resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, ownerMemberId, member, leaf, finalDiagnostics, memberIds, edges, edgeKeys, directWriteSeeds) {
3588
+ const { reference, refinements } = readDepExpression(leaf);
3589
+ const { target, operation } = reference;
3590
+ const owner = nodes[ownerNodeId];
3591
+ const ownerPublicNode = owner.publicNode;
3592
+ if (operation.type === "state-set" && member.type === "property") throw new TypeError("registerDeps() produced a state-set dependency owned by a Property; Property members must remain side-effect free. This is a plugin implementation bug.");
2641
3593
  let candidateIds;
2642
3594
  switch (target.type) {
2643
3595
  case "self":
@@ -2652,84 +3604,99 @@ function resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member,
2652
3604
  case "widget": candidateIds = nodeIdsByWidgetId.get(target.widgetId) ?? [];
2653
3605
  }
2654
3606
  if (candidateIds.length === 0) {
2655
- if ((target.type === "parent" || target.type === "widget") && target.optional) return absent();
3607
+ if ((target.type === "parent" || target.type === "widget") && target.optional) return absentDependency(reference, refinements);
2656
3608
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-target", describeMissingTarget(target), reference));
2657
- return invalid();
3609
+ return invalidDependency(reference, refinements);
2658
3610
  }
2659
3611
  if (candidateIds.length > 1) {
2660
- const related = candidateIds.map((id) => widgetLocation(nodes[id].publicNode));
3612
+ const related = candidateIds.map((id) => sharedWidgetLocation(nodes[id].publicNode));
2661
3613
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "ambiguous-dependency-target", "Dependency target is ambiguous: multiple widgets share that id.", reference, related));
2662
- return invalid();
3614
+ return invalidDependency(reference, refinements);
2663
3615
  }
2664
3616
  const targetNodeId = candidateIds[0];
2665
3617
  const targetWorking = nodes[targetNodeId];
2666
3618
  if (!targetWorking.resolved) {
2667
3619
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "unresolved-dependency-target", "Dependency target could not be resolved to a widget.", reference, [widgetLocation(targetWorking.publicNode)]));
2668
- return invalid(targetNodeId);
3620
+ return invalidDependency(reference, refinements, targetNodeId);
2669
3621
  }
2670
3622
  const targetDefinition = readWidgetPluginDefinition(targetWorking.plugin);
2671
3623
  const targetPublicNode = targetWorking.publicNode;
2672
3624
  if (operation.type === "state-get" || operation.type === "state-set") {
2673
3625
  if (targetDefinition.state === null) {
2674
3626
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-capability", "Dependency target has no state capability.", reference, [widgetLocation(targetPublicNode)]));
2675
- return invalid(targetNodeId);
3627
+ return invalidDependency(reference, refinements, targetNodeId);
2676
3628
  }
2677
3629
  if (!targetDefinition.state.has(operation.key)) {
2678
3630
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-member", `Dependency target has no state member "${operation.key}".`, reference, [widgetLocation(targetPublicNode)]));
2679
- return invalid(targetNodeId);
3631
+ return invalidDependency(reference, refinements, targetNodeId);
2680
3632
  }
2681
3633
  if (operation.type === "state-set" && member.type === "method") directWriteSeeds.add(`${ownerNodeId}:${member.name}`);
2682
3634
  } else if (operation.type === "property-get") {
2683
3635
  if (targetDefinition.properties === null) {
2684
3636
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-capability", "Dependency target has no properties capability.", reference, [widgetLocation(targetPublicNode)]));
2685
- return invalid(targetNodeId);
3637
+ return invalidDependency(reference, refinements, targetNodeId);
2686
3638
  }
2687
3639
  if (!targetDefinition.properties.has(operation.name)) {
2688
3640
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-member", `Dependency target has no property "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
2689
- return invalid(targetNodeId);
2690
- }
2691
- const key = edgeKey(member.type, ownerNodeId, member.name, "property", targetNodeId, operation.name);
2692
- if (!edges.has(key)) edges.set(key, {
2693
- fromKind: member.type,
2694
- fromNodeId: ownerNodeId,
2695
- fromName: member.name,
2696
- toKind: "property",
2697
- toNodeId: targetNodeId,
2698
- toName: operation.name,
2699
- reference
2700
- });
3641
+ return invalidDependency(reference, refinements, targetNodeId);
3642
+ }
3643
+ const toId = memberIds.baseByNodeId[targetNodeId] + memberIds.offsetsByNodeId[targetNodeId].properties.get(operation.name);
3644
+ const key = ownerMemberId * memberIds.count + toId;
3645
+ if (!edgeKeys.has(key)) {
3646
+ edgeKeys.add(key);
3647
+ edges.push({
3648
+ fromKind: member.type,
3649
+ fromNodeId: ownerNodeId,
3650
+ fromName: member.name,
3651
+ fromId: ownerMemberId,
3652
+ toKind: "property",
3653
+ toNodeId: targetNodeId,
3654
+ toName: operation.name,
3655
+ toId,
3656
+ reference
3657
+ });
3658
+ }
2701
3659
  } else {
2702
3660
  if (targetDefinition.methods === null) {
2703
3661
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-capability", "Dependency target has no methods capability.", reference, [widgetLocation(targetPublicNode)]));
2704
- return invalid(targetNodeId);
3662
+ return invalidDependency(reference, refinements, targetNodeId);
2705
3663
  }
2706
3664
  if (!targetDefinition.methods.has(operation.name)) {
2707
3665
  finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-member", `Dependency target has no method "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
2708
- return invalid(targetNodeId);
2709
- }
2710
- const key = edgeKey(member.type, ownerNodeId, member.name, "method", targetNodeId, operation.name);
2711
- if (!edges.has(key)) edges.set(key, {
2712
- fromKind: member.type,
2713
- fromNodeId: ownerNodeId,
2714
- fromName: member.name,
2715
- toKind: "method",
2716
- toNodeId: targetNodeId,
2717
- toName: operation.name,
2718
- reference
2719
- });
3666
+ return invalidDependency(reference, refinements, targetNodeId);
3667
+ }
3668
+ const toId = memberIds.baseByNodeId[targetNodeId] + memberIds.offsetsByNodeId[targetNodeId].methods.get(operation.name);
3669
+ const key = ownerMemberId * memberIds.count + toId;
3670
+ if (!edgeKeys.has(key)) {
3671
+ edgeKeys.add(key);
3672
+ edges.push({
3673
+ fromKind: member.type,
3674
+ fromNodeId: ownerNodeId,
3675
+ fromName: member.name,
3676
+ fromId: ownerMemberId,
3677
+ toKind: "method",
3678
+ toNodeId: targetNodeId,
3679
+ toName: operation.name,
3680
+ toId,
3681
+ reference
3682
+ });
3683
+ }
2720
3684
  }
2721
3685
  return {
2722
- [compiledDependencyBrand]: true,
2723
3686
  status: "resolved",
2724
3687
  targetNodeId,
2725
3688
  reference,
2726
- refinements
3689
+ refinements,
3690
+ [compiledDependencyBrand]: true
2727
3691
  };
2728
3692
  }
2729
3693
  function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics) {
2730
- const edges = /* @__PURE__ */ new Map();
3694
+ const memberIds = createMemberIds(nodes, semanticOrder);
3695
+ const edges = [];
3696
+ const edgeKeys = /* @__PURE__ */ new Set();
2731
3697
  const directWriteSeeds = /* @__PURE__ */ new Set();
2732
- const resolve = (ownerNodeId, member, leaf) => resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member, leaf, finalDiagnostics, edges, directWriteSeeds);
3698
+ const directEmitSeeds = /* @__PURE__ */ new Set();
3699
+ const resolve = (ownerNodeId, ownerMemberId, member, leaf) => resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, ownerMemberId, member, leaf, finalDiagnostics, memberIds, edges, edgeKeys, directWriteSeeds);
2733
3700
  for (const nodeId of semanticOrder) {
2734
3701
  const node = nodes[nodeId];
2735
3702
  if (!node.resolved || node.plugin === null) continue;
@@ -2737,13 +3704,12 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2737
3704
  if (definition.properties === null) continue;
2738
3705
  const configFrag = configFragment$1(node);
2739
3706
  for (const [name, propertyDefinition] of definition.properties) {
2740
- const dep = createDependencyBuilder();
2741
3707
  let rawDeps = {};
2742
3708
  if (propertyDefinition.registerDeps !== void 0) {
2743
3709
  rawDeps = propertyDefinition.registerDeps({
2744
3710
  widget: compileFacade.facadeForNodeId(nodeId),
2745
3711
  blueprint: compileFacade.view,
2746
- dep,
3712
+ dep: createDependencyBuilder(),
2747
3713
  ...configFrag
2748
3714
  });
2749
3715
  assertSyncValue(rawDeps, `Property "${name}"'s registerDeps`);
@@ -2752,7 +3718,8 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2752
3718
  type: "property",
2753
3719
  name
2754
3720
  };
2755
- const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, member, leaf));
3721
+ const ownerMemberId = memberIds.baseByNodeId[nodeId] + memberIds.offsetsByNodeId[nodeId].properties.get(name);
3722
+ const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, ownerMemberId, member, leaf));
2756
3723
  node.properties.set(name, {
2757
3724
  name,
2758
3725
  definition: propertyDefinition,
@@ -2767,13 +3734,12 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2767
3734
  if (definition.methods === null) continue;
2768
3735
  const configFrag = configFragment$1(node);
2769
3736
  for (const [name, methodDefinition] of definition.methods) {
2770
- const dep = createDependencyBuilder();
2771
3737
  let rawDeps = {};
2772
3738
  if (methodDefinition.registerDeps !== void 0) {
2773
3739
  rawDeps = methodDefinition.registerDeps({
2774
3740
  widget: compileFacade.facadeForNodeId(nodeId),
2775
3741
  blueprint: compileFacade.view,
2776
- dep,
3742
+ dep: createDependencyBuilder(),
2777
3743
  ...configFrag
2778
3744
  });
2779
3745
  assertSyncValue(rawDeps, `Method "${name}"'s registerDeps`);
@@ -2782,115 +3748,197 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2782
3748
  type: "method",
2783
3749
  name
2784
3750
  };
2785
- const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, member, leaf));
3751
+ const ownerMemberId = memberIds.baseByNodeId[nodeId] + memberIds.offsetsByNodeId[nodeId].methods.get(name);
3752
+ const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, ownerMemberId, member, leaf));
2786
3753
  node.methods.set(name, {
2787
3754
  name,
2788
3755
  definition: methodDefinition,
2789
3756
  deps,
2790
- transitivelyWrites: false
3757
+ transitivelyWrites: false,
3758
+ transitivelyEmits: false
2791
3759
  });
3760
+ if (methodDefinition.emits !== void 0 && methodDefinition.emits.length > 0) directEmitSeeds.add(`${nodeId}:${name}`);
2792
3761
  }
2793
3762
  }
2794
3763
  return {
2795
3764
  edges,
2796
- directWriteSeeds
3765
+ memberCount: memberIds.count,
3766
+ directWriteSeeds,
3767
+ directEmitSeeds
2797
3768
  };
2798
3769
  }
2799
3770
  //#endregion
2800
3771
  //#region src/blueprint/graph.ts
2801
- function memberKey(kind, nodeId, name) {
2802
- return `${kind}:${nodeId}:${name}`;
2803
- }
2804
3772
  function memberLocation(nodes, ref) {
2805
3773
  const node = nodes[ref.nodeId].publicNode;
2806
3774
  return ref.kind === "property" ? propertyLocation(node, ref.name) : methodLocation(node, ref.name);
2807
3775
  }
3776
+ /** The effects a Method can have, as flags: it writes State, it emits an Event. */
3777
+ const WRITES = 1;
3778
+ const EMITS = 2;
2808
3779
  /**
2809
- * Runs the write-effect fixed point over Method->Method edges, marking transitively-writeful methods
2810
- * on each node's already-built `CompiledMethodMember` map.
3780
+ * Propagates effects over Method->Method edges: a Method writes when it directly writes State or invokes a
3781
+ * Method that writes, and emits when it declares an Event in `emits` or invokes a Method that emits.
3782
+ * One work list over a callee->callers adjacency built once; a caller is revisited only when it gains a
3783
+ * flag, so each Method is queued at most twice. Marks `transitivelyWrites` / `transitivelyEmits` on each
3784
+ * node's already-built `CompiledMethodMember` map and returns the flags by `${nodeId}:${name}` key.
2811
3785
  */
2812
- function computeWritefulMethods(nodes, edges, directWriteSeeds) {
2813
- const writeful = new Set(directWriteSeeds);
2814
- const methodEdges = [...edges.values()].filter((edge) => edge.fromKind === "method" && edge.toKind === "method");
2815
- let changed = true;
2816
- while (changed) {
2817
- changed = false;
2818
- for (const edge of methodEdges) {
2819
- const fromKey = `${edge.fromNodeId}:${edge.fromName}`;
2820
- const toKey = `${edge.toNodeId}:${edge.toName}`;
2821
- if (writeful.has(toKey) && !writeful.has(fromKey)) {
2822
- writeful.add(fromKey);
2823
- changed = true;
3786
+ function computeMethodEffects(nodes, edges, directWriteSeeds, directEmitSeeds) {
3787
+ const effects = /* @__PURE__ */ new Map();
3788
+ for (const key of directWriteSeeds) effects.set(key, WRITES);
3789
+ for (const key of directEmitSeeds) effects.set(key, (effects.get(key) ?? 0) | EMITS);
3790
+ const callersOf = /* @__PURE__ */ new Map();
3791
+ for (const edge of edges) {
3792
+ if (edge.fromKind !== "method" || edge.toKind !== "method") continue;
3793
+ const toKey = `${edge.toNodeId}:${edge.toName}`;
3794
+ const fromKey = `${edge.fromNodeId}:${edge.fromName}`;
3795
+ const callers = callersOf.get(toKey);
3796
+ if (callers === void 0) callersOf.set(toKey, [fromKey]);
3797
+ else callers.push(fromKey);
3798
+ }
3799
+ const workList = [...effects.keys()];
3800
+ for (let index = 0; index < workList.length; index++) {
3801
+ const callee = workList[index];
3802
+ const calleeEffects = effects.get(callee);
3803
+ for (const caller of callersOf.get(callee) ?? []) {
3804
+ const callerEffects = effects.get(caller) ?? 0;
3805
+ if ((callerEffects | calleeEffects) !== callerEffects) {
3806
+ effects.set(caller, callerEffects | calleeEffects);
3807
+ workList.push(caller);
2824
3808
  }
2825
3809
  }
2826
3810
  }
2827
3811
  for (const node of nodes) {
2828
3812
  if (!node.resolved) continue;
2829
- for (const [name, member] of node.methods) if (writeful.has(`${node.nodeId}:${name}`) && !member.transitivelyWrites) node.methods.set(name, {
2830
- ...member,
2831
- transitivelyWrites: true
2832
- });
3813
+ for (const [name, member] of node.methods) {
3814
+ const flags = effects.get(`${node.nodeId}:${name}`) ?? 0;
3815
+ if (flags !== 0) node.methods.set(name, {
3816
+ ...member,
3817
+ transitivelyWrites: (flags & WRITES) !== 0,
3818
+ transitivelyEmits: (flags & EMITS) !== 0
3819
+ });
3820
+ }
2833
3821
  }
2834
- return writeful;
2835
- }
2836
- function emitPurityDiagnostics(nodes, edges, writefulMethods, finalDiagnostics) {
2837
- for (const edge of edges.values()) {
3822
+ return effects;
3823
+ }
3824
+ /** What the diagnostic message says about the invoked Method, by effect flags. */
3825
+ const effectWording = [
3826
+ "",
3827
+ "writes State",
3828
+ "emits an Event",
3829
+ "writes State and emits an Event"
3830
+ ];
3831
+ function emitPurityDiagnostics(nodes, edges, methodEffects, finalDiagnostics) {
3832
+ for (const edge of edges) {
2838
3833
  if (edge.fromKind !== "property" || edge.toKind !== "method") continue;
2839
- if (!writefulMethods.has(`${edge.toNodeId}:${edge.toName}`)) continue;
3834
+ const flags = methodEffects.get(`${edge.toNodeId}:${edge.toName}`) ?? 0;
3835
+ if (flags === 0) continue;
2840
3836
  const ownerNode = nodes[edge.fromNodeId].publicNode;
2841
3837
  const targetNode = nodes[edge.toNodeId].publicNode;
2842
3838
  finalDiagnostics.push(dependencyDiagnostic(ownerNode, {
2843
3839
  type: "property",
2844
3840
  name: edge.fromName
2845
- }, "property-dependency-has-write-effects", `Property "${edge.fromName}" invokes writeful method "${edge.toName}".`, edge.reference, [methodLocation(targetNode, edge.toName)]));
3841
+ }, "property-dependency-has-side-effects", `Property "${edge.fromName}" invokes method "${edge.toName}", which ${effectWording[flags]} (itself or through the Methods it invokes).`, edge.reference, [methodLocation(targetNode, edge.toName)]));
2846
3842
  }
2847
3843
  }
2848
3844
  /**
2849
- * Tarjan's strongly-connected-components algorithm over the evaluation graph, visiting adjacency in
2850
- * `memberOrder` for determinism.
3845
+ * Evaluation-graph adjacency in compressed form: the targets of member `id` are
3846
+ * `targets[offsets[id]]` to `targets[offsets[id + 1] - 1]`, in edge-insertion order.
2851
3847
  */
2852
- function findStronglyConnectedComponents(memberOrder, adjacency) {
2853
- const indexOf = /* @__PURE__ */ new Map();
2854
- let indexCounter = 0;
2855
- const lowlink = /* @__PURE__ */ new Map();
2856
- const onStack = /* @__PURE__ */ new Set();
2857
- const stack = [];
3848
+ function buildAdjacency(edges, memberCount) {
3849
+ const offsets = new Int32Array(memberCount + 1);
3850
+ for (const edge of edges) offsets[edge.fromId + 1]++;
3851
+ for (let id = 0; id < memberCount; id++) offsets[id + 1] += offsets[id];
3852
+ const targets = new Int32Array(edges.length);
3853
+ const next = offsets.slice(0, memberCount);
3854
+ for (const edge of edges) targets[next[edge.fromId]++] = edge.toId;
3855
+ return {
3856
+ offsets,
3857
+ targets
3858
+ };
3859
+ }
3860
+ /**
3861
+ * Tarjan's strongly-connected-components algorithm over the evaluation graph, started from each member
3862
+ * in member order and visiting adjacency in edge-insertion order for determinism. Returns only the
3863
+ * cyclic components (more than one member, or one member with a self-loop), in the order Tarjan
3864
+ * completes them. A member without outgoing edges is a trivial component of its own and can never
3865
+ * take part in a cycle, so it is neither started from nor entered.
3866
+ */
3867
+ function findCyclicComponents(memberCount, offsets, targets) {
3868
+ const visitOrder = new Int32Array(memberCount);
3869
+ const lowlink = new Int32Array(memberCount);
3870
+ const onStack = new Uint8Array(memberCount);
3871
+ const hasSelfLoop = new Uint8Array(memberCount);
3872
+ const stack = new Int32Array(memberCount);
3873
+ const callStack = new Int32Array(memberCount);
3874
+ const cursor = new Int32Array(memberCount);
3875
+ let stackSize = 0;
3876
+ let visited = 0;
2858
3877
  const components = [];
2859
- function strongConnect(key) {
2860
- indexOf.set(key, indexCounter);
2861
- lowlink.set(key, indexCounter);
2862
- indexCounter++;
2863
- stack.push(key);
2864
- onStack.add(key);
2865
- for (const next of adjacency.get(key) ?? []) if (!indexOf.has(next)) {
2866
- strongConnect(next);
2867
- lowlink.set(key, Math.min(lowlink.get(key), lowlink.get(next)));
2868
- } else if (onStack.has(next)) lowlink.set(key, Math.min(lowlink.get(key), indexOf.get(next)));
2869
- if (lowlink.get(key) === indexOf.get(key)) {
2870
- const component = [];
2871
- let member;
2872
- do {
2873
- member = stack.pop();
2874
- onStack.delete(member);
2875
- component.push(member);
2876
- } while (member !== key);
2877
- components.push(component);
2878
- }
2879
- }
2880
- for (const key of memberOrder) if (!indexOf.has(key)) strongConnect(key);
3878
+ for (let root = 0; root < memberCount; root++) {
3879
+ if (visitOrder[root] !== 0 || offsets[root + 1] === offsets[root]) continue;
3880
+ let depth = 0;
3881
+ callStack[depth++] = root;
3882
+ visitOrder[root] = lowlink[root] = ++visited;
3883
+ cursor[root] = offsets[root];
3884
+ stack[stackSize++] = root;
3885
+ onStack[root] = 1;
3886
+ while (depth > 0) {
3887
+ const id = callStack[depth - 1];
3888
+ if (cursor[id] < offsets[id + 1]) {
3889
+ const next = targets[cursor[id]++];
3890
+ if (next === id) hasSelfLoop[id] = 1;
3891
+ if (visitOrder[next] === 0) {
3892
+ if (offsets[next + 1] === offsets[next]) continue;
3893
+ callStack[depth++] = next;
3894
+ visitOrder[next] = lowlink[next] = ++visited;
3895
+ cursor[next] = offsets[next];
3896
+ stack[stackSize++] = next;
3897
+ onStack[next] = 1;
3898
+ } else if (onStack[next] === 1) lowlink[id] = Math.min(lowlink[id], visitOrder[next]);
3899
+ continue;
3900
+ }
3901
+ depth--;
3902
+ if (lowlink[id] === visitOrder[id]) {
3903
+ const component = [];
3904
+ let member;
3905
+ do {
3906
+ member = stack[--stackSize];
3907
+ onStack[member] = 0;
3908
+ component.push(member);
3909
+ } while (member !== id);
3910
+ if (component.length > 1 || hasSelfLoop[id] === 1) components.push(component);
3911
+ }
3912
+ if (depth > 0) {
3913
+ const parent = callStack[depth - 1];
3914
+ lowlink[parent] = Math.min(lowlink[parent], lowlink[id]);
3915
+ }
3916
+ }
3917
+ }
2881
3918
  return components;
2882
3919
  }
2883
- function emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, finalDiagnostics) {
2884
- const refByKey = /* @__PURE__ */ new Map();
2885
- for (const ref of memberOrder) refByKey.set(memberKey(ref.kind, ref.nodeId, ref.name), ref);
2886
- const orderIndex = /* @__PURE__ */ new Map();
2887
- memberOrderKeys.forEach((key, index) => orderIndex.set(key, index));
2888
- const components = findStronglyConnectedComponents(memberOrderKeys, adjacency);
3920
+ function emitCycleDiagnostics(nodes, semanticOrder, memberCount, edges, finalDiagnostics) {
3921
+ const { offsets, targets } = buildAdjacency(edges, memberCount);
3922
+ const components = findCyclicComponents(memberCount, offsets, targets);
3923
+ if (components.length === 0) return [];
3924
+ const memberOrder = [];
3925
+ for (const nodeId of semanticOrder) {
3926
+ const node = nodes[nodeId];
3927
+ if (!node.resolved) continue;
3928
+ for (const name of node.properties.keys()) memberOrder.push({
3929
+ nodeId,
3930
+ kind: "property",
3931
+ name
3932
+ });
3933
+ for (const name of node.methods.keys()) memberOrder.push({
3934
+ nodeId,
3935
+ kind: "method",
3936
+ name
3937
+ });
3938
+ }
2889
3939
  const invalidCycles = [];
2890
3940
  for (const component of components) {
2891
- const hasSelfLoop = component.length === 1 && (adjacency.get(component[0]) ?? []).includes(component[0]);
2892
- if (!(component.length > 1 || hasSelfLoop)) continue;
2893
- const refs = component.map((key) => refByKey.get(key)).sort((a, b) => orderIndex.get(memberKey(a.kind, a.nodeId, a.name)) - orderIndex.get(memberKey(b.kind, b.nodeId, b.name)));
3941
+ const refs = component.sort((a, b) => a - b).map((id) => memberOrder[id]);
2894
3942
  const properties = refs.filter((ref) => ref.kind === "property");
2895
3943
  if (properties.length === 0) continue;
2896
3944
  invalidCycles.push(refs.map((ref) => ({
@@ -2900,9 +3948,9 @@ function emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, fi
2900
3948
  name: ref.name
2901
3949
  }
2902
3950
  })));
3951
+ const related = Object.freeze(refs.map((ref) => Object.freeze(memberLocation(nodes, ref))));
2903
3952
  for (const property of properties) {
2904
3953
  const ownerNode = nodes[property.nodeId].publicNode;
2905
- const related = refs.filter((ref) => ref !== property).map((ref) => memberLocation(nodes, ref));
2906
3954
  finalDiagnostics.push(dependencyDiagnostic(ownerNode, {
2907
3955
  type: "property",
2908
3956
  name: property.name
@@ -2911,36 +3959,12 @@ function emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, fi
2911
3959
  }
2912
3960
  return invalidCycles;
2913
3961
  }
2914
- function runGraphAnalysis(nodes, semanticOrder, edges, directWriteSeeds, finalDiagnostics) {
2915
- const writefulMethods = computeWritefulMethods(nodes, edges, directWriteSeeds);
2916
- emitPurityDiagnostics(nodes, edges, writefulMethods, finalDiagnostics);
2917
- const memberOrder = [];
2918
- for (const nodeId of semanticOrder) {
2919
- const node = nodes[nodeId];
2920
- if (!node.resolved) continue;
2921
- for (const name of node.properties.keys()) memberOrder.push({
2922
- nodeId,
2923
- kind: "property",
2924
- name
2925
- });
2926
- for (const name of node.methods.keys()) memberOrder.push({
2927
- nodeId,
2928
- kind: "method",
2929
- name
2930
- });
2931
- }
2932
- const memberOrderKeys = memberOrder.map((ref) => memberKey(ref.kind, ref.nodeId, ref.name));
2933
- const adjacency = /* @__PURE__ */ new Map();
2934
- for (const edge of edges.values()) {
2935
- const fromKey = memberKey(edge.fromKind, edge.fromNodeId, edge.fromName);
2936
- const toKey = memberKey(edge.toKind, edge.toNodeId, edge.toName);
2937
- const list = adjacency.get(fromKey);
2938
- if (list === void 0) adjacency.set(fromKey, [toKey]);
2939
- else list.push(toKey);
2940
- }
3962
+ function runGraphAnalysis(nodes, semanticOrder, edges, memberCount, directWriteSeeds, directEmitSeeds, finalDiagnostics) {
3963
+ const methodEffects = computeMethodEffects(nodes, edges, directWriteSeeds, directEmitSeeds);
3964
+ emitPurityDiagnostics(nodes, edges, methodEffects, finalDiagnostics);
2941
3965
  return {
2942
- writefulMethods,
2943
- invalidCycles: emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, finalDiagnostics)
3966
+ methodEffects,
3967
+ invalidCycles: emitCycleDiagnostics(nodes, semanticOrder, memberCount, edges, finalDiagnostics)
2944
3968
  };
2945
3969
  }
2946
3970
  //#endregion
@@ -2983,6 +4007,14 @@ function readOwnEnumerableStringKeys(object) {
2983
4007
  return null;
2984
4008
  }
2985
4009
  }
4010
+ /** The own keys of an authored widget node; `meta` is the reserved, uninterpreted extension key. */
4011
+ const RECOGNIZED_WIDGET_FIELDS = /* @__PURE__ */ new Set([
4012
+ "id",
4013
+ "type",
4014
+ "config",
4015
+ "slots",
4016
+ "meta"
4017
+ ]);
2986
4018
  function readArrayInfo(value) {
2987
4019
  try {
2988
4020
  if (!Array.isArray(value)) return {
@@ -3013,25 +4045,35 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3013
4045
  diagnostics: EMPTY_DIAGNOSTICS
3014
4046
  };
3015
4047
  const publicNode = shell;
4048
+ const location = Object.freeze(placement.kind === "root" ? { type: "root" } : placement.kind === "slot" ? {
4049
+ type: "slot",
4050
+ parent: parentPublicNode,
4051
+ slot: placement.slot,
4052
+ index: placement.index
4053
+ } : {
4054
+ type: "raw-slot",
4055
+ parent: parentPublicNode,
4056
+ slot: placement.slot,
4057
+ index: placement.index
4058
+ });
4059
+ const sourcePath = Object.freeze(placement.kind === "root" ? [] : [
4060
+ ...ctx.nodes[parentNodeId].sourcePath,
4061
+ "slots",
4062
+ placement.slot,
4063
+ placement.index
4064
+ ]);
3016
4065
  const working = {
3017
4066
  nodeId,
3018
4067
  parentNodeId,
3019
4068
  source: rawValue,
3020
4069
  rawSlots: [],
3021
- location: Object.freeze(placement.kind === "root" ? { type: "root" } : placement.kind === "slot" ? {
3022
- type: "slot",
3023
- parent: parentPublicNode,
3024
- slot: placement.slot,
3025
- index: placement.index
3026
- } : {
3027
- type: "raw-slot",
3028
- parent: parentPublicNode,
3029
- slot: placement.slot,
3030
- index: placement.index
3031
- }),
4070
+ location,
4071
+ sourcePath,
3032
4072
  resolved: false,
3033
4073
  id: null,
3034
4074
  type: null,
4075
+ typeHint: null,
4076
+ repeatsAncestor: false,
3035
4077
  plugin: null,
3036
4078
  rawConfig: null,
3037
4079
  config: null,
@@ -3051,20 +4093,29 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3051
4093
  flushDiagnostics(ctx, localDiagnostics);
3052
4094
  return nodeId;
3053
4095
  }
4096
+ const idProperty = readOwnDataProperty(raw, "id");
4097
+ const rawId = idProperty.accessible ? idProperty.value : void 0;
4098
+ const hasValidId = idProperty.found && idProperty.accessible && typeof rawId === "string";
4099
+ const typeProperty = readOwnDataProperty(raw, "type");
4100
+ const rawType = typeProperty.accessible ? typeProperty.value : void 0;
4101
+ const hasValidTypeShape = typeProperty.found && typeProperty.accessible && typeof rawType === "string";
4102
+ working.id = hasValidId ? rawId : null;
4103
+ working.typeHint = hasValidTypeShape ? rawType : null;
4104
+ if (sourcePath.length >= 256) {
4105
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-definition", `Widget definition is nested deeper than the maximum supported depth (256).`));
4106
+ finalizeShell(shell, working);
4107
+ flushDiagnostics(ctx, localDiagnostics);
4108
+ return nodeId;
4109
+ }
3054
4110
  if (ctx.activeSourceObjects.has(raw)) {
4111
+ working.repeatsAncestor = true;
3055
4112
  localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-definition", "Widget definition contains a cyclic source reference."));
3056
4113
  finalizeShell(shell, working);
3057
4114
  flushDiagnostics(ctx, localDiagnostics);
3058
4115
  return nodeId;
3059
4116
  }
3060
4117
  ctx.activeSourceObjects.add(raw);
3061
- const idProperty = readOwnDataProperty(raw, "id");
3062
- const rawId = idProperty.accessible ? idProperty.value : void 0;
3063
- const hasValidId = idProperty.found && idProperty.accessible && typeof rawId === "string";
3064
4118
  if (!hasValidId) localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-id", "Widget \"id\" is missing or is not a string.", ["id"]));
3065
- const typeProperty = readOwnDataProperty(raw, "type");
3066
- const rawType = typeProperty.accessible ? typeProperty.value : void 0;
3067
- const hasValidTypeShape = typeProperty.found && typeProperty.accessible && typeof rawType === "string";
3068
4119
  let plugin = null;
3069
4120
  if (!hasValidTypeShape) localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-type", "Widget \"type\" is missing or is not a string.", ["type"]));
3070
4121
  else {
@@ -3073,7 +4124,6 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3073
4124
  }
3074
4125
  const resolved = hasValidId && hasValidTypeShape && plugin !== null;
3075
4126
  working.resolved = resolved;
3076
- working.id = hasValidId ? rawId : null;
3077
4127
  if (resolved) {
3078
4128
  working.type = rawType;
3079
4129
  working.plugin = plugin;
@@ -3127,6 +4177,10 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3127
4177
  });
3128
4178
  }
3129
4179
  recoverSlots(ctx, working, raw, resolved ? working.plugin : null, localDiagnostics);
4180
+ const ownKeys = readOwnEnumerableStringKeys(raw);
4181
+ if (ownKeys !== null) {
4182
+ for (const key of ownKeys) if (!RECOGNIZED_WIDGET_FIELDS.has(key)) localDiagnostics.push(definitionDiagnostic(publicNode, "unexpected-widget-field", `Widget field "${key}" is not recognized; extension data belongs under "meta".`, [key]));
4183
+ }
3130
4184
  ctx.activeSourceObjects.delete(raw);
3131
4185
  finalizeShell(shell, working);
3132
4186
  flushDiagnostics(ctx, localDiagnostics);
@@ -3143,6 +4197,9 @@ function finalizeShell(shell, working) {
3143
4197
  shell.config = working.config;
3144
4198
  }
3145
4199
  shell.slots = {};
4200
+ } else {
4201
+ shell.id = working.id;
4202
+ shell.type = working.typeHint;
3146
4203
  }
3147
4204
  }
3148
4205
  /**
@@ -3208,8 +4265,12 @@ function recoverSlots(ctx, working, raw, plugin, localDiagnostics) {
3208
4265
  }
3209
4266
  fillMissingDeclaredSlots();
3210
4267
  }
4268
+ /**
4269
+ * One push per diagnostic, never `push(...diagnostics)`: a node with very many unknown keys produces more
4270
+ * diagnostics than an engine accepts as call arguments.
4271
+ */
3211
4272
  function flushDiagnostics(ctx, diagnostics) {
3212
- ctx.finalDiagnostics.push(...diagnostics);
4273
+ for (const diagnostic of diagnostics) ctx.finalDiagnostics.push(diagnostic);
3213
4274
  }
3214
4275
  /**
3215
4276
  * Fills in every resolved node's `.slots` public field from its (by-then complete) children and
@@ -3229,7 +4290,7 @@ function finalizeSlots(ctx) {
3229
4290
  function computeWidgetIdIndex(ctx) {
3230
4291
  const index = /* @__PURE__ */ new Map();
3231
4292
  for (const node of ctx.nodes) {
3232
- if (node.id === null) continue;
4293
+ if (node.id === null || node.repeatsAncestor) continue;
3233
4294
  const list = index.get(node.id);
3234
4295
  if (list === void 0) index.set(node.id, [node.nodeId]);
3235
4296
  else list.push(node.nodeId);
@@ -3239,10 +4300,11 @@ function computeWidgetIdIndex(ctx) {
3239
4300
  function emitDuplicateIdDiagnostics(ctx, index) {
3240
4301
  for (const ids of index.values()) {
3241
4302
  if (ids.length < 2) continue;
3242
- for (const nodeId of ids) {
4303
+ const locations = ids.map((id) => sharedWidgetLocation(ctx.nodes[id].publicNode));
4304
+ for (const [position, nodeId] of ids.entries()) {
3243
4305
  const node = ctx.nodes[nodeId];
3244
- const related = ids.filter((otherId) => otherId !== nodeId).map((otherId) => widgetLocation(ctx.nodes[otherId].publicNode));
3245
- ctx.finalDiagnostics.push(definitionDiagnostic(node.publicNode, "invalid-widget-id", `Duplicate widget id "${node.id}".`, ["id"], related));
4306
+ const related = locations.filter((_, otherPosition) => otherPosition !== position);
4307
+ ctx.finalDiagnostics.push(definitionDiagnostic(node.publicNode, "duplicate-widget-id", `Duplicate widget id "${node.id}".`, ["id"], related));
3246
4308
  }
3247
4309
  }
3248
4310
  }
@@ -3297,6 +4359,36 @@ function recoverBlueprint(system, definition) {
3297
4359
  }
3298
4360
  //#endregion
3299
4361
  //#region src/blueprint/structure.ts
4362
+ /**
4363
+ * A structure validator that reports a location absent from the Blueprint being compiled (an index outside
4364
+ * the slot, an undeclared slot, a node of another Blueprint) violates the callback contract, exactly like
4365
+ * the other callback-contract escapes (`blueprint/deps.ts`): it is an implementation bug, not an Issue.
4366
+ */
4367
+ function structureLocationViolation(scope, field, detail) {
4368
+ return /* @__PURE__ */ new TypeError(`${scope} reported a structure diagnostic whose ${field} ${detail}; this is a plugin implementation bug.`);
4369
+ }
4370
+ function assertSlotIndex(scope, field, index, childCount) {
4371
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= childCount) throw structureLocationViolation(scope, field, `is not an existing child index (the slot has ${childCount} children)`);
4372
+ }
4373
+ function assertDeclaredSlot(scope, field, node, slot) {
4374
+ if (typeof slot !== "string" || !node.resolved || !node.semanticSlots.has(slot)) throw structureLocationViolation(scope, field, "is not a slot declared by the widget's plugin");
4375
+ }
4376
+ /**
4377
+ * Validates one system-level location (`location` or a `related` entry) against the Blueprint being compiled.
4378
+ * `field` names the offending field path, e.g. `location` or `related[1]`.
4379
+ */
4380
+ function assertSystemLocation(nodes, resolveNodeId, field, location) {
4381
+ const scope = "System-level validateStructure";
4382
+ if (typeof location !== "object" || location === null) throw structureLocationViolation(scope, field, "is not a location object");
4383
+ const { type, node: locationNode, slot, index } = location;
4384
+ if (type !== "widget" && type !== "slot" && type !== "slot-child") throw structureLocationViolation(scope, `${field}.type`, "is not \"widget\", \"slot\" or \"slot-child\"");
4385
+ const nodeId = resolveNodeId(locationNode);
4386
+ if (nodeId === void 0) throw structureLocationViolation(scope, `${field}.node`, "is not a node of the Blueprint being compiled");
4387
+ if (type === "widget") return;
4388
+ const node = nodes[nodeId];
4389
+ assertDeclaredSlot(scope, `${field}.slot`, node, slot);
4390
+ if (type === "slot-child") assertSlotIndex(scope, `${field}.index`, index, node.semanticSlots.get(slot).length);
4391
+ }
3300
4392
  function configFragment(node) {
3301
4393
  return node.plugin !== null && readWidgetPluginDefinition(node.plugin).config !== null ? { config: node.config } : {};
3302
4394
  }
@@ -3381,40 +4473,49 @@ function runStructureValidation(system, nodes, semanticOrder, compileFacade, fin
3381
4473
  if (!node.resolved || node.plugin === null) continue;
3382
4474
  const definition = readWidgetPluginDefinition(node.plugin);
3383
4475
  const publicNode = node.publicNode;
3384
- const widgetFacade = compileFacade.facadeForNodeId(nodeId);
3385
4476
  if (definition.slots !== null) for (const [slotName, slotDefinition] of definition.slots) {
3386
4477
  if (slotDefinition.validateStructure === void 0) continue;
3387
4478
  const children = (node.semanticSlots.get(slotName) ?? []).map((id) => compileFacade.facadeForNodeId(id));
3388
4479
  const { collector, items, close } = createCollector();
3389
4480
  try {
3390
- assertSyncValue(slotDefinition.validateStructure({
3391
- widget: widgetFacade,
4481
+ const result = slotDefinition.validateStructure({
4482
+ widget: compileFacade.facadeForNodeId(nodeId),
3392
4483
  slot: slotName,
3393
4484
  children,
3394
4485
  blueprint: compileFacade.view,
3395
4486
  ...configFragment(node),
3396
4487
  ...collector
3397
- }), `Slot "${slotName}"'s validateStructure`);
4488
+ });
4489
+ assertSyncValue(result, `Slot "${slotName}"'s validateStructure`);
3398
4490
  } finally {
3399
4491
  close();
3400
4492
  }
3401
- for (const item of items) finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slotName, item.index, void 0, item.reason));
4493
+ for (const item of items) {
4494
+ if (item.index !== void 0) assertSlotIndex(`Slot "${slotName}"'s validateStructure`, "index", item.index, children.length);
4495
+ finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slotName, item.index, void 0, item.reason));
4496
+ }
3402
4497
  }
3403
4498
  if (definition.validateStructure !== null) {
3404
4499
  const { collector, items, close } = createCollector();
3405
4500
  try {
3406
- assertSyncValue(definition.validateStructure({
3407
- widget: widgetFacade,
4501
+ const result = definition.validateStructure({
4502
+ widget: compileFacade.facadeForNodeId(nodeId),
3408
4503
  blueprint: compileFacade.view,
3409
4504
  ...configFragment(node),
3410
4505
  ...collector
3411
- }), `Plugin "${node.type}"'s validateStructure`);
4506
+ });
4507
+ assertSyncValue(result, `Plugin "${node.type}"'s validateStructure`);
3412
4508
  } finally {
3413
4509
  close();
3414
4510
  }
3415
4511
  for (const item of items) {
3416
4512
  const slot = "slot" in item ? item.slot : void 0;
3417
4513
  const index = "index" in item ? item.index : void 0;
4514
+ const scope = `Plugin "${node.type}"'s validateStructure`;
4515
+ if (slot !== void 0) {
4516
+ assertDeclaredSlot(scope, "slot", node, slot);
4517
+ if (index !== void 0) assertSlotIndex(scope, "index", index, node.semanticSlots.get(slot).length);
4518
+ } else if (index !== void 0) throw structureLocationViolation(scope, "index", "has no slot to be an index of");
3418
4519
  finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slot, index, void 0, item.reason));
3419
4520
  }
3420
4521
  }
@@ -3422,10 +4523,11 @@ function runStructureValidation(system, nodes, semanticOrder, compileFacade, fin
3422
4523
  if (system.validateStructure !== null) {
3423
4524
  const { collector, items, close } = createCollector();
3424
4525
  try {
3425
- assertSyncValue(system.validateStructure({
4526
+ const result = system.validateStructure({
3426
4527
  blueprint: compileFacade.view,
3427
4528
  ...collector
3428
- }), "System-level validateStructure");
4529
+ });
4530
+ assertSyncValue(result, "System-level validateStructure");
3429
4531
  } finally {
3430
4532
  close();
3431
4533
  }
@@ -3433,6 +4535,8 @@ function runStructureValidation(system, nodes, semanticOrder, compileFacade, fin
3433
4535
  semanticOrder.forEach((nodeId, index) => semanticOrderIndex.set(nodeId, index));
3434
4536
  for (const item of items) {
3435
4537
  const { location, related } = item;
4538
+ assertSystemLocation(nodes, compileFacade.resolveNodeId, "location", location);
4539
+ related?.forEach((relatedLocation, relatedIndex) => assertSystemLocation(nodes, compileFacade.resolveNodeId, `related[${relatedIndex}]`, relatedLocation));
3436
4540
  const nodeId = compileFacade.resolveNodeId(location.node);
3437
4541
  const realNode = nodeId !== void 0 ? nodes[nodeId].publicNode : location.node;
3438
4542
  finalDiagnostics.push(structureDiagnostic(realNode, item.message, location.type === "widget" ? void 0 : location.slot, location.type === "slot-child" ? location.index : void 0, normalizeRelated(nodes, semanticOrderIndex, compileFacade.resolveNodeId, related), item.reason));
@@ -3468,6 +4572,11 @@ function createNavigator(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeI
3468
4572
  if (nodeId === void 0) return null;
3469
4573
  return nodes[nodeId].location;
3470
4574
  },
4575
+ getSourcePath(node) {
4576
+ const nodeId = nodeIdByPublicNode.get(node);
4577
+ if (nodeId === void 0) return null;
4578
+ return nodes[nodeId].sourcePath;
4579
+ },
3471
4580
  getChildren(node) {
3472
4581
  const nodeId = nodeIdByPublicNode.get(node);
3473
4582
  if (nodeId === void 0) return EMPTY_CHILDREN;
@@ -3512,6 +4621,9 @@ function createCompileFacade(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootN
3512
4621
  const slots = Object.create(null);
3513
4622
  for (const [slotName, childIds] of working.semanticSlots) slots[slotName] = Object.freeze(childIds.map((childId) => facadeForNodeId(childId)));
3514
4623
  shell.slots = Object.freeze(slots);
4624
+ } else {
4625
+ shell.id = working.id;
4626
+ shell.type = working.typeHint;
3515
4627
  }
3516
4628
  const facade = Object.freeze(shell);
3517
4629
  facadeByNodeId.set(nodeId, facade);
@@ -3606,13 +4718,15 @@ function buildCompiledNodes(nodes, diagnosticsByNode) {
3606
4718
  source: node.source,
3607
4719
  parentNodeId: node.parentNodeId,
3608
4720
  location: node.location,
4721
+ sourcePath: node.sourcePath,
3609
4722
  rawSlots: Object.freeze(node.rawSlots),
3610
4723
  diagnostics
3611
4724
  };
3612
4725
  if (!node.resolved) return {
3613
4726
  ...base,
3614
4727
  resolved: false,
3615
- id: node.id
4728
+ id: node.id,
4729
+ type: node.typeHint
3616
4730
  };
3617
4731
  return {
3618
4732
  ...base,
@@ -3629,28 +4743,31 @@ function buildCompiledNodes(nodes, diagnosticsByNode) {
3629
4743
  };
3630
4744
  });
3631
4745
  }
3632
- const JSON_PROVEN_BY_CONSTRUCTION = Object.freeze({
3633
- compatible: true,
3634
- diagnostics: Object.freeze([])
3635
- });
3636
4746
  /**
3637
4747
  * `sourceJsonProven` is set only for a value Core itself produced with `JSON.parse` (no reviver): such a
3638
- * value cannot hold anything `inspectJsonValue` rejects, so the inspection would prove nothing new.
4748
+ * value can only leave the JSON domain through a non-finite number (`1e400`), so a cheap scan replaces the
4749
+ * full `inspectJsonValue` inspection and the result stays equivalent to `createBlueprint(JSON.parse(text))`.
4750
+ *
4751
+ * Compile-time plugin callbacks (config, structure, `registerDeps`) own no dependency or `emit` callables,
4752
+ * so a Blueprint compiled while a Method runs must not let them use that Method's (see `callbackScope`).
3639
4753
  */
3640
4754
  function compileBlueprint(system, definition, sourceJsonProven = false) {
4755
+ return runOutsideCallbacks(() => compileBlueprintOutsideCallbacks(system, definition, sourceJsonProven));
4756
+ }
4757
+ function compileBlueprintOutsideCallbacks(system, definition, sourceJsonProven) {
3641
4758
  const { nodes, rootNodeId, nodeIdByPublicNode, nodeIdsByWidgetId, finalDiagnostics, diagnosticsByNode } = recoverBlueprint(system, definition);
3642
- const jsonInspection = sourceJsonProven ? JSON_PROVEN_BY_CONSTRUCTION : inspectJsonValue(definition);
4759
+ const jsonInspection = sourceJsonProven ? inspectParsedJsonValue(definition) : inspectJsonValue(definition);
3643
4760
  const sourceJsonCompatible = jsonInspection.compatible;
3644
- finalDiagnostics.push(...jsonInspection.diagnostics);
4761
+ for (const diagnostic of jsonInspection.diagnostics) finalDiagnostics.push(diagnostic);
3645
4762
  const semanticOrder = computeSemanticOrder(nodes, rootNodeId);
3646
4763
  const navigator = createNavigator(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId);
3647
4764
  const compileFacade = createCompileFacade(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId);
3648
4765
  runStructureValidation(system, nodes, semanticOrder, compileFacade, finalDiagnostics);
3649
- const { edges, directWriteSeeds } = resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics);
3650
- const analysis = runGraphAnalysis(nodes, semanticOrder, edges, directWriteSeeds, finalDiagnostics);
4766
+ const { edges, memberCount, directWriteSeeds, directEmitSeeds } = resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics);
4767
+ const analysis = runGraphAnalysis(nodes, semanticOrder, edges, memberCount, directWriteSeeds, directEmitSeeds, finalDiagnostics);
3651
4768
  finalizeDiagnosticsByNode(nodeIdByPublicNode, finalDiagnostics, diagnosticsByNode);
3652
- for (const list of diagnosticsByNode.values()) freezeDiagnosticSnapshot(list);
3653
4769
  freezeDiagnosticSnapshot(finalDiagnostics);
4770
+ for (const list of diagnosticsByNode.values()) Object.freeze(list);
3654
4771
  for (const node of nodes) {
3655
4772
  const shell = node.publicNode;
3656
4773
  shell.diagnostics = diagnosticsByNode.get(node.nodeId) ?? EMPTY_DIAGNOSTICS;
@@ -3682,6 +4799,7 @@ function compileBlueprint(system, definition, sourceJsonProven = false) {
3682
4799
  getWidget: validNavigator.getWidget,
3683
4800
  getParent: validNavigator.getParent,
3684
4801
  getLocation: validNavigator.getLocation,
4802
+ getSourcePath: validNavigator.getSourcePath,
3685
4803
  getChildren: validNavigator.getChildren,
3686
4804
  getChildrenAt: validNavigator.getChildrenAt,
3687
4805
  diagnostics: EMPTY_DIAGNOSTICS,
@@ -3702,6 +4820,7 @@ function compileBlueprint(system, definition, sourceJsonProven = false) {
3702
4820
  getWidget: jsonInvalidNavigator.getWidget,
3703
4821
  getParent: jsonInvalidNavigator.getParent,
3704
4822
  getLocation: jsonInvalidNavigator.getLocation,
4823
+ getSourcePath: jsonInvalidNavigator.getSourcePath,
3705
4824
  getChildren: jsonInvalidNavigator.getChildren,
3706
4825
  getChildrenAt: jsonInvalidNavigator.getChildrenAt,
3707
4826
  diagnostics: finalDiagnostics,
@@ -3717,6 +4836,7 @@ function compileBlueprint(system, definition, sourceJsonProven = false) {
3717
4836
  getWidget: invalidNavigator.getWidget,
3718
4837
  getParent: invalidNavigator.getParent,
3719
4838
  getLocation: invalidNavigator.getLocation,
4839
+ getSourcePath: invalidNavigator.getSourcePath,
3720
4840
  getChildren: invalidNavigator.getChildren,
3721
4841
  getChildrenAt: invalidNavigator.getChildrenAt,
3722
4842
  diagnostics: finalDiagnostics,
@@ -3734,9 +4854,13 @@ function attachInternalsAndFreeze(blueprint, compiled) {
3734
4854
  //#endregion
3735
4855
  //#region src/system.ts
3736
4856
  /**
3737
- * Thrown by `createWidgetSystem` for an invalid plugin registration. Discriminate by class and `code`;
3738
- * `message` is not protocol.
4857
+ * Thrown by `createWidgetSystem` for invalid options or an invalid plugin registration. Discriminate by
4858
+ * class and `code`; `message` is not protocol. The options shape is checked first, then the plugin
4859
+ * entries in tuple order.
3739
4860
  *
4861
+ * - `invalid-options`: `options` is not an object, `options.plugins` is not an array, or
4862
+ * `options.validateStructure` is present (neither `undefined` nor `null`) but not a function.
4863
+ * `pluginIndex`, `pluginType` and `firstPluginIndex` are `null`.
3740
4864
  * - `foreign-plugin`: the entry at `pluginIndex` was not completed by this loaded module instance
3741
4865
  * (another module instance or a structural look-alike). `pluginType` is its `type` when a string,
3742
4866
  * else `null`. `firstPluginIndex` is `null`.
@@ -3749,7 +4873,7 @@ var WidgetSystemConfigurationError = class extends Error {
3749
4873
  pluginType;
3750
4874
  firstPluginIndex;
3751
4875
  name = "WidgetSystemConfigurationError";
3752
- constructor(code, pluginIndex, pluginType, firstPluginIndex = null, message = code === "foreign-plugin" ? `The widget plugin at index ${pluginIndex} was not created by this widget core instance.` : `Duplicate widget plugin type "${pluginType}" at index ${pluginIndex} (first registered at index ${firstPluginIndex}).`) {
4876
+ constructor(code, pluginIndex, pluginType, firstPluginIndex = null, message = code === "invalid-options" ? "The createWidgetSystem options are malformed." : code === "foreign-plugin" ? `The widget plugin at index ${pluginIndex} was not created by this widget core instance.` : `Duplicate widget plugin type "${pluginType}" at index ${pluginIndex} (first registered at index ${firstPluginIndex}).`) {
3753
4877
  super(message);
3754
4878
  this.code = code;
3755
4879
  this.pluginIndex = pluginIndex;
@@ -3757,6 +4881,21 @@ var WidgetSystemConfigurationError = class extends Error {
3757
4881
  this.firstPluginIndex = firstPluginIndex;
3758
4882
  }
3759
4883
  };
4884
+ function describeOptionValue(value) {
4885
+ return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
4886
+ }
4887
+ function invalidOptions(problem) {
4888
+ return new WidgetSystemConfigurationError("invalid-options", null, null, null, `Invalid createWidgetSystem options: ${problem}.`);
4889
+ }
4890
+ /**
4891
+ * Checks the options shape before any plugin entry is inspected.
4892
+ */
4893
+ function assertWidgetSystemOptions(options) {
4894
+ if (typeof options !== "object" || options === null) throw invalidOptions(`expected an options object, got ${describeOptionValue(options)}`);
4895
+ const { plugins, validateStructure } = options;
4896
+ if (!Array.isArray(plugins)) throw invalidOptions(`"plugins" must be an array of widget plugins, got ${describeOptionValue(plugins)}`);
4897
+ if (validateStructure !== void 0 && validateStructure !== null && typeof validateStructure !== "function") throw invalidOptions(`"validateStructure" must be a function when provided, got ${describeOptionValue(validateStructure)}`);
4898
+ }
3760
4899
  /**
3761
4900
  * Best-effort read of a foreign entry's `type`; a throwing accessor must not leak as an uncoded failure.
3762
4901
  */
@@ -3769,9 +4908,11 @@ function readForeignPluginType(entry) {
3769
4908
  }
3770
4909
  }
3771
4910
  /**
3772
- * Creates an instance-scoped, immutable widget system. Duplicate `plugin.type` is rejected.
4911
+ * Creates an instance-scoped, immutable widget system. Malformed options, foreign plugins and duplicate
4912
+ * `plugin.type` are rejected with a `WidgetSystemConfigurationError`.
3773
4913
  */
3774
4914
  function createWidgetSystem(options) {
4915
+ assertWidgetSystemOptions(options);
3775
4916
  const plugins = Object.freeze([...options.plugins]);
3776
4917
  const pluginsByType = /* @__PURE__ */ new Map();
3777
4918
  const firstIndexByType = /* @__PURE__ */ new Map();
@@ -3795,9 +4936,7 @@ function createWidgetSystem(options) {
3795
4936
  plugins,
3796
4937
  validateStructure: options.validateStructure ?? null,
3797
4938
  catalog,
3798
- getPlugin(type) {
3799
- return pluginsByType.get(type);
3800
- },
4939
+ getPlugin: ((type) => pluginsByType.get(type) ?? null),
3801
4940
  createBlueprint(definition) {
3802
4941
  return compileBlueprint(system, definition);
3803
4942
  },
@@ -3808,4 +4947,4 @@ function createWidgetSystem(options) {
3808
4947
  return Object.freeze(system);
3809
4948
  }
3810
4949
  //#endregion
3811
- export { EMPTY_DIAGNOSTICS, WIDGET_CONFIG_JSON_SCHEMA_DIALECT, WidgetSystemConfigurationError, WidgetSystemRuntimeDisposedError, createWidgetDocument, createWidgetPlugin, createWidgetSystem, createWidgetValueContract, normalizeSeparatedWidgetSource, separateWidgetSource };
4950
+ export { EMPTY_DIAGNOSTICS, MAX_JSON_DEPTH, WIDGET_CONFIG_JSON_SCHEMA_DIALECT, WidgetSystemConfigurationError, WidgetSystemRuntimeDisposedError, WidgetSystemRuntimeReentrancyError, createWidgetDocument, createWidgetPlugin, createWidgetSystem, createWidgetValueContract, isJsonValue, normalizeSeparatedWidgetSource, separateWidgetSource, setIsolatedErrorHandler };