bubus 1.7.3 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +775 -266
  2. package/dist/esm/async_context.js +39 -0
  3. package/dist/esm/async_context.js.map +7 -0
  4. package/dist/esm/base_event.js +825 -0
  5. package/dist/esm/base_event.js.map +7 -0
  6. package/dist/esm/bridge_jsonl.js +150 -0
  7. package/dist/esm/bridge_jsonl.js.map +7 -0
  8. package/dist/esm/bridge_nats.js +88 -0
  9. package/dist/esm/bridge_nats.js.map +7 -0
  10. package/dist/esm/bridge_postgres.js +231 -0
  11. package/dist/esm/bridge_postgres.js.map +7 -0
  12. package/dist/esm/bridge_redis.js +155 -0
  13. package/dist/esm/bridge_redis.js.map +7 -0
  14. package/dist/esm/bridge_sqlite.js +235 -0
  15. package/dist/esm/bridge_sqlite.js.map +7 -0
  16. package/dist/esm/bridges.js +306 -0
  17. package/dist/esm/bridges.js.map +7 -0
  18. package/dist/esm/event_bus.js +1046 -0
  19. package/dist/esm/event_bus.js.map +7 -0
  20. package/dist/esm/event_handler.js +279 -0
  21. package/dist/esm/event_handler.js.map +7 -0
  22. package/dist/esm/event_history.js +172 -0
  23. package/dist/esm/event_history.js.map +7 -0
  24. package/dist/esm/event_result.js +426 -0
  25. package/dist/esm/event_result.js.map +7 -0
  26. package/dist/esm/events_suck.js +39 -0
  27. package/dist/esm/events_suck.js.map +7 -0
  28. package/dist/esm/helpers.js +64 -0
  29. package/dist/esm/helpers.js.map +7 -0
  30. package/dist/esm/index.js +37 -16206
  31. package/dist/esm/index.js.map +4 -4
  32. package/dist/esm/lock_manager.js +323 -0
  33. package/dist/esm/lock_manager.js.map +7 -0
  34. package/dist/esm/logging.js +196 -0
  35. package/dist/esm/logging.js.map +7 -0
  36. package/dist/esm/middlewares.js +1 -0
  37. package/dist/esm/middlewares.js.map +7 -0
  38. package/dist/esm/optional_deps.js +34 -0
  39. package/dist/esm/optional_deps.js.map +7 -0
  40. package/dist/esm/retry.js +237 -0
  41. package/dist/esm/retry.js.map +7 -0
  42. package/dist/esm/timing.js +56 -0
  43. package/dist/esm/timing.js.map +7 -0
  44. package/dist/esm/types.js +84 -0
  45. package/dist/esm/types.js.map +7 -0
  46. package/dist/types/async_context.d.ts +4 -2
  47. package/dist/types/base_event.d.ts +124 -76
  48. package/dist/types/bridge_jsonl.d.ts +26 -0
  49. package/dist/types/bridge_nats.d.ts +20 -0
  50. package/dist/types/bridge_postgres.d.ts +31 -0
  51. package/dist/types/bridge_redis.d.ts +34 -0
  52. package/dist/types/bridge_sqlite.d.ts +30 -0
  53. package/dist/types/bridges.d.ts +49 -0
  54. package/dist/types/event_bus.d.ts +99 -68
  55. package/dist/types/event_handler.d.ts +73 -19
  56. package/dist/types/event_history.d.ts +45 -0
  57. package/dist/types/event_result.d.ts +60 -38
  58. package/dist/types/events_suck.d.ts +40 -0
  59. package/dist/types/helpers.d.ts +1 -0
  60. package/dist/types/index.d.ts +13 -2
  61. package/dist/types/lock_manager.d.ts +33 -31
  62. package/dist/types/logging.d.ts +5 -1
  63. package/dist/types/middlewares.d.ts +13 -0
  64. package/dist/types/optional_deps.d.ts +3 -0
  65. package/dist/types/retry.d.ts +52 -0
  66. package/dist/types/timing.d.ts +3 -0
  67. package/dist/types/types.d.ts +18 -7
  68. package/package.json +32 -11
@@ -0,0 +1,323 @@
1
+ const withResolvers = () => {
2
+ if (typeof Promise.withResolvers === "function") {
3
+ return Promise.withResolvers();
4
+ }
5
+ let resolve;
6
+ let reject;
7
+ const promise = new Promise((resolve_fn, reject_fn) => {
8
+ resolve = resolve_fn;
9
+ reject = reject_fn;
10
+ });
11
+ return { promise, resolve, reject };
12
+ };
13
+ const EVENT_CONCURRENCY_MODES = ["global-serial", "bus-serial", "parallel"];
14
+ const EVENT_HANDLER_CONCURRENCY_MODES = ["serial", "parallel"];
15
+ const EVENT_HANDLER_COMPLETION_MODES = ["all", "first"];
16
+ class AsyncLock {
17
+ size;
18
+ in_use;
19
+ waiters;
20
+ constructor(size) {
21
+ this.size = size;
22
+ this.in_use = 0;
23
+ this.waiters = [];
24
+ }
25
+ async acquire() {
26
+ if (this.size === Infinity) {
27
+ return;
28
+ }
29
+ if (this.in_use < this.size) {
30
+ this.in_use += 1;
31
+ return;
32
+ }
33
+ await new Promise((resolve) => {
34
+ this.waiters.push(resolve);
35
+ });
36
+ }
37
+ release() {
38
+ if (this.size === Infinity) {
39
+ return;
40
+ }
41
+ const next = this.waiters.shift();
42
+ if (next) {
43
+ next();
44
+ return;
45
+ }
46
+ this.in_use = Math.max(0, this.in_use - 1);
47
+ }
48
+ }
49
+ const runWithLock = async (lock, fn) => {
50
+ if (!lock) {
51
+ return await fn();
52
+ }
53
+ await lock.acquire();
54
+ try {
55
+ return await fn();
56
+ } finally {
57
+ lock.release();
58
+ }
59
+ };
60
+ class HandlerLock {
61
+ lock;
62
+ state;
63
+ constructor(lock) {
64
+ this.lock = lock;
65
+ this.state = "held";
66
+ }
67
+ // used by EventBus._processEventImmediately to yield the parent handler's lock to the child event so it can be processed immediately
68
+ yieldHandlerLockForChildRun() {
69
+ if (!this.lock || this.state !== "held") {
70
+ return false;
71
+ }
72
+ this.state = "yielded";
73
+ this.lock.release();
74
+ return true;
75
+ }
76
+ // used by EventBus._processEventImmediately to reacquire the handler lock after the child event has been processed
77
+ async reclaimHandlerLockIfRunning() {
78
+ if (!this.lock || this.state !== "yielded") {
79
+ return false;
80
+ }
81
+ await this.lock.acquire();
82
+ if (this.state !== "yielded") {
83
+ this.lock.release();
84
+ return false;
85
+ }
86
+ this.state = "held";
87
+ return true;
88
+ }
89
+ // used by EventResult.runHandler to exit the handler lock after the handler has finished executing
90
+ exitHandlerRun() {
91
+ if (this.state === "closed") {
92
+ return;
93
+ }
94
+ const should_release = !!this.lock && this.state === "held";
95
+ this.state = "closed";
96
+ if (should_release) {
97
+ this.lock.release();
98
+ }
99
+ }
100
+ // used by EventBus._processEventImmediately to yield the handler lock and reacquire it after the child event has been processed
101
+ async runQueueJump(fn) {
102
+ const yielded = this.yieldHandlerLockForChildRun();
103
+ try {
104
+ return await fn();
105
+ } finally {
106
+ if (yielded) {
107
+ await this.reclaimHandlerLockIfRunning();
108
+ }
109
+ }
110
+ }
111
+ }
112
+ class LockManager {
113
+ bus;
114
+ // Live bus reference; used to read defaults and idle state.
115
+ auto_schedule_idle_checks;
116
+ bus_event_lock;
117
+ // Per-bus event lock; created with LockManager and never swapped.
118
+ pause_depth;
119
+ // Re-entrant pause counter; increments on _requestRunloopPause, decrements on release.
120
+ pause_waiters;
121
+ // Resolvers for _waitUntilRunloopResumed; drained when pause_depth hits 0.
122
+ active_handler_results;
123
+ // Stack of active handler results for "inside handler" detection.
124
+ idle_waiters;
125
+ // Resolvers waiting for stable idle; cleared when idle confirmed.
126
+ idle_check_pending;
127
+ // Debounce flag to avoid scheduling redundant idle checks.
128
+ idle_check_streak;
129
+ // Counts consecutive idle checks; used to require two ticks of idle.
130
+ constructor(bus, options = {}) {
131
+ this.bus = bus;
132
+ this.auto_schedule_idle_checks = options.auto_schedule_idle_checks ?? true;
133
+ this.bus_event_lock = new AsyncLock(1);
134
+ this.pause_depth = 0;
135
+ this.pause_waiters = [];
136
+ this.active_handler_results = [];
137
+ this.idle_waiters = [];
138
+ this.idle_check_pending = false;
139
+ this.idle_check_streak = 0;
140
+ }
141
+ // Low-level runloop pause: increments a re-entrant counter and returns a release
142
+ // function. Used for broad, bus-scoped pauses during queue-jump across buses.
143
+ _requestRunloopPause() {
144
+ this.pause_depth += 1;
145
+ let released = false;
146
+ return () => {
147
+ if (released) {
148
+ return;
149
+ }
150
+ released = true;
151
+ this.pause_depth = Math.max(0, this.pause_depth - 1);
152
+ if (this.pause_depth !== 0) {
153
+ return;
154
+ }
155
+ const waiters = this.pause_waiters;
156
+ this.pause_waiters = [];
157
+ for (const resolve of waiters) {
158
+ resolve();
159
+ }
160
+ };
161
+ }
162
+ _waitUntilRunloopResumed() {
163
+ if (this.pause_depth === 0) {
164
+ return Promise.resolve();
165
+ }
166
+ return new Promise((resolve) => {
167
+ this.pause_waiters.push(resolve);
168
+ });
169
+ }
170
+ _isPaused() {
171
+ return this.pause_depth > 0;
172
+ }
173
+ async _runWithHandlerDispatchContext(result, fn) {
174
+ this.active_handler_results.push(result);
175
+ try {
176
+ return await fn();
177
+ } finally {
178
+ const idx = this.active_handler_results.indexOf(result);
179
+ if (idx >= 0) {
180
+ this.active_handler_results.splice(idx, 1);
181
+ }
182
+ }
183
+ }
184
+ _getActiveHandlerResult() {
185
+ return this.active_handler_results[this.active_handler_results.length - 1];
186
+ }
187
+ _getActiveHandlerResults() {
188
+ return [...this.active_handler_results];
189
+ }
190
+ // Per-bus check: true only if this specific bus has a handler on its stack.
191
+ // For cross-bus queue-jumping, EventBus._processEventImmediately uses getParentEventResultAcrossAllBuses()
192
+ // to walk up the parent event tree, and the bus proxy passes handler_result
193
+ // to _processEventImmediately so it can yield/reacquire the correct lock.
194
+ _isAnyHandlerActive() {
195
+ return this.active_handler_results.length > 0;
196
+ }
197
+ waitForIdle(timeout_seconds = null) {
198
+ return new Promise((resolve) => {
199
+ let done = false;
200
+ let timeout_id = null;
201
+ const finish = (became_idle) => {
202
+ if (done) {
203
+ return;
204
+ }
205
+ done = true;
206
+ if (timeout_id !== null) {
207
+ clearTimeout(timeout_id);
208
+ timeout_id = null;
209
+ }
210
+ resolve(became_idle);
211
+ };
212
+ this.idle_waiters.push(finish);
213
+ this.scheduleIdleCheck();
214
+ if (timeout_seconds === null || timeout_seconds === void 0) {
215
+ return;
216
+ }
217
+ const timeout_ms = Math.max(0, Number(timeout_seconds)) * 1e3;
218
+ if (!Number.isFinite(timeout_ms)) {
219
+ return;
220
+ }
221
+ timeout_id = setTimeout(() => {
222
+ const index = this.idle_waiters.indexOf(finish);
223
+ if (index >= 0) {
224
+ this.idle_waiters.splice(index, 1);
225
+ }
226
+ finish(false);
227
+ }, timeout_ms);
228
+ });
229
+ }
230
+ // Called by EventBus.markEventCompleted and EventBus.markHandlerCompleted to notify
231
+ // waitUntilIdle() callers that the bus may now be idle.
232
+ _notifyIdleListeners() {
233
+ if (this.idle_waiters.length === 0) {
234
+ this.idle_check_streak = 0;
235
+ return;
236
+ }
237
+ if (!this.bus.isIdleAndQueueEmpty()) {
238
+ this.idle_check_streak = 0;
239
+ if (this.idle_waiters.length > 0) {
240
+ this.scheduleIdleCheck();
241
+ }
242
+ return;
243
+ }
244
+ this.idle_check_streak += 1;
245
+ if (this.idle_check_streak < 2) {
246
+ if (this.idle_waiters.length > 0) {
247
+ this.scheduleIdleCheck();
248
+ }
249
+ return;
250
+ }
251
+ this.idle_check_streak = 0;
252
+ const waiters = this.idle_waiters;
253
+ this.idle_waiters = [];
254
+ for (const resolve of waiters) {
255
+ resolve(true);
256
+ }
257
+ }
258
+ // get the bus-level lock that prevents/allows multiple events to be processed concurrently on the same bus
259
+ getLockForEvent(event) {
260
+ const resolved = event.event_concurrency ?? this.bus.event_concurrency;
261
+ if (resolved === "parallel") {
262
+ return null;
263
+ }
264
+ if (resolved === "global-serial") {
265
+ return this.bus._lock_for_event_global_serial;
266
+ }
267
+ return this.bus_event_lock;
268
+ }
269
+ async _runWithEventLock(event, fn, options = {}) {
270
+ const pre_acquired = options.pre_acquired_lock ?? null;
271
+ if (options.bypass_event_locks || pre_acquired) {
272
+ return await fn();
273
+ }
274
+ return await runWithLock(this.getLockForEvent(event), fn);
275
+ }
276
+ async _runWithHandlerLock(event, default_handler_concurrency, fn) {
277
+ const lock = event._getHandlerLock(default_handler_concurrency);
278
+ if (lock) {
279
+ await lock.acquire();
280
+ }
281
+ const handler_lock = lock ? new HandlerLock(lock) : null;
282
+ try {
283
+ return await fn(handler_lock);
284
+ } finally {
285
+ handler_lock?.exitHandlerRun();
286
+ }
287
+ }
288
+ // Schedules a debounced idle check to run after a short delay. Used to gate
289
+ // waitUntilIdle() calls during handler execution and after event completion.
290
+ scheduleIdleCheck() {
291
+ if (!this.auto_schedule_idle_checks) {
292
+ return;
293
+ }
294
+ if (this.idle_check_pending) {
295
+ return;
296
+ }
297
+ this.idle_check_pending = true;
298
+ setTimeout(() => {
299
+ this.idle_check_pending = false;
300
+ this._notifyIdleListeners();
301
+ }, 0);
302
+ }
303
+ // Reset all state to initial values
304
+ clear() {
305
+ this.pause_depth = 0;
306
+ this.pause_waiters = [];
307
+ this.active_handler_results = [];
308
+ this.idle_waiters = [];
309
+ this.idle_check_pending = false;
310
+ this.idle_check_streak = 0;
311
+ }
312
+ }
313
+ export {
314
+ AsyncLock,
315
+ EVENT_CONCURRENCY_MODES,
316
+ EVENT_HANDLER_COMPLETION_MODES,
317
+ EVENT_HANDLER_CONCURRENCY_MODES,
318
+ HandlerLock,
319
+ LockManager,
320
+ runWithLock,
321
+ withResolvers
322
+ };
323
+ //# sourceMappingURL=lock_manager.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lock_manager.ts"],
4
+ "sourcesContent": ["import type { BaseEvent } from './base_event.js'\nimport type { EventResult } from './event_result.js'\n\n// \u2500\u2500\u2500 Deferred / withResolvers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type Deferred<T> = {\n promise: Promise<T>\n resolve: (value: T | PromiseLike<T>) => void\n reject: (reason?: unknown) => void\n}\n\nexport const withResolvers = <T>(): Deferred<T> => {\n if (typeof Promise.withResolvers === 'function') {\n return Promise.withResolvers<T>()\n }\n let resolve!: (value: T | PromiseLike<T>) => void\n let reject!: (reason?: unknown) => void\n const promise = new Promise<T>((resolve_fn, reject_fn) => {\n resolve = resolve_fn\n reject = reject_fn\n })\n return { promise, resolve, reject }\n}\n\n// \u2500\u2500\u2500 Concurrency modes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const EVENT_CONCURRENCY_MODES = ['global-serial', 'bus-serial', 'parallel'] as const\nexport type EventConcurrencyMode = (typeof EVENT_CONCURRENCY_MODES)[number]\n\nexport const EVENT_HANDLER_CONCURRENCY_MODES = ['serial', 'parallel'] as const\nexport type EventHandlerConcurrencyMode = (typeof EVENT_HANDLER_CONCURRENCY_MODES)[number]\n\nexport const EVENT_HANDLER_COMPLETION_MODES = ['all', 'first'] as const\nexport type EventHandlerCompletionMode = (typeof EVENT_HANDLER_COMPLETION_MODES)[number]\n\n// \u2500\u2500\u2500 AsyncLock \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class AsyncLock {\n size: number\n in_use: number\n waiters: Array<() => void>\n\n constructor(size: number) {\n this.size = size\n this.in_use = 0\n this.waiters = []\n }\n\n async acquire(): Promise<void> {\n if (this.size === Infinity) {\n return\n }\n if (this.in_use < this.size) {\n this.in_use += 1\n return\n }\n await new Promise<void>((resolve) => {\n this.waiters.push(resolve)\n })\n }\n\n release(): void {\n if (this.size === Infinity) {\n return\n }\n const next = this.waiters.shift()\n if (next) {\n // Handoff: keep permit accounted for and transfer directly to next waiter.\n next()\n return\n }\n this.in_use = Math.max(0, this.in_use - 1)\n }\n}\n\nexport const runWithLock = async <T>(lock: AsyncLock | null, fn: () => Promise<T>): Promise<T> => {\n if (!lock) {\n return await fn()\n }\n await lock.acquire()\n try {\n return await fn()\n } finally {\n lock.release()\n }\n}\n\n// \u2500\u2500\u2500 HandlerLock \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type HandlerExecutionState = 'held' | 'yielded' | 'closed'\n\n// Tracks a single handler execution's ownership of a handler lock.\n// Reacquire is race-safe: if the handler exits while waiting to reclaim,\n// the reclaimed lock is immediately released to avoid leaks.\nexport class HandlerLock {\n private lock: AsyncLock | null\n private state: HandlerExecutionState\n\n constructor(lock: AsyncLock | null) {\n this.lock = lock\n this.state = 'held'\n }\n\n // used by EventBus._processEventImmediately to yield the parent handler's lock to the child event so it can be processed immediately\n yieldHandlerLockForChildRun(): boolean {\n if (!this.lock || this.state !== 'held') {\n return false\n }\n this.state = 'yielded'\n this.lock.release()\n return true\n }\n\n // used by EventBus._processEventImmediately to reacquire the handler lock after the child event has been processed\n async reclaimHandlerLockIfRunning(): Promise<boolean> {\n if (!this.lock || this.state !== 'yielded') {\n return false\n }\n await this.lock.acquire()\n if (this.state !== 'yielded') {\n // Handler exited while this reacquire was pending.\n this.lock.release()\n return false\n }\n this.state = 'held'\n return true\n }\n\n // used by EventResult.runHandler to exit the handler lock after the handler has finished executing\n exitHandlerRun(): void {\n if (this.state === 'closed') {\n return\n }\n const should_release = !!this.lock && this.state === 'held'\n this.state = 'closed'\n if (should_release) {\n this.lock!.release()\n }\n }\n\n // used by EventBus._processEventImmediately to yield the handler lock and reacquire it after the child event has been processed\n async runQueueJump<T>(fn: () => Promise<T>): Promise<T> {\n const yielded = this.yieldHandlerLockForChildRun()\n try {\n return await fn()\n } finally {\n if (yielded) {\n await this.reclaimHandlerLockIfRunning()\n }\n }\n }\n}\n\n// \u2500\u2500\u2500 LockManager \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// Interface that must be implemented by the EventBus class to be used by the LockManager\nexport type EventBusInterfaceForLockManager = {\n isIdleAndQueueEmpty: () => boolean\n event_concurrency: EventConcurrencyMode\n _lock_for_event_global_serial: AsyncLock\n}\n\nexport type LockManagerOptions = {\n auto_schedule_idle_checks?: boolean\n}\n\n// The LockManager is responsible for managing the concurrency of events and handlers\nexport class LockManager {\n private bus: EventBusInterfaceForLockManager // Live bus reference; used to read defaults and idle state.\n private auto_schedule_idle_checks: boolean\n\n readonly bus_event_lock: AsyncLock // Per-bus event lock; created with LockManager and never swapped.\n private pause_depth: number // Re-entrant pause counter; increments on _requestRunloopPause, decrements on release.\n private pause_waiters: Array<() => void> // Resolvers for _waitUntilRunloopResumed; drained when pause_depth hits 0.\n private active_handler_results: EventResult[] // Stack of active handler results for \"inside handler\" detection.\n\n private idle_waiters: Array<(became_idle: boolean) => void> // Resolvers waiting for stable idle; cleared when idle confirmed.\n private idle_check_pending: boolean // Debounce flag to avoid scheduling redundant idle checks.\n private idle_check_streak: number // Counts consecutive idle checks; used to require two ticks of idle.\n\n constructor(bus: EventBusInterfaceForLockManager, options: LockManagerOptions = {}) {\n this.bus = bus\n this.auto_schedule_idle_checks = options.auto_schedule_idle_checks ?? true\n this.bus_event_lock = new AsyncLock(1) // used for the bus-serial concurrency mode\n\n this.pause_depth = 0\n this.pause_waiters = []\n this.active_handler_results = []\n\n this.idle_waiters = []\n this.idle_check_pending = false\n this.idle_check_streak = 0\n }\n\n // Low-level runloop pause: increments a re-entrant counter and returns a release\n // function. Used for broad, bus-scoped pauses during queue-jump across buses.\n _requestRunloopPause(): () => void {\n this.pause_depth += 1\n let released = false\n return () => {\n if (released) {\n return\n }\n released = true\n this.pause_depth = Math.max(0, this.pause_depth - 1)\n if (this.pause_depth !== 0) {\n return\n }\n const waiters = this.pause_waiters\n this.pause_waiters = []\n for (const resolve of waiters) {\n resolve()\n }\n }\n }\n\n _waitUntilRunloopResumed(): Promise<void> {\n if (this.pause_depth === 0) {\n return Promise.resolve()\n }\n return new Promise((resolve) => {\n this.pause_waiters.push(resolve)\n })\n }\n\n _isPaused(): boolean {\n return this.pause_depth > 0\n }\n\n async _runWithHandlerDispatchContext<T>(result: EventResult, fn: () => Promise<T>): Promise<T> {\n this.active_handler_results.push(result)\n try {\n return await fn()\n } finally {\n const idx = this.active_handler_results.indexOf(result)\n if (idx >= 0) {\n this.active_handler_results.splice(idx, 1)\n }\n }\n }\n\n _getActiveHandlerResult(): EventResult | undefined {\n return this.active_handler_results[this.active_handler_results.length - 1]\n }\n\n _getActiveHandlerResults(): EventResult[] {\n return [...this.active_handler_results]\n }\n\n // Per-bus check: true only if this specific bus has a handler on its stack.\n // For cross-bus queue-jumping, EventBus._processEventImmediately uses getParentEventResultAcrossAllBuses()\n // to walk up the parent event tree, and the bus proxy passes handler_result\n // to _processEventImmediately so it can yield/reacquire the correct lock.\n _isAnyHandlerActive(): boolean {\n return this.active_handler_results.length > 0\n }\n\n waitForIdle(timeout_seconds: number | null = null): Promise<boolean> {\n return new Promise((resolve) => {\n let done = false\n let timeout_id: ReturnType<typeof setTimeout> | null = null\n\n const finish = (became_idle: boolean): void => {\n if (done) {\n return\n }\n done = true\n if (timeout_id !== null) {\n clearTimeout(timeout_id)\n timeout_id = null\n }\n resolve(became_idle)\n }\n\n this.idle_waiters.push(finish)\n this.scheduleIdleCheck()\n\n if (timeout_seconds === null || timeout_seconds === undefined) {\n return\n }\n\n const timeout_ms = Math.max(0, Number(timeout_seconds)) * 1000\n if (!Number.isFinite(timeout_ms)) {\n return\n }\n\n timeout_id = setTimeout(() => {\n const index = this.idle_waiters.indexOf(finish)\n if (index >= 0) {\n this.idle_waiters.splice(index, 1)\n }\n finish(false)\n }, timeout_ms)\n })\n }\n\n // Called by EventBus.markEventCompleted and EventBus.markHandlerCompleted to notify\n // waitUntilIdle() callers that the bus may now be idle.\n _notifyIdleListeners(): void {\n // Fast-path: most completions have no waitUntilIdle() callers waiting,\n // so skip expensive idle snapshot scans in that common case.\n if (this.idle_waiters.length === 0) {\n this.idle_check_streak = 0\n return\n }\n\n if (!this.bus.isIdleAndQueueEmpty()) {\n this.idle_check_streak = 0\n if (this.idle_waiters.length > 0) {\n this.scheduleIdleCheck()\n }\n return\n }\n\n this.idle_check_streak += 1\n if (this.idle_check_streak < 2) {\n if (this.idle_waiters.length > 0) {\n this.scheduleIdleCheck()\n }\n return\n }\n\n this.idle_check_streak = 0\n const waiters = this.idle_waiters\n this.idle_waiters = []\n for (const resolve of waiters) {\n resolve(true)\n }\n }\n\n // get the bus-level lock that prevents/allows multiple events to be processed concurrently on the same bus\n getLockForEvent(event: BaseEvent): AsyncLock | null {\n const resolved = event.event_concurrency ?? this.bus.event_concurrency\n if (resolved === 'parallel') {\n return null\n }\n if (resolved === 'global-serial') {\n return this.bus._lock_for_event_global_serial\n }\n return this.bus_event_lock\n }\n\n async _runWithEventLock<T>(\n event: BaseEvent,\n fn: () => Promise<T>,\n options: { bypass_event_locks?: boolean; pre_acquired_lock?: AsyncLock | null } = {}\n ): Promise<T> {\n const pre_acquired = options.pre_acquired_lock ?? null\n if (options.bypass_event_locks || pre_acquired) {\n return await fn()\n }\n return await runWithLock(this.getLockForEvent(event), fn)\n }\n\n async _runWithHandlerLock<T>(\n event: BaseEvent,\n default_handler_concurrency: EventHandlerConcurrencyMode | undefined,\n fn: (lock: HandlerLock | null) => Promise<T>\n ): Promise<T> {\n const lock = event._getHandlerLock(default_handler_concurrency)\n if (lock) {\n await lock.acquire()\n }\n const handler_lock = lock ? new HandlerLock(lock) : null\n try {\n return await fn(handler_lock)\n } finally {\n handler_lock?.exitHandlerRun()\n }\n }\n\n // Schedules a debounced idle check to run after a short delay. Used to gate\n // waitUntilIdle() calls during handler execution and after event completion.\n private scheduleIdleCheck(): void {\n if (!this.auto_schedule_idle_checks) {\n return\n }\n if (this.idle_check_pending) {\n return\n }\n this.idle_check_pending = true\n setTimeout(() => {\n this.idle_check_pending = false\n this._notifyIdleListeners()\n }, 0)\n }\n\n // Reset all state to initial values\n clear(): void {\n this.pause_depth = 0\n this.pause_waiters = []\n this.active_handler_results = []\n this.idle_waiters = []\n this.idle_check_pending = false\n this.idle_check_streak = 0\n }\n}\n"],
5
+ "mappings": "AAWO,MAAM,gBAAgB,MAAsB;AACjD,MAAI,OAAO,QAAQ,kBAAkB,YAAY;AAC/C,WAAO,QAAQ,cAAiB;AAAA,EAClC;AACA,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,IAAI,QAAW,CAAC,YAAY,cAAc;AACxD,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AACD,SAAO,EAAE,SAAS,SAAS,OAAO;AACpC;AAIO,MAAM,0BAA0B,CAAC,iBAAiB,cAAc,UAAU;AAG1E,MAAM,kCAAkC,CAAC,UAAU,UAAU;AAG7D,MAAM,iCAAiC,CAAC,OAAO,OAAO;AAKtD,MAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,MAAc;AACxB,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU,CAAC;AAAA,EAClB;AAAA,EAEA,MAAM,UAAyB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AO,MAAM,gBAAgB,2BAA2B;AAC9D,QAAI,MAAM;AACR,YAAM,KAAK,QAAQ;AAAA,IACrB;AACA,UAAM,eAAe,OAAO,IAAI,YAAY,IAAI,IAAI;AACpD,QAAI;AACF,aAAO,MAAM,GAAG,YAAY;AAAA,IAC9B,UAAE;AACA,oBAAc,eAAe;AAAA,IAC/B;AAAA,EACF;AAAA;AAAA;AAAA,EAIQ,oBAA0B;AAChC,QAAI,CAAC,KAAK,2BAA2B;AACnC;AAAA,IACF;AACA,QAAI,KAAK,oBAAoB;AAC3B;AAAA,IACF;AACA,SAAK,qBAAqB;AAC1B,eAAW,MAAM;AACf,WAAK,qBAAqB;AAC1B,WAAK,qBAAqB;AAAA,IAC5B,GAAG,CAAC;AAAA,EACN;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,cAAc;AACnB,SAAK,gBAAgB,CAAC;AACtB,SAAK,yBAAyB,CAAC;AAC/B,SAAK,eAAe,CAAC;AACrB,SAAK,qBAAqB;AAC1B,SAAK,oBAAoB;AAAA,EAC3B;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,196 @@
1
+ import { BaseEvent } from "./base_event.js";
2
+ import { EventHandlerCancelledError, EventHandlerTimeoutError } from "./event_handler.js";
3
+ const logTree = (bus) => {
4
+ const parent_to_children = /* @__PURE__ */ new Map();
5
+ const addChild = (parent_id, child) => {
6
+ const existing = parent_to_children.get(parent_id) ?? [];
7
+ existing.push(child);
8
+ parent_to_children.set(parent_id, existing);
9
+ };
10
+ const root_events = [];
11
+ const seen = /* @__PURE__ */ new Set();
12
+ for (const event of bus.event_history.values()) {
13
+ const parent_id = event.event_parent_id;
14
+ if (!parent_id || parent_id === event.event_id || !bus.event_history.has(parent_id)) {
15
+ if (!seen.has(event.event_id)) {
16
+ root_events.push(event);
17
+ seen.add(event.event_id);
18
+ }
19
+ }
20
+ }
21
+ if (root_events.length === 0) {
22
+ return "(No events in history)";
23
+ }
24
+ const nodes_by_id = /* @__PURE__ */ new Map();
25
+ for (const root of root_events) {
26
+ nodes_by_id.set(root.event_id, root);
27
+ for (const descendant of root.event_descendants) {
28
+ nodes_by_id.set(descendant.event_id, descendant);
29
+ }
30
+ }
31
+ for (const node of nodes_by_id.values()) {
32
+ const parent_id = node.event_parent_id;
33
+ if (!parent_id || parent_id === node.event_id) {
34
+ continue;
35
+ }
36
+ if (!nodes_by_id.has(parent_id)) {
37
+ continue;
38
+ }
39
+ addChild(parent_id, node);
40
+ }
41
+ for (const children of parent_to_children.values()) {
42
+ children.sort((a, b) => a.event_created_at < b.event_created_at ? -1 : a.event_created_at > b.event_created_at ? 1 : 0);
43
+ }
44
+ const lines = [];
45
+ const bus_label = typeof bus.toString === "function" ? bus.toString() : bus.name;
46
+ lines.push(`\u{1F4CA} Event History Tree for ${bus_label}`);
47
+ lines.push("=".repeat(80));
48
+ root_events.sort((a, b) => a.event_created_at < b.event_created_at ? -1 : a.event_created_at > b.event_created_at ? 1 : 0);
49
+ const visited = /* @__PURE__ */ new Set();
50
+ root_events.forEach((event, index) => {
51
+ lines.push(buildTreeLine(event, "", index === root_events.length - 1, parent_to_children, visited));
52
+ });
53
+ lines.push("=".repeat(80));
54
+ return lines.join("\n");
55
+ };
56
+ const buildTreeLine = (event, indent, is_last, parent_to_children, visited) => {
57
+ const connector = is_last ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
58
+ const status_icon = event.event_status === "completed" ? "\u2705" : event.event_status === "started" ? "\u{1F3C3}" : "\u23F3";
59
+ const created_at = formatTimestamp(event.event_created_at);
60
+ let timing = `[${created_at}`;
61
+ if (event.event_completed_at) {
62
+ const created_ms = Date.parse(event.event_created_at);
63
+ const completed_ms = Date.parse(event.event_completed_at);
64
+ if (!Number.isNaN(created_ms) && !Number.isNaN(completed_ms)) {
65
+ const duration = (completed_ms - created_ms) / 1e3;
66
+ timing += ` (${duration.toFixed(3)}s)`;
67
+ }
68
+ }
69
+ timing += "]";
70
+ const line = `${indent}${connector}${status_icon} ${event.event_type}#${event.event_id.slice(-4)} ${timing}`;
71
+ if (visited.has(event.event_id)) {
72
+ return line;
73
+ }
74
+ visited.add(event.event_id);
75
+ const extension = is_last ? " " : "\u2502 ";
76
+ const new_indent = indent + extension;
77
+ const result_items = [];
78
+ for (const result of event.event_results.values()) {
79
+ result_items.push({ type: "result", result });
80
+ }
81
+ const children = parent_to_children.get(event.event_id) ?? [];
82
+ const printed_child_ids = new Set(event.event_results.size > 0 ? event.event_results.keys() : []);
83
+ for (const child of children) {
84
+ if (!printed_child_ids.has(child.event_id) && !child.event_emitted_by_handler_id) {
85
+ result_items.push({ type: "child", child });
86
+ printed_child_ids.add(child.event_id);
87
+ }
88
+ }
89
+ if (result_items.length === 0) {
90
+ return line;
91
+ }
92
+ const child_lines = [];
93
+ result_items.forEach((item, index) => {
94
+ const is_last_item = index === result_items.length - 1;
95
+ if (item.type === "result") {
96
+ child_lines.push(buildResultLine(item.result, new_indent, is_last_item, parent_to_children, visited));
97
+ } else {
98
+ child_lines.push(buildTreeLine(item.child, new_indent, is_last_item, parent_to_children, visited));
99
+ }
100
+ });
101
+ return [line, ...child_lines].join("\n");
102
+ };
103
+ const buildResultLine = (result, indent, is_last, parent_to_children, visited) => {
104
+ const connector = is_last ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
105
+ const status_icon = result.status === "completed" ? "\u2705" : result.status === "error" ? "\u274C" : result.status === "started" ? "\u{1F3C3}" : "\u23F3";
106
+ const handler_label = result.handler_name && result.handler_name !== "anonymous" ? result.handler_name : result.handler_file_path ? result.handler_file_path : "anonymous";
107
+ const handler_display = `${result.eventbus_label}.${handler_label}#${result.handler_id.slice(-4)}`;
108
+ let line = `${indent}${connector}${status_icon} ${handler_display}`;
109
+ if (result.started_at) {
110
+ line += ` [${formatTimestamp(result.started_at)}`;
111
+ if (result.completed_at) {
112
+ const started_ms = Date.parse(result.started_at);
113
+ const completed_ms = Date.parse(result.completed_at);
114
+ if (!Number.isNaN(started_ms) && !Number.isNaN(completed_ms)) {
115
+ const duration = (completed_ms - started_ms) / 1e3;
116
+ line += ` (${duration.toFixed(3)}s)`;
117
+ }
118
+ }
119
+ line += "]";
120
+ }
121
+ if (result.status === "error" && result.error) {
122
+ if (result.error instanceof EventHandlerTimeoutError) {
123
+ line += ` \u23F1\uFE0F Timeout: ${result.error.message}`;
124
+ } else if (result.error instanceof EventHandlerCancelledError) {
125
+ line += ` \u{1F6AB} Cancelled: ${result.error.message}`;
126
+ } else {
127
+ const error_name = result.error instanceof Error ? result.error.name : "Error";
128
+ const error_message = result.error instanceof Error ? result.error.message : String(result.error);
129
+ line += ` \u2620\uFE0F ${error_name}: ${error_message}`;
130
+ }
131
+ } else if (result.status === "completed") {
132
+ line += ` \u2192 ${formatResultValue(result.result)}`;
133
+ }
134
+ const extension = is_last ? " " : "\u2502 ";
135
+ const new_indent = indent + extension;
136
+ const direct_children = result.event_children;
137
+ if (direct_children.length === 0) {
138
+ return line;
139
+ }
140
+ const child_lines = [];
141
+ const parent_children = parent_to_children.get(result.event_id) ?? [];
142
+ const emitted_children = parent_children.filter((child) => child.event_emitted_by_handler_id === result.handler_id);
143
+ const children_by_id = /* @__PURE__ */ new Map();
144
+ direct_children.forEach((child) => {
145
+ children_by_id.set(child.event_id, child);
146
+ });
147
+ emitted_children.forEach((child) => {
148
+ if (!children_by_id.has(child.event_id)) {
149
+ children_by_id.set(child.event_id, child);
150
+ }
151
+ });
152
+ const children_to_print = Array.from(children_by_id.values()).filter((child) => !visited.has(child.event_id));
153
+ children_to_print.forEach((child, index) => {
154
+ child_lines.push(buildTreeLine(child, new_indent, index === children_to_print.length - 1, parent_to_children, visited));
155
+ });
156
+ return [line, ...child_lines].join("\n");
157
+ };
158
+ const formatTimestamp = (value) => {
159
+ if (!value) {
160
+ return "N/A";
161
+ }
162
+ const date = new Date(value);
163
+ if (Number.isNaN(date.getTime())) {
164
+ return "N/A";
165
+ }
166
+ return date.toISOString().slice(11, 23);
167
+ };
168
+ const formatResultValue = (value) => {
169
+ if (value === null || value === void 0) {
170
+ return "None";
171
+ }
172
+ if (value instanceof BaseEvent) {
173
+ return `Event(${value.event_type}#${value.event_id.slice(-4)})`;
174
+ }
175
+ if (typeof value === "string") {
176
+ return JSON.stringify(value);
177
+ }
178
+ if (typeof value === "number" || typeof value === "boolean") {
179
+ return String(value);
180
+ }
181
+ if (Array.isArray(value)) {
182
+ return `list(${value.length} items)`;
183
+ }
184
+ if (typeof value === "object") {
185
+ return `dict(${Object.keys(value).length} items)`;
186
+ }
187
+ return `${typeof value}(...)`;
188
+ };
189
+ export {
190
+ buildResultLine,
191
+ buildTreeLine,
192
+ formatResultValue,
193
+ formatTimestamp,
194
+ logTree
195
+ };
196
+ //# sourceMappingURL=logging.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/logging.ts"],
4
+ "sourcesContent": ["import { BaseEvent } from './base_event.js'\nimport { EventResult } from './event_result.js'\nimport { EventHandlerCancelledError, EventHandlerTimeoutError } from './event_handler.js'\n\ntype LogTreeBus = {\n name: string\n event_history: {\n values(): IterableIterator<BaseEvent>\n has(event_id: string): boolean\n }\n toString?: () => string\n}\n\nexport const logTree = (bus: LogTreeBus): string => {\n const parent_to_children = new Map<string, BaseEvent[]>()\n\n const addChild = (parent_id: string, child: BaseEvent): void => {\n const existing = parent_to_children.get(parent_id) ?? []\n existing.push(child)\n parent_to_children.set(parent_id, existing)\n }\n\n const root_events: BaseEvent[] = []\n const seen = new Set<string>()\n\n for (const event of bus.event_history.values()) {\n const parent_id = event.event_parent_id\n if (!parent_id || parent_id === event.event_id || !bus.event_history.has(parent_id)) {\n if (!seen.has(event.event_id)) {\n root_events.push(event)\n seen.add(event.event_id)\n }\n }\n }\n\n if (root_events.length === 0) {\n return '(No events in history)'\n }\n\n const nodes_by_id = new Map<string, BaseEvent>()\n for (const root of root_events) {\n nodes_by_id.set(root.event_id, root)\n for (const descendant of root.event_descendants) {\n nodes_by_id.set(descendant.event_id, descendant)\n }\n }\n\n for (const node of nodes_by_id.values()) {\n const parent_id = node.event_parent_id\n if (!parent_id || parent_id === node.event_id) {\n continue\n }\n if (!nodes_by_id.has(parent_id)) {\n continue\n }\n addChild(parent_id, node)\n }\n\n for (const children of parent_to_children.values()) {\n children.sort((a, b) => (a.event_created_at < b.event_created_at ? -1 : a.event_created_at > b.event_created_at ? 1 : 0))\n }\n\n const lines: string[] = []\n const bus_label = typeof bus.toString === 'function' ? bus.toString() : bus.name\n lines.push(`\uD83D\uDCCA Event History Tree for ${bus_label}`)\n lines.push('='.repeat(80))\n\n root_events.sort((a, b) => (a.event_created_at < b.event_created_at ? -1 : a.event_created_at > b.event_created_at ? 1 : 0))\n const visited = new Set<string>()\n root_events.forEach((event, index) => {\n lines.push(buildTreeLine(event, '', index === root_events.length - 1, parent_to_children, visited))\n })\n\n lines.push('='.repeat(80))\n\n return lines.join('\\n')\n}\n\nexport const buildTreeLine = (\n event: BaseEvent,\n indent: string,\n is_last: boolean,\n parent_to_children: Map<string, BaseEvent[]>,\n visited: Set<string>\n): string => {\n const connector = is_last ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '\n const status_icon = event.event_status === 'completed' ? '\u2705' : event.event_status === 'started' ? '\uD83C\uDFC3' : '\u23F3'\n\n const created_at = formatTimestamp(event.event_created_at)\n let timing = `[${created_at}`\n if (event.event_completed_at) {\n const created_ms = Date.parse(event.event_created_at)\n const completed_ms = Date.parse(event.event_completed_at)\n if (!Number.isNaN(created_ms) && !Number.isNaN(completed_ms)) {\n const duration = (completed_ms - created_ms) / 1000\n timing += ` (${duration.toFixed(3)}s)`\n }\n }\n timing += ']'\n\n const line = `${indent}${connector}${status_icon} ${event.event_type}#${event.event_id.slice(-4)} ${timing}`\n\n if (visited.has(event.event_id)) {\n return line\n }\n visited.add(event.event_id)\n\n const extension = is_last ? ' ' : '\u2502 '\n const new_indent = indent + extension\n\n const result_items: Array<{ type: 'result'; result: EventResult } | { type: 'child'; child: BaseEvent }> = []\n for (const result of event.event_results.values()) {\n result_items.push({ type: 'result', result })\n }\n const children = parent_to_children.get(event.event_id) ?? []\n const printed_child_ids = new Set<string>(event.event_results.size > 0 ? event.event_results.keys() : [])\n for (const child of children) {\n if (!printed_child_ids.has(child.event_id) && !child.event_emitted_by_handler_id) {\n result_items.push({ type: 'child', child })\n printed_child_ids.add(child.event_id)\n }\n }\n\n if (result_items.length === 0) {\n return line\n }\n\n const child_lines: string[] = []\n result_items.forEach((item, index) => {\n const is_last_item = index === result_items.length - 1\n if (item.type === 'result') {\n child_lines.push(buildResultLine(item.result, new_indent, is_last_item, parent_to_children, visited))\n } else {\n child_lines.push(buildTreeLine(item.child, new_indent, is_last_item, parent_to_children, visited))\n }\n })\n\n return [line, ...child_lines].join('\\n')\n}\n\nexport const buildResultLine = (\n result: EventResult,\n indent: string,\n is_last: boolean,\n parent_to_children: Map<string, BaseEvent[]>,\n visited: Set<string>\n): string => {\n const connector = is_last ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '\n const status_icon = result.status === 'completed' ? '\u2705' : result.status === 'error' ? '\u274C' : result.status === 'started' ? '\uD83C\uDFC3' : '\u23F3'\n\n const handler_label =\n result.handler_name && result.handler_name !== 'anonymous'\n ? result.handler_name\n : result.handler_file_path\n ? result.handler_file_path\n : 'anonymous'\n const handler_display = `${result.eventbus_label}.${handler_label}#${result.handler_id.slice(-4)}`\n let line = `${indent}${connector}${status_icon} ${handler_display}`\n\n if (result.started_at) {\n line += ` [${formatTimestamp(result.started_at)}`\n if (result.completed_at) {\n const started_ms = Date.parse(result.started_at)\n const completed_ms = Date.parse(result.completed_at)\n if (!Number.isNaN(started_ms) && !Number.isNaN(completed_ms)) {\n const duration = (completed_ms - started_ms) / 1000\n line += ` (${duration.toFixed(3)}s)`\n }\n }\n line += ']'\n }\n\n if (result.status === 'error' && result.error) {\n if (result.error instanceof EventHandlerTimeoutError) {\n line += ` \u23F1\uFE0F Timeout: ${result.error.message}`\n } else if (result.error instanceof EventHandlerCancelledError) {\n line += ` \uD83D\uDEAB Cancelled: ${result.error.message}`\n } else {\n const error_name = result.error instanceof Error ? result.error.name : 'Error'\n const error_message = result.error instanceof Error ? result.error.message : String(result.error)\n line += ` \u2620\uFE0F ${error_name}: ${error_message}`\n }\n } else if (result.status === 'completed') {\n line += ` \u2192 ${formatResultValue(result.result)}`\n }\n\n const extension = is_last ? ' ' : '\u2502 '\n const new_indent = indent + extension\n\n const direct_children = result.event_children\n if (direct_children.length === 0) {\n return line\n }\n\n const child_lines: string[] = []\n const parent_children = parent_to_children.get(result.event_id) ?? []\n const emitted_children = parent_children.filter((child) => child.event_emitted_by_handler_id === result.handler_id)\n const children_by_id = new Map<string, BaseEvent>()\n direct_children.forEach((child) => {\n children_by_id.set(child.event_id, child)\n })\n emitted_children.forEach((child) => {\n if (!children_by_id.has(child.event_id)) {\n children_by_id.set(child.event_id, child)\n }\n })\n const children_to_print = Array.from(children_by_id.values()).filter((child) => !visited.has(child.event_id))\n\n children_to_print.forEach((child, index) => {\n child_lines.push(buildTreeLine(child, new_indent, index === children_to_print.length - 1, parent_to_children, visited))\n })\n\n return [line, ...child_lines].join('\\n')\n}\n\nexport const formatTimestamp = (value?: string): string => {\n if (!value) {\n return 'N/A'\n }\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) {\n return 'N/A'\n }\n return date.toISOString().slice(11, 23)\n}\n\nexport const formatResultValue = (value: unknown): string => {\n if (value === null || value === undefined) {\n return 'None'\n }\n if (value instanceof BaseEvent) {\n return `Event(${value.event_type}#${value.event_id.slice(-4)})`\n }\n if (typeof value === 'string') {\n return JSON.stringify(value)\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value)\n }\n if (Array.isArray(value)) {\n return `list(${value.length} items)`\n }\n if (typeof value === 'object') {\n return `dict(${Object.keys(value as Record<string, unknown>).length} items)`\n }\n return `${typeof value}(...)`\n}\n"],
5
+ "mappings": "AAAA,SAAS,iBAAiB;AAE1B,SAAS,4BAA4B,gCAAgC;AAW9D,MAAM,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YAAY,OAAO,UAAU,WAAW;AAC3D,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,QAAQ,MAAM,MAAM;AAAA,EAC7B;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,QAAQ,OAAO,KAAK,KAAgC,EAAE,MAAM;AAAA,EACrE;AACA,SAAO,GAAG,OAAO,KAAK;AACxB;",
6
+ "names": []
7
+ }
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=middlewares.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,34 @@
1
+ const isNodeRuntime = () => {
2
+ const maybe_process = globalThis.process;
3
+ return typeof maybe_process?.versions?.node === "string";
4
+ };
5
+ const missingDependencyError = (bridge_name, package_name) => new Error(`${bridge_name} requires optional dependency "${package_name}". Install it with: npm install ${package_name}`);
6
+ const assertOptionalDependencyAvailable = (bridge_name, package_name) => {
7
+ if (!isNodeRuntime()) return;
8
+ const maybe_process = globalThis.process;
9
+ const get_builtin_module = maybe_process?.getBuiltinModule;
10
+ if (typeof get_builtin_module !== "function") return;
11
+ const module_builtin = get_builtin_module("module");
12
+ const create_require = module_builtin?.createRequire;
13
+ if (typeof create_require !== "function") return;
14
+ const require_fn = create_require(import.meta.url);
15
+ try {
16
+ require_fn.resolve(package_name);
17
+ } catch {
18
+ throw missingDependencyError(bridge_name, package_name);
19
+ }
20
+ };
21
+ const importOptionalDependency = async (bridge_name, package_name) => {
22
+ const dynamic_import = Function("module_name", "return import(module_name)");
23
+ try {
24
+ return await dynamic_import(package_name);
25
+ } catch {
26
+ throw missingDependencyError(bridge_name, package_name);
27
+ }
28
+ };
29
+ export {
30
+ assertOptionalDependencyAvailable,
31
+ importOptionalDependency,
32
+ isNodeRuntime
33
+ };
34
+ //# sourceMappingURL=optional_deps.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/optional_deps.ts"],
4
+ "sourcesContent": ["export const isNodeRuntime = (): boolean => {\n const maybe_process = (globalThis as { process?: { versions?: { node?: string } } }).process\n return typeof maybe_process?.versions?.node === 'string'\n}\n\nconst missingDependencyError = (bridge_name: string, package_name: string): Error =>\n new Error(`${bridge_name} requires optional dependency \"${package_name}\". Install it with: npm install ${package_name}`)\n\nexport const assertOptionalDependencyAvailable = (bridge_name: string, package_name: string): void => {\n if (!isNodeRuntime()) return\n\n const maybe_process = (globalThis as { process?: { getBuiltinModule?: (name: string) => any } }).process\n const get_builtin_module = maybe_process?.getBuiltinModule\n if (typeof get_builtin_module !== 'function') return\n\n const module_builtin = get_builtin_module('module')\n const create_require = module_builtin?.createRequire\n if (typeof create_require !== 'function') return\n\n const require_fn = create_require(import.meta.url) as { resolve: (specifier: string) => string }\n try {\n require_fn.resolve(package_name)\n } catch {\n throw missingDependencyError(bridge_name, package_name)\n }\n}\n\nexport const importOptionalDependency = async (bridge_name: string, package_name: string): Promise<any> => {\n const dynamic_import = Function('module_name', 'return import(module_name)') as (module_name: string) => Promise<unknown>\n try {\n return (await dynamic_import(package_name)) as any\n } catch {\n throw missingDependencyError(bridge_name, package_name)\n }\n}\n"],
5
+ "mappings": "AAAO,MAAM,gBAAgB,MAAe;AAC1C,QAAM,gBAAiB,WAA8D;AACrF,SAAO,OAAO,eAAe,UAAU,SAAS;AAClD;AAEA,MAAM,yBAAyB,CAAC,aAAqB,iBACnD,IAAI,MAAM,GAAG,WAAW,kCAAkC,YAAY,mCAAmC,YAAY,EAAE;AAElH,MAAM,oCAAoC,CAAC,aAAqB,iBAA+B;AACpG,MAAI,CAAC,cAAc,EAAG;AAEtB,QAAM,gBAAiB,WAA0E;AACjG,QAAM,qBAAqB,eAAe;AAC1C,MAAI,OAAO,uBAAuB,WAAY;AAE9C,QAAM,iBAAiB,mBAAmB,QAAQ;AAClD,QAAM,iBAAiB,gBAAgB;AACvC,MAAI,OAAO,mBAAmB,WAAY;AAE1C,QAAM,aAAa,eAAe,YAAY,GAAG;AACjD,MAAI;AACF,eAAW,QAAQ,YAAY;AAAA,EACjC,QAAQ;AACN,UAAM,uBAAuB,aAAa,YAAY;AAAA,EACxD;AACF;AAEO,MAAM,2BAA2B,OAAO,aAAqB,iBAAuC;AACzG,QAAM,iBAAiB,SAAS,eAAe,4BAA4B;AAC3E,MAAI;AACF,WAAQ,MAAM,eAAe,YAAY;AAAA,EAC3C,QAAQ;AACN,UAAM,uBAAuB,aAAa,YAAY;AAAA,EACxD;AACF;",
6
+ "names": []
7
+ }