@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/README.md +244 -64
- package/dist/{dep-DKbvAjPb.d.mts → dep-BXcdMm-M.d.mts} +298 -89
- package/dist/event-Bk-mkL1E.mjs +956 -0
- package/dist/index.d.mts +93 -12
- package/dist/index.mjs +1735 -596
- package/dist/inspection/index.d.mts +35 -3
- package/dist/inspection/index.mjs +23 -2
- package/dist/integration/index.d.mts +8 -2
- package/dist/integration/index.mjs +11 -3
- package/dist/internals-CVKUQDIN.mjs +388 -0
- package/package.json +3 -2
- package/dist/event-BMif_vRJ.mjs +0 -192
- package/dist/internals-L391flXY.mjs +0 -199
|
@@ -0,0 +1,956 @@
|
|
|
1
|
+
import { effect, endBatch, getActiveSub, getBatchDepth, setActiveSub, startBatch } from "alien-signals";
|
|
2
|
+
//#region src/diagnostic.ts
|
|
3
|
+
const EMPTY_DIAGNOSTICS = Object.freeze([]);
|
|
4
|
+
var WidgetSystemRuntimeDisposedError = class extends Error {
|
|
5
|
+
name = "WidgetSystemRuntimeDisposedError";
|
|
6
|
+
code = "runtime-disposed";
|
|
7
|
+
constructor(message = "The widget system runtime has been disposed.") {
|
|
8
|
+
super(message);
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Thrown when one Runtime's event emits nest deeper than its re-entrancy limit: an event listener keeps
|
|
13
|
+
* re-invoking a Method that emits again. A non-semantic safety guard against runaway re-entrancy (a
|
|
14
|
+
* `RangeError`, like any other runaway recursion), never a Diagnostic. Event-listener isolation does not
|
|
15
|
+
* swallow it, so it unwinds every nested emit to the operation that started the loop.
|
|
16
|
+
*/
|
|
17
|
+
var WidgetSystemRuntimeReentrancyError = class extends RangeError {
|
|
18
|
+
name = "WidgetSystemRuntimeReentrancyError";
|
|
19
|
+
code = "emit-depth-exceeded";
|
|
20
|
+
constructor(message = "Event emits nested deeper than the Runtime's re-entrancy limit: an event listener keeps re-invoking a Method that emits.") {
|
|
21
|
+
super(message);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/runtime/context.ts
|
|
26
|
+
function createCallbackOwner(widgetId, method, emits) {
|
|
27
|
+
return {
|
|
28
|
+
sink: null,
|
|
29
|
+
widgetId,
|
|
30
|
+
method,
|
|
31
|
+
emits
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The innermost running `compute`/`execute` callback of this widget-core instance, across every Runtime.
|
|
36
|
+
*
|
|
37
|
+
* A dependency callable may run only while its own owner is the innermost running callback — not after
|
|
38
|
+
* that callback returned or threw, and not from another callback running inside it. The second half is
|
|
39
|
+
* what keeps a Property `compute` from ever writing State through a setter retained from a Method that is
|
|
40
|
+
* still running further down the stack (a Property is the innermost callback while it evaluates; a
|
|
41
|
+
* read-only Method it invokes is innermost while that Method runs). Realm-wide rather than per Runtime
|
|
42
|
+
* so the same holds when the Method and the Property belong to different Runtimes.
|
|
43
|
+
*
|
|
44
|
+
* Code that is not such a callback never counts as one, even while it runs inside one: an external
|
|
45
|
+
* listener (State, Property, diagnostics, Event, `WidgetDocument`, inspection) and a plugin callback that
|
|
46
|
+
* owns no callables (`validate`, `validateArgs`, `default`, a dependency `.validate()` refinement, config
|
|
47
|
+
* and structure callbacks) run with `owner` set to `null`, so a callable retained from the Method that
|
|
48
|
+
* triggered them throws there; the owner is restored once that code returned or threw. What this cannot
|
|
49
|
+
* tell apart is a callable retained from an earlier invocation of the same member and used during a later
|
|
50
|
+
* one: the check compares members, not invocations (the one accepted gap).
|
|
51
|
+
*
|
|
52
|
+
* A mutable holder so callbacks save and restore it with plain assignments rather than calls: a restore
|
|
53
|
+
* in a `finally` then still runs when runaway recursion has exhausted the stack, and each frame restores
|
|
54
|
+
* the absolute value it saved, so one frame that cannot restore is corrected by the next.
|
|
55
|
+
*/
|
|
56
|
+
const callbackScope = { owner: null };
|
|
57
|
+
/**
|
|
58
|
+
* Runs `run` with no callback open (see {@link callbackScope}) and restores the previous owner afterwards,
|
|
59
|
+
* also when `run` throws. For code that is not a callback owning dependency or `emit` callables; hot paths
|
|
60
|
+
* inline the same save/restore instead of allocating a closure.
|
|
61
|
+
*/
|
|
62
|
+
function runOutsideCallbacks(run) {
|
|
63
|
+
const previousOwner = callbackScope.owner;
|
|
64
|
+
callbackScope.owner = null;
|
|
65
|
+
try {
|
|
66
|
+
return run();
|
|
67
|
+
} finally {
|
|
68
|
+
callbackScope.owner = previousOwner;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function createRuntimeContext() {
|
|
72
|
+
let disposed = false;
|
|
73
|
+
const owned = /* @__PURE__ */ new Set();
|
|
74
|
+
let disposalListeners = /* @__PURE__ */ new Set();
|
|
75
|
+
function assertActive() {
|
|
76
|
+
if (disposed) throw new WidgetSystemRuntimeDisposedError();
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
isDisposed: () => disposed,
|
|
80
|
+
assertActive,
|
|
81
|
+
emitNesting: {
|
|
82
|
+
depth: 0,
|
|
83
|
+
unwinding: null
|
|
84
|
+
},
|
|
85
|
+
registerSubscription(rawDispose) {
|
|
86
|
+
let unsubscribed = false;
|
|
87
|
+
const handle = () => {
|
|
88
|
+
if (unsubscribed) return;
|
|
89
|
+
unsubscribed = true;
|
|
90
|
+
if (!disposed) owned.delete(handle);
|
|
91
|
+
rawDispose();
|
|
92
|
+
};
|
|
93
|
+
owned.add(handle);
|
|
94
|
+
return handle;
|
|
95
|
+
},
|
|
96
|
+
subscribeDisposal(listener) {
|
|
97
|
+
assertActive();
|
|
98
|
+
const entry = { listener };
|
|
99
|
+
disposalListeners.add(entry);
|
|
100
|
+
return () => {
|
|
101
|
+
if (disposed) return;
|
|
102
|
+
disposalListeners.delete(entry);
|
|
103
|
+
entry.listener = null;
|
|
104
|
+
};
|
|
105
|
+
},
|
|
106
|
+
dispose() {
|
|
107
|
+
if (disposed) return;
|
|
108
|
+
disposed = true;
|
|
109
|
+
for (const handle of owned) handle();
|
|
110
|
+
owned.clear();
|
|
111
|
+
const delivering = [...disposalListeners];
|
|
112
|
+
disposalListeners = /* @__PURE__ */ new Set();
|
|
113
|
+
for (const entry of delivering) {
|
|
114
|
+
const listener = entry.listener;
|
|
115
|
+
entry.listener = null;
|
|
116
|
+
if (listener !== null) invokeListenerIsolated(() => listener(), void 0);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/runtime/adapter.ts
|
|
123
|
+
/**
|
|
124
|
+
* The function isolated exceptions are handed to, or `null` for the default report: a queued microtask
|
|
125
|
+
* rethrow. Realm-wide, like the delivery queue it relies on: a report site has no Runtime at hand, and some
|
|
126
|
+
* reports (a `WidgetDocument` subscriber's exception, the delivery bound's `RangeError`) belong to none.
|
|
127
|
+
*/
|
|
128
|
+
let isolatedErrorHandler = null;
|
|
129
|
+
/**
|
|
130
|
+
* Sets the function that receives the exceptions Core isolates: those thrown by a State, Property,
|
|
131
|
+
* diagnostics, Event, disposal, inspection or `WidgetDocument` listener, by a Property `compute` while a
|
|
132
|
+
* subscription re-evaluates it, and the `RangeError` that reports a bounded runaway loop. `null` or
|
|
133
|
+
* `undefined` restores the default report, a rethrow in a queued microtask. Returns the handler that was set
|
|
134
|
+
* before (`null` for the default), so a caller that sets one temporarily can put it back.
|
|
135
|
+
*
|
|
136
|
+
* Every report goes through one hand-over pass (see {@link deliverQueued}): an exception isolated while a
|
|
137
|
+
* Runtime operation is in progress is handed over once the outermost operation has finished its work, still
|
|
138
|
+
* before it returns to its caller (also when it throws); one isolated with no operation in progress starts the
|
|
139
|
+
* pass at once. Within a pass, reports and Property inspection deliveries are handed over one at a time, in the
|
|
140
|
+
* order Core produced them, and the handler is never re-entered: what its own calls isolate is handed over
|
|
141
|
+
* after it returns, behind what was already waiting. The handler therefore never runs while Core is evaluating,
|
|
142
|
+
* checking or flushing (unless the host holds its own alien-signals batch, which is unsupported), and it may
|
|
143
|
+
* read and write any Runtime. A `compute` exception that several subscriptions re-read is handed over once
|
|
144
|
+
* per pass.
|
|
145
|
+
*
|
|
146
|
+
* A handler that throws breaks nothing: its exception is rethrown in a queued microtask, and the remaining
|
|
147
|
+
* reports are still handed over. A report still queued when the handler is replaced goes to the new handler;
|
|
148
|
+
* one still queued when the handler is removed is rethrown in a microtask. A handler whose handling keeps
|
|
149
|
+
* causing new isolated exceptions is stopped by {@link MAX_HANDLER_CAUSED_DEPTH} and
|
|
150
|
+
* {@link MAX_HANDLER_CAUSED_REPORTS}, and what its handling causes after the inspection delivery bound stopped a
|
|
151
|
+
* pass is rethrown in a microtask too. These rethrows are the only microtasks Core queues while a handler is
|
|
152
|
+
* set; in a host without `queueMicrotask` such a report is dropped, and nothing else is affected. One handler serves the
|
|
153
|
+
* whole loaded Core module, every System, Runtime and `WidgetDocument` alike: it belongs to the host, and a
|
|
154
|
+
* plugin or renderer library must not set it.
|
|
155
|
+
*/
|
|
156
|
+
function setIsolatedErrorHandler(handler) {
|
|
157
|
+
if (handler !== null && handler !== void 0 && typeof handler !== "function") throw new TypeError(`setIsolatedErrorHandler() expects a function, null or undefined, got ${typeof handler}.`);
|
|
158
|
+
const previous = isolatedErrorHandler;
|
|
159
|
+
isolatedErrorHandler = handler ?? null;
|
|
160
|
+
return previous;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Reports an exception isolated from the current operation through the host's error-reporting
|
|
164
|
+
* boundary, outside the current alien-signals flush: to the handler when one is set (see
|
|
165
|
+
* {@link handOverIsolatedException}), otherwise by a queued microtask rethrow.
|
|
166
|
+
*/
|
|
167
|
+
function reportIsolatedException(error) {
|
|
168
|
+
if (isolatedErrorHandler !== null) {
|
|
169
|
+
handOverIsolatedException(error, false);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
queueMicrotask(() => {
|
|
173
|
+
throw error;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Exception objects a subscription's tracked read threw that are queued for reporting and not reported yet.
|
|
178
|
+
* One failing Property is re-read by each of its subscriptions and by every dependent's, and each read
|
|
179
|
+
* rethrows the one cached exception object; it is reported once per synchronous turn, not once per read.
|
|
180
|
+
* With a handler set the turn is the hand-over pass: an exception handed over stays here until the pass ends
|
|
181
|
+
* (see {@link readExceptionsHandedOver}).
|
|
182
|
+
*/
|
|
183
|
+
const queuedReadExceptions = /* @__PURE__ */ new Set();
|
|
184
|
+
function reportTrackedReadException(error) {
|
|
185
|
+
if ((typeof error !== "object" || error === null) && typeof error !== "function") {
|
|
186
|
+
reportIsolatedException(error);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (queuedReadExceptions.has(error)) return;
|
|
190
|
+
if (isolatedErrorHandler !== null) {
|
|
191
|
+
handOverIsolatedException(error, true);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
queuedReadExceptions.add(error);
|
|
195
|
+
queueMicrotask(() => {
|
|
196
|
+
queuedReadExceptions.delete(error);
|
|
197
|
+
throw error;
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Invokes `listener(value)` with no active alien subscriber and no open callback (see `callbackScope`), so
|
|
202
|
+
* neither its reads nor a dependency or `emit` callable it retained from a running Method reach into the
|
|
203
|
+
* operation that notified it, restoring both afterward. A synchronous throw is isolated so it cannot escape
|
|
204
|
+
* into the current alien-signals flush (see {@link reportIsolatedException}).
|
|
205
|
+
*/
|
|
206
|
+
function invokeListenerIsolated(listener, value) {
|
|
207
|
+
const previousOwner = callbackScope.owner;
|
|
208
|
+
callbackScope.owner = null;
|
|
209
|
+
const previous = setActiveSub(void 0);
|
|
210
|
+
try {
|
|
211
|
+
listener(value);
|
|
212
|
+
} catch (error) {
|
|
213
|
+
reportIsolatedException(error);
|
|
214
|
+
} finally {
|
|
215
|
+
callbackScope.owner = previousOwner;
|
|
216
|
+
setActiveSub(previous);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** Runs `read` with no active alien subscriber, so whatever it reads is not tracked by the caller. */
|
|
220
|
+
function readUntracked(read) {
|
|
221
|
+
const previous = setActiveSub(void 0);
|
|
222
|
+
try {
|
|
223
|
+
return read();
|
|
224
|
+
} finally {
|
|
225
|
+
setActiveSub(previous);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Whether `error` is an engine's call-stack exhaustion. Engines give it no dedicated type: V8,
|
|
230
|
+
* JavaScriptCore, Hermes and QuickJS-ng throw a `RangeError` ("Maximum call stack size exceeded"),
|
|
231
|
+
* SpiderMonkey an `InternalError` ("too much recursion"), QuickJS and XS a "stack overflow". The message is
|
|
232
|
+
* the only signal, so an ordinary `RangeError` (an invalid date, array length, ...) never matches.
|
|
233
|
+
*/
|
|
234
|
+
function isEngineStackOverflow(error) {
|
|
235
|
+
try {
|
|
236
|
+
return (error instanceof RangeError || error instanceof Error && error.name === "InternalError") && /call stack|stack overflow|too much recursion/i.test(error.message);
|
|
237
|
+
} catch {
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Whether `error` is unwinding a runaway emit loop: the emit re-entrancy guard's
|
|
243
|
+
* {@link WidgetSystemRuntimeReentrancyError}, or an engine stack overflow. These are the exceptions event
|
|
244
|
+
* listener isolation does not swallow. Isolating one would make the emit retry its remaining listeners,
|
|
245
|
+
* each of which runs into the same failure again — at every nesting level, which is exponential work.
|
|
246
|
+
*/
|
|
247
|
+
function isEmitLoopError(error) {
|
|
248
|
+
return error instanceof WidgetSystemRuntimeReentrancyError || isEngineStackOverflow(error);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* {@link invokeListenerIsolated} for a synchronous semantic event listener and its argument tuple: no
|
|
252
|
+
* reads leak into an enclosing Property/effect, and a throw is reported outside the emit instead of
|
|
253
|
+
* aborting the emitting Method and the remaining listeners — unless it is unwinding a runaway emit loop
|
|
254
|
+
* ({@link isEmitLoopError}), which is rethrown. Event delivery never runs inside an alien-signals flush, so
|
|
255
|
+
* the rethrow cannot strand another subscriber's queued notification.
|
|
256
|
+
*/
|
|
257
|
+
function invokeEventListenerIsolated(listener, args) {
|
|
258
|
+
const previousOwner = callbackScope.owner;
|
|
259
|
+
callbackScope.owner = null;
|
|
260
|
+
const previous = setActiveSub(void 0);
|
|
261
|
+
try {
|
|
262
|
+
listener(...args);
|
|
263
|
+
} catch (error) {
|
|
264
|
+
if (isEmitLoopError(error)) throw error;
|
|
265
|
+
reportIsolatedException(error);
|
|
266
|
+
} finally {
|
|
267
|
+
callbackScope.owner = previousOwner;
|
|
268
|
+
setActiveSub(previous);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Nesting depth of the calls that can drive an `alien-signals` evaluation/flush and therefore have to be
|
|
273
|
+
* back out of the reactive graph before a deferred propagation is safe to release: `RuntimeState`'s
|
|
274
|
+
* `attemptSet`, `RuntimeMethod`'s `invoke`, `resetState` and the tracked read of a Property's result
|
|
275
|
+
* computed. Purely local bookkeeping for {@link writeDeferringFlush}, not a semantic boundary of its own.
|
|
276
|
+
*/
|
|
277
|
+
let operationDepth = 0;
|
|
278
|
+
/**
|
|
279
|
+
* Whether the caller is outside everything of the Runtime and of the reactive graph: no Runtime operation in
|
|
280
|
+
* progress, no open alien batch and no active subscriber. Only then does a read or a no-op write of a signal
|
|
281
|
+
* have no side effect anyone could observe.
|
|
282
|
+
*/
|
|
283
|
+
function isRuntimeIdle() {
|
|
284
|
+
return operationDepth === 0 && getBatchDepth() === 0 && getActiveSub() === void 0;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* alien-signals' batch depth when the outermost {@link runRuntimeOperation} frame was entered. Every batch
|
|
288
|
+
* level opened inside that operation — a `RuntimeMethod` invocation's own batch, `resetState`'s batch and
|
|
289
|
+
* every level {@link writeDeferringFlush} opened — is above it.
|
|
290
|
+
*/
|
|
291
|
+
let entryBatchDepth = 0;
|
|
292
|
+
/**
|
|
293
|
+
* Listener deliveries requested while a Runtime operation was in progress (Property inspection completions,
|
|
294
|
+
* and the isolated exceptions queued for the handler, see {@link handOverIsolatedException}), in request
|
|
295
|
+
* order, each with its generation (see {@link MAX_DELIVERY_GENERATIONS}).
|
|
296
|
+
*
|
|
297
|
+
* A listener that runs while a Property evaluation, an alien-signals dirty check or a flush is in progress and
|
|
298
|
+
* reads or writes the Runtime re-enters alien-signals@3.2.1 there, which it does not support: `checkDirty` has
|
|
299
|
+
* no branch for a computed whose getter is running (`RecursedCheck`), treats it as clean and clears the
|
|
300
|
+
* `Pending` flag of every reader between it and the read, which then stay clean with a stale value; a write
|
|
301
|
+
* flushes a second time inside the first and can re-enter the running getter, whose older result then
|
|
302
|
+
* overwrites the newer one; and an effect that is running is not queued again by a write its own run caused
|
|
303
|
+
* (issue #198). Queued deliveries run once the outermost operation has left, after its deferred propagations
|
|
304
|
+
* were released: nothing is evaluating, checking or flushing then.
|
|
305
|
+
*/
|
|
306
|
+
let queuedDeliveries = [];
|
|
307
|
+
let queuedGenerations = [];
|
|
308
|
+
/**
|
|
309
|
+
* Whether the host call in progress has anything to finish when its outermost operation leaves (see
|
|
310
|
+
* {@link finishHostCall}): deliveries in `queuedDeliveries`, or a subscription that counted a notification in it
|
|
311
|
+
* (see {@link hostCalls}). One flag for both, so that the check every outermost operation makes when it leaves is
|
|
312
|
+
* one load and one test while there is neither, the common case.
|
|
313
|
+
*/
|
|
314
|
+
let hostCallWork = false;
|
|
315
|
+
/** Whether {@link deliverQueued} is running: operations its listeners start queue their deliveries behind. */
|
|
316
|
+
let delivering = false;
|
|
317
|
+
/** The generation of the delivery running now; `0` outside {@link deliverQueued}. */
|
|
318
|
+
let deliveryGeneration = 0;
|
|
319
|
+
/**
|
|
320
|
+
* How many generations of deliveries one outermost operation runs. A delivery queued by an operation that a
|
|
321
|
+
* delivered listener started is one generation later than that listener's. A listener that keeps changing what
|
|
322
|
+
* it observes (it writes, on every completion, a State its own Property depends on) would otherwise make the
|
|
323
|
+
* outermost call loop until the values stop changing, or forever. Beyond the limit the remaining deliveries
|
|
324
|
+
* are dropped and a `RangeError` is reported through the isolated-exception channel (not a coded error: it
|
|
325
|
+
* reports a listener bug, like any exception an isolated listener throws). The reports queued for the handler
|
|
326
|
+
* are not dropped with the deliveries (see {@link handOverAtDeliveryLimit}); a report that the handler's own
|
|
327
|
+
* calls cause stays in the generation of the report the handler was handling, because the handler's feedback
|
|
328
|
+
* has its own bounds ({@link MAX_HANDLER_CAUSED_DEPTH}, {@link MAX_HANDLER_CAUSED_REPORTS}). Internal, not
|
|
329
|
+
* configurable.
|
|
330
|
+
*/
|
|
331
|
+
const MAX_DELIVERY_GENERATIONS = 100;
|
|
332
|
+
/**
|
|
333
|
+
* Numbers the host's calls into the Runtime in which a subscription was notified. A subscription compares it with
|
|
334
|
+
* the number it last counted in to restart its count of notifications (see {@link MAX_NOTIFICATIONS_PER_CALL}).
|
|
335
|
+
* Realm-wide, like {@link operationDepth}.
|
|
336
|
+
*
|
|
337
|
+
* It is advanced when such a call ends, not when a call starts, so that an operation in which nothing is
|
|
338
|
+
* notified (a cached read, a write nobody observes) executes nothing for it: the first notification a
|
|
339
|
+
* subscription counts in a call sets {@link hostCallWork}, and the outermost operation's exit, which tests that
|
|
340
|
+
* flag already, advances the number in {@link finishHostCall}. A call ends when its outermost operation leaves
|
|
341
|
+
* outside the queued-delivery drain, after the drain: the operations that the listeners of a queued delivery
|
|
342
|
+
* start are outermost too, but they run before the host's call returns, on its behalf, so they keep its number.
|
|
343
|
+
* A hand-over pass of the isolated-error handler that starts while no operation is in progress is a call of its
|
|
344
|
+
* own and advances it too (see {@link handOverIsolatedException}); one that runs at the end of an operation
|
|
345
|
+
* belongs to that call.
|
|
346
|
+
* It starts at `1`, above every value a subscription stores before its first count (see
|
|
347
|
+
* {@link createTrackedSubscription}).
|
|
348
|
+
*/
|
|
349
|
+
let hostCalls = 1;
|
|
350
|
+
/**
|
|
351
|
+
* How many times one subscription's listener is notified within one host call into the Runtime, the deliveries
|
|
352
|
+
* that call queues included (see {@link hostCalls}). Listeners that keep changing what they observe (a
|
|
353
|
+
* self-normaliser that writes a fresh copy while something else reads the member, two listeners mirroring each
|
|
354
|
+
* other's objects, a diverging pair) would otherwise make that call loop forever: the loop runs inside
|
|
355
|
+
* alien-signals' flush, iteratively, so nothing else bounds it. Beyond the limit the listener is not called again
|
|
356
|
+
* until the call returns, and one `RangeError` naming what the subscription observes is reported through the
|
|
357
|
+
* isolated-exception channel (not a coded error: it reports a listener bug, like any exception an isolated
|
|
358
|
+
* listener throws). High enough that a converging cascade of listeners does not reach it (it takes thousands of
|
|
359
|
+
* listener steps in one call), low enough that a loop reaches it within milliseconds. Counted separately from
|
|
360
|
+
* {@link MAX_DELIVERY_GENERATIONS}: an inspection delivery round is not a subscriber notification. It must stay
|
|
361
|
+
* well above it, because a loop that runs through delivery rounds notifies a subscriber once per round, and
|
|
362
|
+
* stopping and reporting that loop is the delivery bound's job. Internal, not configurable; exported for the tests only.
|
|
363
|
+
*/
|
|
364
|
+
const MAX_NOTIFICATIONS_PER_CALL = 1e4;
|
|
365
|
+
/** Reports that a subscription reached {@link MAX_NOTIFICATIONS_PER_CALL}; `observed` names what it observes. */
|
|
366
|
+
function reportNotificationLimit(observed) {
|
|
367
|
+
reportIsolatedException(/* @__PURE__ */ new RangeError(`The subscription to ${observed} was notified ${MAX_NOTIFICATIONS_PER_CALL} times within one call into the Runtime, so its listener is not called again until that call returns. The usual cause is listeners that keep writing what one another observe.`));
|
|
368
|
+
}
|
|
369
|
+
function describeSubscription(subject, owner) {
|
|
370
|
+
if (typeof owner === "string") return `${subject} "${owner}"`;
|
|
371
|
+
return `${subject} "${"key" in owner ? owner.key : owner.name}" of widget "${owner.widgetId}"`;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Closes every batch level opened inside the outermost Runtime operation, letting alien-signals flush the
|
|
375
|
+
* notifications it already queued.
|
|
376
|
+
*
|
|
377
|
+
* In normal operation the only levels still open here are the ones {@link writeDeferringFlush} opened, the ones
|
|
378
|
+
* nested Method invocations left open ({@link endBatchDeferringFlush}) and the ones nested writes opened
|
|
379
|
+
* ({@link runRuntimeWrite}): every other level is closed by its own `endBatch()` in a `finally`.
|
|
380
|
+
* But that `finally` cannot be relied
|
|
381
|
+
* on when runaway recursion (a valid Method <-> Method cycle) exhausts the engine's stack: the deepest
|
|
382
|
+
* frames' `endBatch()` calls themselves overflow and never decrement. Draining to the depth recorded on
|
|
383
|
+
* entry, rather than counting the levels this module opened, closes those leaked levels too, so a
|
|
384
|
+
* `RangeError` can never leave the realm permanently batched.
|
|
385
|
+
*
|
|
386
|
+
* The loop condition is re-tested after every `endBatch()`: that flush can run an effect whose Property
|
|
387
|
+
* recompute commits its own diagnostic snapshot, which opens a fresh level this same drain must then close.
|
|
388
|
+
* Runtime subscriptions never throw out of a flush (listener and tracked-read exceptions are isolated),
|
|
389
|
+
* but any other alien effect sharing the realm can; such a throw must not leave alien-signals permanently
|
|
390
|
+
* batched (every later flush in the realm would be silently suspended), so the remaining levels are
|
|
391
|
+
* closed before the throw is rethrown.
|
|
392
|
+
*/
|
|
393
|
+
function releaseBatches() {
|
|
394
|
+
while (getBatchDepth() > entryBatchDepth) try {
|
|
395
|
+
endBatch();
|
|
396
|
+
} catch (error) {
|
|
397
|
+
releaseBatches();
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Tracks one nesting level of the calls that can drive an evaluation, and closes every batch level opened
|
|
403
|
+
* inside it (see {@link releaseBatches}) once the outermost level is leaving.
|
|
404
|
+
*
|
|
405
|
+
* The release runs while the depth is still `1`, so a listener that the release's own flush invokes and
|
|
406
|
+
* that re-enters the Runtime cannot re-enter the drain loop. The decrement is unconditional: a throw
|
|
407
|
+
* inside the release's flush must not leave the depth pinned above `0`, or every later call would look
|
|
408
|
+
* nested and no release would ever run again. Both depth updates are plain expressions, never calls, so
|
|
409
|
+
* they still run when the stack is exhausted.
|
|
410
|
+
*
|
|
411
|
+
* `fn` receives `argument`, so a hot path passes a function that already exists together with its
|
|
412
|
+
* argument instead of allocating a closure per call.
|
|
413
|
+
*
|
|
414
|
+
* Reads, Method invocations and subscriptions use this entry; State writes use {@link runRuntimeWrite}, which
|
|
415
|
+
* differs only on a nested entry, so that this one executes nothing for a feature only writes need.
|
|
416
|
+
*/
|
|
417
|
+
function runRuntimeOperation(fn, argument) {
|
|
418
|
+
if (operationDepth === 0) entryBatchDepth = getBatchDepth();
|
|
419
|
+
++operationDepth;
|
|
420
|
+
try {
|
|
421
|
+
return fn(argument);
|
|
422
|
+
} finally {
|
|
423
|
+
if (operationDepth === 1) try {
|
|
424
|
+
releaseBatches();
|
|
425
|
+
} finally {
|
|
426
|
+
--operationDepth;
|
|
427
|
+
if (hostCallWork && !delivering) finishHostCall();
|
|
428
|
+
}
|
|
429
|
+
else --operationDepth;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* {@link runRuntimeOperation} for an operation that writes State (`RuntimeState`'s `attemptSet`, both
|
|
434
|
+
* `resetState()`s). It executes the same statements, except that when it is entered while another operation is
|
|
435
|
+
* in progress (a listener the enclosing operation's flush invokes, say) with no batch level open, it opens one,
|
|
436
|
+
* which the outermost frame's release closes: its writes never flush on their own, like a nested Method
|
|
437
|
+
* invocation's (see {@link endBatchDeferringFlush}). Flushing them there would run the effects they queue inside
|
|
438
|
+
* the flush that is running the listener's own effect, and alien-signals does not queue an effect again for a
|
|
439
|
+
* write made while that effect runs, so a subscriber whose value the write changes could miss it.
|
|
440
|
+
*
|
|
441
|
+
* A separate entry rather than a parameter of {@link runRuntimeOperation}, so that a read, outermost or nested,
|
|
442
|
+
* executes nothing for this; and a copy of its body rather than a call to it, so that an outermost write executes
|
|
443
|
+
* exactly what it did before. Keep the two bodies identical apart from the nested entry.
|
|
444
|
+
*/
|
|
445
|
+
function runRuntimeWrite(fn, argument) {
|
|
446
|
+
if (operationDepth !== 0) {
|
|
447
|
+
if (getBatchDepth() === 0) startBatch();
|
|
448
|
+
} else entryBatchDepth = getBatchDepth();
|
|
449
|
+
++operationDepth;
|
|
450
|
+
try {
|
|
451
|
+
return fn(argument);
|
|
452
|
+
} finally {
|
|
453
|
+
if (operationDepth === 1) try {
|
|
454
|
+
releaseBatches();
|
|
455
|
+
} finally {
|
|
456
|
+
--operationDepth;
|
|
457
|
+
if (hostCallWork && !delivering) finishHostCall();
|
|
458
|
+
}
|
|
459
|
+
else --operationDepth;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Runs `deliver` now when no Runtime operation is in progress, otherwise once the outermost one has left
|
|
464
|
+
* (still synchronously, before it returns to its caller), after the deliveries requested before it. `deliver`
|
|
465
|
+
* must not throw: it invokes listeners through {@link invokeListenerIsolated}.
|
|
466
|
+
*/
|
|
467
|
+
function deliverWhenIdle(deliver) {
|
|
468
|
+
if (operationDepth === 0 && !delivering) {
|
|
469
|
+
deliver();
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
queuedDeliveries.push(deliver);
|
|
473
|
+
queuedGenerations.push(deliveryGeneration + 1);
|
|
474
|
+
hostCallWork = true;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Finishes the host call whose outermost operation is leaving: runs the deliveries it queued (see
|
|
478
|
+
* {@link deliverQueued}), then advances {@link hostCalls}, so the notifications of those deliveries count in this
|
|
479
|
+
* call and the next call starts every count from zero. The advance is in a `finally` of plain statements, so it
|
|
480
|
+
* happens even when the drain throws (only an exhausted engine stack can make it throw).
|
|
481
|
+
*/
|
|
482
|
+
function finishHostCall() {
|
|
483
|
+
try {
|
|
484
|
+
if (queuedDeliveries.length > 0) deliverQueued();
|
|
485
|
+
} finally {
|
|
486
|
+
hostCallWork = false;
|
|
487
|
+
++hostCalls;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* The causal depth of the report the handler is handling now, or `-1` while it is not running. Every hand-over
|
|
492
|
+
* happens inside {@link deliverQueued}, so the handler is never re-entered: one value is enough. A report
|
|
493
|
+
* isolated while the handler runs was caused by its handling of this report, one level deeper.
|
|
494
|
+
*/
|
|
495
|
+
let handlingDepth = -1;
|
|
496
|
+
/** Whether the running pass of {@link deliverQueued} handed a report over: its end then resets the state below. */
|
|
497
|
+
let handOverPassDirty = false;
|
|
498
|
+
/** Read exceptions handed over in the running pass: they stay in {@link queuedReadExceptions} until it ends. */
|
|
499
|
+
let readExceptionsHandedOver = [];
|
|
500
|
+
/** Reports caused by the handler's handling (depth above `0`) handed over in the running pass. */
|
|
501
|
+
let handlerCausedReports = 0;
|
|
502
|
+
/** Whether the running pass already handed the handler the `RangeError` of each bound below. */
|
|
503
|
+
let depthBoundReported = false;
|
|
504
|
+
let totalBoundReported = false;
|
|
505
|
+
/**
|
|
506
|
+
* How many reports caused by the handler's handling are handed over within one pass, whatever their depth. The
|
|
507
|
+
* depth bound alone does not stop a handler whose handling of each report causes two new ones: the chains stay
|
|
508
|
+
* short of the limit while their number doubles at every level. Far above anything a converging handler
|
|
509
|
+
* causes. Beyond it the handler is handed one `RangeError`, and the reports its handling causes later in that
|
|
510
|
+
* pass are rethrown in a microtask. Internal, not configurable; exported for the tests only.
|
|
511
|
+
*/
|
|
512
|
+
const MAX_HANDLER_CAUSED_REPORTS = 1e4;
|
|
513
|
+
/**
|
|
514
|
+
* Runs every queued delivery in order, including those queued by the operations the delivered listeners start
|
|
515
|
+
* (each of those operations is outermost while it runs, so it releases its own deferred propagations), up to
|
|
516
|
+
* {@link MAX_DELIVERY_GENERATIONS} generations. This is also the one hand-over pass of the isolated-error handler
|
|
517
|
+
* (see {@link handOverIsolatedException}).
|
|
518
|
+
*/
|
|
519
|
+
function deliverQueued() {
|
|
520
|
+
delivering = true;
|
|
521
|
+
try {
|
|
522
|
+
for (let index = 0; index < queuedDeliveries.length; index++) {
|
|
523
|
+
deliveryGeneration = queuedGenerations[index];
|
|
524
|
+
if (deliveryGeneration > MAX_DELIVERY_GENERATIONS) {
|
|
525
|
+
handOverAtDeliveryLimit(index);
|
|
526
|
+
break;
|
|
527
|
+
}
|
|
528
|
+
queuedDeliveries[index]();
|
|
529
|
+
}
|
|
530
|
+
} finally {
|
|
531
|
+
queuedDeliveries = [];
|
|
532
|
+
queuedGenerations = [];
|
|
533
|
+
deliveryGeneration = 0;
|
|
534
|
+
delivering = false;
|
|
535
|
+
if (handOverPassDirty) endHandOverPass();
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
function endHandOverPass() {
|
|
539
|
+
handOverPassDirty = false;
|
|
540
|
+
for (const error of readExceptionsHandedOver) queuedReadExceptions.delete(error);
|
|
541
|
+
readExceptionsHandedOver = [];
|
|
542
|
+
handlerCausedReports = 0;
|
|
543
|
+
depthBoundReported = false;
|
|
544
|
+
totalBoundReported = false;
|
|
545
|
+
}
|
|
546
|
+
/** The queued delivery of each report, so the delivery bound can tell reports apart from inspection deliveries. */
|
|
547
|
+
const queuedReports = /* @__PURE__ */ new WeakMap();
|
|
548
|
+
/**
|
|
549
|
+
* Ends a delivery run that reached {@link MAX_DELIVERY_GENERATIONS} at `from`. The inspection deliveries from
|
|
550
|
+
* there on are dropped; the reports among them are still handed over, in order, and then the `RangeError` that
|
|
551
|
+
* reports the bound. An exception isolated by what the handler does meanwhile is not handed to it in this call
|
|
552
|
+
* (that could go on forever): it is rethrown in a microtask, like an exception the handler throws.
|
|
553
|
+
*/
|
|
554
|
+
function handOverAtDeliveryLimit(from) {
|
|
555
|
+
const end = queuedDeliveries.length;
|
|
556
|
+
for (let index = from; index < end; index++) {
|
|
557
|
+
const report = queuedReports.get(queuedDeliveries[index]);
|
|
558
|
+
if (report !== void 0) handOverQueuedReport(report);
|
|
559
|
+
}
|
|
560
|
+
const handler = isolatedErrorHandler;
|
|
561
|
+
const limitError = /* @__PURE__ */ new RangeError(`Inspection listeners kept changing what they observe for more than ${MAX_DELIVERY_GENERATIONS} rounds within one Runtime call; the remaining inspection notifications of that call were dropped.`);
|
|
562
|
+
if (handler === null) queueMicrotask(() => {
|
|
563
|
+
throw limitError;
|
|
564
|
+
});
|
|
565
|
+
else callIsolatedErrorHandler(handler, limitError, 0);
|
|
566
|
+
for (let index = end; index < queuedDeliveries.length; index++) {
|
|
567
|
+
const report = queuedReports.get(queuedDeliveries[index]);
|
|
568
|
+
if (report !== void 0) fallBack(report);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Queues `error` for the handler behind the deliveries already waiting, exactly like {@link deliverWhenIdle},
|
|
573
|
+
* and starts the pass at once when no Runtime operation is in progress and none is running: otherwise the
|
|
574
|
+
* outermost operation's existing exit check, or the running pass, hands it over.
|
|
575
|
+
*/
|
|
576
|
+
function handOverIsolatedException(error, readException) {
|
|
577
|
+
const depth = handlingDepth < 0 ? 0 : handlingDepth + 1;
|
|
578
|
+
if (readException) queuedReadExceptions.add(error);
|
|
579
|
+
const report = {
|
|
580
|
+
error,
|
|
581
|
+
readException,
|
|
582
|
+
depth
|
|
583
|
+
};
|
|
584
|
+
const deliver = () => handOverQueuedReport(report);
|
|
585
|
+
queuedReports.set(deliver, report);
|
|
586
|
+
queuedDeliveries.push(deliver);
|
|
587
|
+
queuedGenerations.push(depth === 0 ? deliveryGeneration + 1 : deliveryGeneration);
|
|
588
|
+
hostCallWork = true;
|
|
589
|
+
if (operationDepth === 0 && !delivering) finishHostCall();
|
|
590
|
+
}
|
|
591
|
+
/** Hands a queued report to the handler that is set now, or rethrows it in a microtask when none is. */
|
|
592
|
+
function handOverQueuedReport(report) {
|
|
593
|
+
const handler = isolatedErrorHandler;
|
|
594
|
+
if (handler === null) {
|
|
595
|
+
fallBack(report);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
handOverPassDirty = true;
|
|
599
|
+
if (report.readException) readExceptionsHandedOver.push(report.error);
|
|
600
|
+
const depth = report.depth;
|
|
601
|
+
if (depth > 100) {
|
|
602
|
+
if (!depthBoundReported) {
|
|
603
|
+
depthBoundReported = true;
|
|
604
|
+
callIsolatedErrorHandler(handler, /* @__PURE__ */ new RangeError(`The isolated-error handler caused a new isolated exception while handling the previous one 100 times in a row within one Runtime call; the exceptions further down that chain are rethrown in a microtask instead of being handed to it.`), depth);
|
|
605
|
+
}
|
|
606
|
+
fallBack(report);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (depth > 0 && ++handlerCausedReports > 1e4) {
|
|
610
|
+
if (!totalBoundReported) {
|
|
611
|
+
totalBoundReported = true;
|
|
612
|
+
callIsolatedErrorHandler(handler, /* @__PURE__ */ new RangeError(`The isolated-error handler caused more than ${MAX_HANDLER_CAUSED_REPORTS} new isolated exceptions while handling others within one Runtime call; the ones it causes later in that call are rethrown in a microtask instead of being handed to it.`), depth);
|
|
613
|
+
}
|
|
614
|
+
fallBack(report);
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
callIsolatedErrorHandler(handler, report.error, depth);
|
|
618
|
+
}
|
|
619
|
+
/** Rethrows a report the handler does not take in a microtask; it leaves the de-duplication set when the pass ends. */
|
|
620
|
+
function fallBack(report) {
|
|
621
|
+
handOverPassDirty = true;
|
|
622
|
+
if (report.readException) readExceptionsHandedOver.push(report.error);
|
|
623
|
+
rethrowInMicrotask(report.error);
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Calls the handler with no active alien subscriber (see {@link invokeListenerIsolated}), recording the depth of
|
|
627
|
+
* the report it handles; its own exception goes to a microtask rethrow, never back to it.
|
|
628
|
+
*/
|
|
629
|
+
function callIsolatedErrorHandler(handler, error, depth) {
|
|
630
|
+
const previous = setActiveSub(void 0);
|
|
631
|
+
handlingDepth = depth;
|
|
632
|
+
try {
|
|
633
|
+
handler(error);
|
|
634
|
+
} catch (handlerError) {
|
|
635
|
+
rethrowInMicrotask(handlerError);
|
|
636
|
+
} finally {
|
|
637
|
+
handlingDepth = -1;
|
|
638
|
+
setActiveSub(previous);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* The fallback channel while a handler is set. It never throws: in a host without `queueMicrotask` the report is
|
|
643
|
+
* dropped, and the pass, the host's call and every other report go on as if it had been queued.
|
|
644
|
+
*/
|
|
645
|
+
function rethrowInMicrotask(error) {
|
|
646
|
+
try {
|
|
647
|
+
queueMicrotask(() => {
|
|
648
|
+
throw error;
|
|
649
|
+
});
|
|
650
|
+
} catch {}
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Performs a signal write whose propagation must not be flushed while a computed may still be
|
|
654
|
+
* mid-evaluation, by holding an alien batch open until the outermost {@link runRuntimeOperation} frame on
|
|
655
|
+
* the stack is leaving — i.e. until nothing that could still be evaluating remains.
|
|
656
|
+
*
|
|
657
|
+
* Why this is required in pinned alien-signals@3.2.1 (`esm/index.mjs` / `esm/system.mjs`):
|
|
658
|
+
*
|
|
659
|
+
* - `signalOper` ends a changed write with `propagate(subs, ...)` followed by `if (!batchDepth) flush()`.
|
|
660
|
+
* A write performed from inside a computed's own evaluator therefore starts a *nested* flush that runs
|
|
661
|
+
* the effects the outer propagation had already queued — while the computed that queued them is still
|
|
662
|
+
* mid-`updateComputed`.
|
|
663
|
+
* - `updateComputed` sets `c.flags = 1 | 4` (`Mutable | RecursedCheck`) and only assigns
|
|
664
|
+
* `c.value = c.getter(...)` after the getter returns, so during that window the computed carries
|
|
665
|
+
* neither `Dirty` (16) nor `Pending` (32) and still holds its previous value.
|
|
666
|
+
* - `checkDirty` has no `RecursedCheck` branch: a queued effect whose dependency chain passes through
|
|
667
|
+
* that computed hits none of its `(1 | 16)` / `(1 | 32)` cases, concludes `dirty === false`, and then
|
|
668
|
+
* clears its own intermediate's `Pending` flag (`sub.flags &= ~32`). The intermediate is now marked
|
|
669
|
+
* clean while still holding a stale cached value, so the later `shallowPropagate` — which only
|
|
670
|
+
* upgrades subscribers that are still `Pending` — skips it for good: the effect never runs again and
|
|
671
|
+
* even an untracked `.get()` returns the stale cache.
|
|
672
|
+
*
|
|
673
|
+
* Keeping `batchDepth > 0` for the write removes the nested flush entirely: `propagate` still marks and
|
|
674
|
+
* queues every watcher through alien-signals' own bookkeeping, and the queue is drained later — by the
|
|
675
|
+
* flush that is already running (it re-reads the shared queue length) or by
|
|
676
|
+
* {@link runRuntimeOperation}'s release. Nothing here re-implements propagation, ordering or dedupe.
|
|
677
|
+
*
|
|
678
|
+
* The write itself is unconditional and immediate, so a snapshot is committed exactly where it was
|
|
679
|
+
* before: `pendingValue` is written synchronously and every later read commits it (`signalOper`'s read
|
|
680
|
+
* path runs `updateSignal` when the signal is `Dirty`), which keeps "the snapshot is committed by the
|
|
681
|
+
* time the operation's `ExecutionResult` is observable" true. Only the *notification* moves — never past
|
|
682
|
+
* the end of the operation that produced it.
|
|
683
|
+
*
|
|
684
|
+
* One consequence of using an alien batch as the deferral mechanism, rather than a normative rule about
|
|
685
|
+
* Runtime operations: while a level is open, alien-signals coalesces as it does inside any batch, so two
|
|
686
|
+
* writes to the *same* signal before the release notify its subscribers once, with the final value. This
|
|
687
|
+
* is not a new Runtime semantic — it is the ordinary behavior of the batching alien-signals already owns,
|
|
688
|
+
* already observable inside `RuntimeMethod.invoke`'s batch. Every actual completed recompute still
|
|
689
|
+
* notifies each of its own subscribers exactly once; alien-signals, not this module, decides which
|
|
690
|
+
* recomputes happen.
|
|
691
|
+
*/
|
|
692
|
+
function writeDeferringFlush(write) {
|
|
693
|
+
if (operationDepth === 0) {
|
|
694
|
+
write();
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
startBatch();
|
|
698
|
+
write();
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Closes a batch level its caller opened inside its own {@link runRuntimeOperation} frame (a
|
|
702
|
+
* `RuntimeMethod` invocation's batch), unless another Runtime operation encloses that frame: the level is
|
|
703
|
+
* then left open, and the outermost frame's release closes it (see {@link releaseBatches}), exactly as it
|
|
704
|
+
* closes the levels {@link writeDeferringFlush} opens.
|
|
705
|
+
*
|
|
706
|
+
* An enclosing operation may be a Property read whose computed is mid-evaluation: a Property may invoke a
|
|
707
|
+
* write-free Method, and when alien-signals' own flush evaluates that Property (an effect's dirty check),
|
|
708
|
+
* the flush runs at batch depth `0`, so the invocation's own batch is the outermost one. A plain `endBatch()`
|
|
709
|
+
* would then reach depth `0` and call `flush()` while the computed is mid-`updateComputed`, with the effects
|
|
710
|
+
* the write queued still waiting — the nested flush {@link writeDeferringFlush} documents, which leaves the
|
|
711
|
+
* Property's other dependents marked clean with stale values and their subscribers unnotified.
|
|
712
|
+
*
|
|
713
|
+
* Leaving the level open does not depend on whether the invocation also committed a changed diagnostic
|
|
714
|
+
* snapshot (whose {@link writeDeferringFlush} level used to be the only thing keeping depth above `0`), so
|
|
715
|
+
* the flush timing of a nested invocation no longer depends on its diagnostics either.
|
|
716
|
+
*/
|
|
717
|
+
function endBatchDeferringFlush() {
|
|
718
|
+
if (operationDepth > 1) return;
|
|
719
|
+
endBatch();
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Creates a Runtime-owned public subscription: an alien `effect()` that tracks `read()`, skips the
|
|
723
|
+
* bootstrap run, and invokes `listener` through {@link invokeListenerIsolated} on every actual
|
|
724
|
+
* subsequent run. Returns an idempotent unsubscribe function registered with the Runtime's disposal
|
|
725
|
+
* bookkeeping.
|
|
726
|
+
*
|
|
727
|
+
* `read()` itself can throw: a Property's tracked result read rethrows its `compute`'s exception (the
|
|
728
|
+
* Property primitive caches that outcome instead of letting it escape the computed). Such a run is
|
|
729
|
+
* isolated like a listener exception — the write that triggered it and every other subscriber are
|
|
730
|
+
* unaffected — and only skips this subscription's notification. The tracked read had already linked the
|
|
731
|
+
* effect to the Property before rethrowing, so the subscription stays live and resumes on the next
|
|
732
|
+
* completed recompute. A bootstrap run that throws is isolated the same way. The exception is reported once
|
|
733
|
+
* per synchronous turn however many subscriptions re-read it (see {@link reportTrackedReadException}).
|
|
734
|
+
*
|
|
735
|
+
* A caller whose `read()` can evaluate Properties (a Property's `subscribe()`) calls this inside a Runtime
|
|
736
|
+
* operation, so that the inspection completions the bootstrap run produces are delivered after the effect's
|
|
737
|
+
* first run has finished, not inside it, where alien-signals would not run the effect again for a write a
|
|
738
|
+
* listener makes (issue #198). The other subscriptions only read signals, and need no operation.
|
|
739
|
+
*
|
|
740
|
+
* Within one host call into the Runtime (see {@link hostCalls}) the listener is called at most
|
|
741
|
+
* {@link MAX_NOTIFICATIONS_PER_CALL} times; `subject` and `owner` name what the subscription observes in the
|
|
742
|
+
* report of the limit, whose text is built only when the limit is reached. A notification adds three comparisons
|
|
743
|
+
* and an increment (and three assignments in the first notification of a call). The subscription stores the two
|
|
744
|
+
* references it is given and one number besides what it stored before: `countedIn` replaces the bootstrap flag
|
|
745
|
+
* (`-1` until the bootstrap run, then the host call the count belongs to; `0` matches no call, since
|
|
746
|
+
* {@link hostCalls} starts at `1`). Nothing is allocated unless the limit is reached.
|
|
747
|
+
*/
|
|
748
|
+
function createTrackedSubscription(context, read, listener, subject, owner) {
|
|
749
|
+
let countedIn = -1;
|
|
750
|
+
let notifications = 0;
|
|
751
|
+
const rawDispose = effect(() => {
|
|
752
|
+
let value;
|
|
753
|
+
try {
|
|
754
|
+
value = read();
|
|
755
|
+
} catch (error) {
|
|
756
|
+
if (countedIn === -1) countedIn = 0;
|
|
757
|
+
reportTrackedReadException(error);
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
if (countedIn === -1) {
|
|
761
|
+
countedIn = 0;
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (operationDepth !== 0) {
|
|
765
|
+
if (countedIn !== hostCalls) {
|
|
766
|
+
countedIn = hostCalls;
|
|
767
|
+
notifications = 0;
|
|
768
|
+
hostCallWork = true;
|
|
769
|
+
}
|
|
770
|
+
if (++notifications > 1e4) {
|
|
771
|
+
if (notifications === 10001) reportNotificationLimit(describeSubscription(subject, owner));
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
invokeListenerIsolated(listener, value);
|
|
776
|
+
});
|
|
777
|
+
return context.registerSubscription(rawDispose);
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* {@link createTrackedSubscription} for the Runtime diagnostics aggregate, whose `read()` re-runs after any commit
|
|
781
|
+
* but whose value changes less often: a run whose value is the one last delivered (initially `initial`) neither
|
|
782
|
+
* calls the listener nor counts towards the limit. A separate function with the same body, so that the other
|
|
783
|
+
* subscriptions store and test nothing for this filter and the aggregate allocates no filter closure. Keep the two
|
|
784
|
+
* bodies identical apart from the filter.
|
|
785
|
+
*/
|
|
786
|
+
function createDistinctTrackedSubscription(context, read, listener, initial) {
|
|
787
|
+
let delivered = initial;
|
|
788
|
+
let countedIn = -1;
|
|
789
|
+
let notifications = 0;
|
|
790
|
+
const rawDispose = effect(() => {
|
|
791
|
+
let value;
|
|
792
|
+
try {
|
|
793
|
+
value = read();
|
|
794
|
+
} catch (error) {
|
|
795
|
+
if (countedIn === -1) countedIn = 0;
|
|
796
|
+
reportTrackedReadException(error);
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
if (countedIn === -1) {
|
|
800
|
+
countedIn = 0;
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (value === delivered) return;
|
|
804
|
+
if (operationDepth !== 0) {
|
|
805
|
+
if (countedIn !== hostCalls) {
|
|
806
|
+
countedIn = hostCalls;
|
|
807
|
+
notifications = 0;
|
|
808
|
+
hostCallWork = true;
|
|
809
|
+
}
|
|
810
|
+
if (++notifications > 1e4) {
|
|
811
|
+
if (notifications === 10001) reportNotificationLimit("the diagnostics of the Runtime");
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
delivered = value;
|
|
816
|
+
invokeListenerIsolated(listener, value);
|
|
817
|
+
});
|
|
818
|
+
return context.registerSubscription(rawDispose);
|
|
819
|
+
}
|
|
820
|
+
//#endregion
|
|
821
|
+
//#region src/runtime/sync.ts
|
|
822
|
+
function assertSyncValue(value, description, name, what) {
|
|
823
|
+
if ((typeof value === "object" && value !== null || typeof value === "function") && "then" in value && typeof value.then === "function") {
|
|
824
|
+
const subject = name === void 0 ? description : `${description} "${name}"'s ${what}`;
|
|
825
|
+
throw new TypeError(`${subject} returned a thenable. The widget-core semantic boundary is synchronous only.`);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Callback-context lifetime guard: a callback's `addDiagnostic` / `hasAnyDiagnostic` belong to the
|
|
830
|
+
* synchronous call that received them. Calling one after that callback returned or threw is an
|
|
831
|
+
* implementation-contract violation (the operation's diagnostics are already final), so it throws.
|
|
832
|
+
*/
|
|
833
|
+
function throwClosedCollector(method) {
|
|
834
|
+
throw new TypeError(`${method} was called after its callback returned. Diagnostics must be reported synchronously while the callback runs.`);
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* The same lifetime guard for a callback's dependency callables (`deps.*`) and `emit` callables. They
|
|
838
|
+
* are valid only while the callback that received them is the innermost running callback (see
|
|
839
|
+
* `callbackScope` in `./context`): a call after it returned or threw, or from a listener or another
|
|
840
|
+
* callback running inside it, is an implementation-contract violation and performs nothing.
|
|
841
|
+
*/
|
|
842
|
+
function throwClosedCallbackMember(member) {
|
|
843
|
+
throw new TypeError(`${member === "deps" ? "A dependency" : "An emit"} callable was called outside the callback that received it. Dependency and emit callables must be used synchronously while that callback runs, not after it returned and not from a listener or another callback running inside it.`);
|
|
844
|
+
}
|
|
845
|
+
function createEventPrimitive(context) {
|
|
846
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
847
|
+
let inspectionListeners = null;
|
|
848
|
+
function publishInspectionOccurrence(args) {
|
|
849
|
+
if (inspectionListeners === null) return;
|
|
850
|
+
const snapshot = inspectionListeners.slice();
|
|
851
|
+
for (const { listener } of snapshot) invokeListenerIsolated(listener, args);
|
|
852
|
+
}
|
|
853
|
+
return {
|
|
854
|
+
public: Object.freeze({ subscribe(listener) {
|
|
855
|
+
context.assertActive();
|
|
856
|
+
const entry = { listener };
|
|
857
|
+
listeners.add(entry);
|
|
858
|
+
return context.registerSubscription(() => listeners.delete(entry));
|
|
859
|
+
} }),
|
|
860
|
+
emit(...args) {
|
|
861
|
+
context.assertActive();
|
|
862
|
+
const nesting = context.emitNesting;
|
|
863
|
+
if (nesting.unwinding !== null) throw nesting.unwinding;
|
|
864
|
+
if (nesting.depth >= 128) throw nesting.unwinding = new WidgetSystemRuntimeReentrancyError(`Event emits nested deeper than 128 levels in one Runtime: an event listener keeps re-invoking a Method that emits.`);
|
|
865
|
+
++nesting.depth;
|
|
866
|
+
try {
|
|
867
|
+
const listenersSnapshot = [...listeners];
|
|
868
|
+
publishInspectionOccurrence(Object.freeze([...args]));
|
|
869
|
+
for (const { listener } of listenersSnapshot) {
|
|
870
|
+
if (nesting.unwinding !== null) throw nesting.unwinding;
|
|
871
|
+
invokeEventListenerIsolated(listener, args);
|
|
872
|
+
}
|
|
873
|
+
if (nesting.unwinding !== null) throw nesting.unwinding;
|
|
874
|
+
} catch (error) {
|
|
875
|
+
nesting.unwinding ??= error;
|
|
876
|
+
throw error;
|
|
877
|
+
} finally {
|
|
878
|
+
if (--nesting.depth === 0) nesting.unwinding = null;
|
|
879
|
+
}
|
|
880
|
+
},
|
|
881
|
+
inspection: { subscribe(listener) {
|
|
882
|
+
const entry = { listener };
|
|
883
|
+
if (inspectionListeners === null) inspectionListeners = [];
|
|
884
|
+
inspectionListeners.push(entry);
|
|
885
|
+
return () => {
|
|
886
|
+
if (inspectionListeners === null) return;
|
|
887
|
+
const index = inspectionListeners.indexOf(entry);
|
|
888
|
+
if (index !== -1) inspectionListeners.splice(index, 1);
|
|
889
|
+
};
|
|
890
|
+
} }
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
/** The renderer-integration emitter (`@deviltea/widget-core/integration`): valid until disposal. */
|
|
894
|
+
function buildEventEmitter(events) {
|
|
895
|
+
const emitter = Object.create(null);
|
|
896
|
+
for (const name of events.keys()) {
|
|
897
|
+
const primitive = events.get(name);
|
|
898
|
+
emitter[name] = (...args) => primitive.emit(...args);
|
|
899
|
+
}
|
|
900
|
+
return Object.freeze(emitter);
|
|
901
|
+
}
|
|
902
|
+
const methodEmitTemplates = /* @__PURE__ */ new WeakMap();
|
|
903
|
+
/** The context members of a Method of a plugin that declares no Events: there is no `emit`. */
|
|
904
|
+
const NO_EMIT_FRAGMENT = Object.freeze({});
|
|
905
|
+
function methodEmitTemplate(pluginType, eventDefinitions) {
|
|
906
|
+
let template = methodEmitTemplates.get(eventDefinitions);
|
|
907
|
+
if (template === void 0) {
|
|
908
|
+
const prototype = Object.create(null);
|
|
909
|
+
for (const name of eventDefinitions.keys()) Object.defineProperty(prototype, name, {
|
|
910
|
+
value: function undeclaredEmit() {
|
|
911
|
+
const owner = callbackScope.owner;
|
|
912
|
+
if (owner === null || owner.method === null) throwClosedCallbackMember("emit");
|
|
913
|
+
if (owner.emits?.includes(name)) throwClosedCallbackMember("emit");
|
|
914
|
+
throw new TypeError(`Widget plugin "${pluginType}": Method "${owner.method}" (widget "${owner.widgetId}") emitted Event "${name}" without declaring it. Add "${name}" to the Method's "emits". This is a plugin implementation bug.`);
|
|
915
|
+
},
|
|
916
|
+
writable: false,
|
|
917
|
+
configurable: false
|
|
918
|
+
});
|
|
919
|
+
Object.freeze(prototype);
|
|
920
|
+
template = {
|
|
921
|
+
prototype,
|
|
922
|
+
fragment: Object.freeze({ emit: Object.freeze(Object.create(prototype)) })
|
|
923
|
+
};
|
|
924
|
+
methodEmitTemplates.set(eventDefinitions, template);
|
|
925
|
+
}
|
|
926
|
+
return template;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* The `emit`-related members of one Method's `execute` context. A Method of a plugin without Events has
|
|
930
|
+
* none; a Method that declares no `emits` receives the plugin's shared empty `emit`; a Method that declares
|
|
931
|
+
* some receives its own `emit`, holding only the declared Events. Each of its callables requires the owner
|
|
932
|
+
* of this very Method to be the innermost running callback (like a dependency callable), so an `emit`
|
|
933
|
+
* retained past its callback, reached from a Property `compute`, or used while a different Method of the
|
|
934
|
+
* same widget runs, throws without delivering. An Event the Method did not declare is not an own member:
|
|
935
|
+
* calling it throws a `TypeError` naming the Method before anything is delivered.
|
|
936
|
+
*/
|
|
937
|
+
function createMethodEmitFragment(context, owner, pluginType, eventDefinitions, events, emits) {
|
|
938
|
+
if (eventDefinitions === null || events === null) return NO_EMIT_FRAGMENT;
|
|
939
|
+
const template = methodEmitTemplate(pluginType, eventDefinitions);
|
|
940
|
+
if (emits === void 0 || emits.length === 0) return template.fragment;
|
|
941
|
+
const emitter = Object.create(template.prototype);
|
|
942
|
+
for (const name of emits) {
|
|
943
|
+
const primitive = events.get(name);
|
|
944
|
+
Object.defineProperty(emitter, name, {
|
|
945
|
+
value: (...args) => {
|
|
946
|
+
context.assertActive();
|
|
947
|
+
if (callbackScope.owner !== owner) throwClosedCallbackMember("emit");
|
|
948
|
+
primitive.emit(...args);
|
|
949
|
+
},
|
|
950
|
+
enumerable: true
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
return Object.freeze({ emit: Object.freeze(emitter) });
|
|
954
|
+
}
|
|
955
|
+
//#endregion
|
|
956
|
+
export { EMPTY_DIAGNOSTICS as C, runOutsideCallbacks as S, WidgetSystemRuntimeReentrancyError as T, setIsolatedErrorHandler as _, throwClosedCallbackMember as a, createCallbackOwner as b, createTrackedSubscription as c, invokeListenerIsolated as d, isEngineStackOverflow as f, runRuntimeWrite as g, runRuntimeOperation as h, assertSyncValue as i, deliverWhenIdle as l, readUntracked as m, createEventPrimitive as n, throwClosedCollector as o, isRuntimeIdle as p, createMethodEmitFragment as r, createDistinctTrackedSubscription as s, buildEventEmitter as t, endBatchDeferringFlush as u, writeDeferringFlush as v, WidgetSystemRuntimeDisposedError as w, createRuntimeContext as x, callbackScope as y };
|