@isoloop/runtime 0.0.0-next.62ef495 → 0.0.0-next.800569e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bootstrap.js CHANGED
@@ -8,14 +8,14 @@ var __esmMin = (fn, res, err) => () => {
8
8
  throw err = [e], e;
9
9
  }
10
10
  };
11
- var __exportAll = (all, no_symbols) => {
12
- let target = {};
11
+ var __exportAll = (all, flags) => {
12
+ let target = Object.setPrototypeOf({}, null);
13
13
  for (var name in all) __defProp(target, name, {
14
14
  get: all[name],
15
15
  enumerable: true
16
16
  });
17
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
- return target;
17
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ return flags & 2 ? target : Object.preventExtensions(target);
19
19
  };
20
20
  // ../protocol/dist/index.js
21
21
  /**
@@ -38,6 +38,69 @@ function envelopeGuard(types) {
38
38
  function isSystemTopic(topic) {
39
39
  return topic.startsWith(SYSTEM_TOPIC_PREFIX);
40
40
  }
41
+ function createCommitter(o) {
42
+ const intervalMs = o.intervalMs ?? 100;
43
+ const half = Math.max(1, Math.floor((o.credit ?? 1e3) / 2));
44
+ /** Highest settled offset per topic, not yet sent. */
45
+ const offsets = /* @__PURE__ */ new Map();
46
+ /** Records settled per topic since its last send: the early send at half the credit. */
47
+ const counts = /* @__PURE__ */ new Map();
48
+ let timer;
49
+ let queued = false;
50
+ const take = () => {
51
+ if (timer !== void 0) {
52
+ clearTimeout(timer);
53
+ timer = void 0;
54
+ }
55
+ queued = false;
56
+ if (offsets.size === 0) return void 0;
57
+ const out = [];
58
+ for (const [topic, offset] of offsets) out.push({
59
+ topic,
60
+ offset
61
+ });
62
+ offsets.clear();
63
+ counts.clear();
64
+ return out;
65
+ };
66
+ const flush = () => {
67
+ const out = take();
68
+ if (out) o.send(out);
69
+ };
70
+ const schedule = () => {
71
+ if (intervalMs === 0) {
72
+ if (queued) return;
73
+ queued = true;
74
+ queueMicrotask(() => {
75
+ if (queued) flush();
76
+ });
77
+ return;
78
+ }
79
+ timer ??= setTimeout(flush, intervalMs);
80
+ };
81
+ return {
82
+ settle(topic, offset, records = 1) {
83
+ const prev = offsets.get(topic);
84
+ if (prev === void 0 || offset > prev) offsets.set(topic, offset);
85
+ const n = (counts.get(topic) ?? 0) + records;
86
+ counts.set(topic, n);
87
+ if (n >= half) flush();
88
+ else schedule();
89
+ },
90
+ flush,
91
+ take,
92
+ drop(topic) {
93
+ offsets.delete(topic);
94
+ counts.delete(topic);
95
+ },
96
+ pending: () => offsets,
97
+ dispose() {
98
+ if (timer !== void 0) clearTimeout(timer);
99
+ timer = void 0;
100
+ queued = false;
101
+ }
102
+ };
103
+ }
41
104
  /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
42
105
  function systemSchema(check) {
43
106
  return { "~standard": {
@@ -152,8 +215,322 @@ var init_dist = __esmMin((() => {
152
215
  retention: { kind: "compacted" }
153
216
  });
154
217
  }));
218
+ // src/busy.ts
219
+ function createBusy(now = () => performance.now()) {
220
+ let frame = null;
221
+ const spent = /* @__PURE__ */ new Map();
222
+ const containers = /* @__PURE__ */ new WeakMap();
223
+ /** Each key's current life. */
224
+ const lives = /* @__PURE__ */ new Map();
225
+ const lifeOf = (key) => lives.get(key) ?? null;
226
+ const bill = (key, ms) => {
227
+ spent.set(key, (spent.get(key) ?? 0) + ms);
228
+ };
229
+ const settle = (f) => {
230
+ const fallback = f.owner.key === PENDING ? null : f.owner.key;
231
+ if (f.pending) for (const o of f.pending) {
232
+ o.key = fallback;
233
+ o.life = f.owner.life;
234
+ }
235
+ if (f.roots && f.roots.length > 0) {
236
+ const unique = [...new Set(f.roots)];
237
+ const share = f.spent / unique.length;
238
+ for (const key of unique) bill(key, share);
239
+ } else if (fallback !== null) bill(fallback, f.spent);
240
+ };
241
+ const busy = {
242
+ run(owner, fn, self, args) {
243
+ const t = now();
244
+ const outer = frame;
245
+ if (outer) outer.spent += t - outer.start;
246
+ const f = {
247
+ owner,
248
+ start: t,
249
+ spent: 0,
250
+ parent: outer,
251
+ roots: null,
252
+ pending: null
253
+ };
254
+ frame = f;
255
+ try {
256
+ return fn.apply(self, args);
257
+ } finally {
258
+ const end = now();
259
+ f.spent += end - f.start;
260
+ frame = outer;
261
+ if (outer) outer.start = end;
262
+ settle(f);
263
+ }
264
+ },
265
+ capture() {
266
+ const f = frame;
267
+ if (!f) return {
268
+ key: null,
269
+ life: null
270
+ };
271
+ const o = {
272
+ key: PENDING,
273
+ life: null
274
+ };
275
+ (f.pending ??= []).push(o);
276
+ return o;
277
+ },
278
+ of: (key, life) => ({
279
+ key,
280
+ life: life === void 0 ? lifeOf(key) : life
281
+ }),
282
+ begin(key) {
283
+ const life = {
284
+ key,
285
+ ended: false
286
+ };
287
+ lives.set(key, life);
288
+ return life;
289
+ },
290
+ end(life) {
291
+ life.ended = true;
292
+ if (lives.get(life.key) === life) {
293
+ lives.delete(life.key);
294
+ spent.delete(life.key);
295
+ }
296
+ },
297
+ bind(fn) {
298
+ const owner = busy.capture();
299
+ return (...args) => busy.run(owner, fn, void 0, args);
300
+ },
301
+ report(key, life) {
302
+ const f = frame;
303
+ if (!f) return;
304
+ (f.roots ??= []).push(key);
305
+ if (f.pending) {
306
+ const l = life === void 0 ? lifeOf(key) : life;
307
+ for (const o of f.pending) {
308
+ o.key = key;
309
+ o.life = l;
310
+ }
311
+ f.pending = null;
312
+ }
313
+ },
314
+ take(key) {
315
+ const ms = spent.get(key) ?? 0;
316
+ spent.delete(key);
317
+ return ms;
318
+ },
319
+ claim(container, key) {
320
+ containers.set(container, {
321
+ key,
322
+ life: lifeOf(key)
323
+ });
324
+ },
325
+ keyOf(container) {
326
+ return busy.rootOf(container)?.key ?? null;
327
+ },
328
+ rootOf(container) {
329
+ if (typeof container !== "object" || container === null) return null;
330
+ return containers.get(container) ?? null;
331
+ }
332
+ };
333
+ return busy;
334
+ }
335
+ /** Keeps a wrapper's `name` and `length` the native function's. */
336
+ function like(wrapper, native) {
337
+ Object.defineProperty(wrapper, "name", {
338
+ value: native.name,
339
+ configurable: true
340
+ });
341
+ Object.defineProperty(wrapper, "length", {
342
+ value: native.length,
343
+ configurable: true
344
+ });
345
+ return wrapper;
346
+ }
347
+ /** `f` as a callback, when it is a function: schedulers call any function. */
348
+ function callable(f) {
349
+ return typeof f === "function" ? f : null;
350
+ }
351
+ /**
352
+ * `cb` run as `owner` when the scheduler calls it, with the scheduler's `this`
353
+ * and arguments. Always in a frame, even for nobody: a shared framework's
354
+ * task (React's scheduler port, set up while its module loaded) still splits
355
+ * among the roots it reports. Once the owner's life ended it doesn't run;
356
+ * `stale` gets the scheduler's `this` instead, to stop what would call it
357
+ * again (ADR 0015, decision 9).
358
+ */
359
+ function billed(busy, owner, cb, stale) {
360
+ return function(...args) {
361
+ if (owner.life?.ended === true) {
362
+ stale?.(this);
363
+ return;
364
+ }
365
+ return busy.run(owner, cb, this, args);
366
+ };
367
+ }
368
+ /**
369
+ * Wraps a scheduling function on `scope` so the callback in argument 0 is
370
+ * billed to the owner current at registration. Everything else (the return
371
+ * value, ids, `clear*`, other arguments) is the native's.
372
+ */
373
+ function wrapScheduler(scope, name, busy) {
374
+ const native = Reflect.get(scope, name);
375
+ if (typeof native !== "function") return;
376
+ const clear = name === "setInterval" ? callable(Reflect.get(scope, "clearInterval")) : null;
377
+ const wrapper = like(function(...args) {
378
+ const cb = callable(args[0]);
379
+ let id;
380
+ if (cb) args[0] = billed(busy, busy.capture(), cb, clear ? () => {
381
+ clear.call(scope, id);
382
+ } : void 0);
383
+ const r = Reflect.apply(native, this ?? scope, args);
384
+ id = r;
385
+ return r;
386
+ }, native);
387
+ Reflect.set(scope, name, wrapper);
388
+ }
389
+ /**
390
+ * Wraps `MessagePort`'s `onmessage` and its `message` listeners, so a port
391
+ * a member creates (a scheduler's `MessageChannel`, say) bills its messages
392
+ * to that member. `onmessage` still reads back the function that was set,
393
+ * and `removeEventListener` still removes what `addEventListener` added.
394
+ */
395
+ function wrapPorts(scope, busy) {
396
+ const Port = Reflect.get(scope, "MessagePort");
397
+ if (typeof Port !== "function") return;
398
+ const proto = Reflect.get(Port, "prototype");
399
+ if (typeof proto !== "object" || proto === null) return;
400
+ const close = callable(Reflect.get(proto, "close"));
401
+ const shut = (port) => {
402
+ if (close && typeof port === "object" && port !== null) close.call(port);
403
+ };
404
+ const on = Object.getOwnPropertyDescriptor(proto, "onmessage");
405
+ const get = callable(on ? Reflect.get(on, "get") : void 0);
406
+ const set = callable(on ? Reflect.get(on, "set") : void 0);
407
+ if (on && get && set) {
408
+ /** What each port's `onmessage` was set to, as read back. */
409
+ const assigned = /* @__PURE__ */ new WeakMap();
410
+ Object.defineProperty(proto, "onmessage", {
411
+ configurable: true,
412
+ enumerable: on.enumerable ?? true,
413
+ get: like(function() {
414
+ if (typeof this === "object" && this !== null && assigned.has(this)) return assigned.get(this);
415
+ return get.call(this);
416
+ }, get),
417
+ set: like(function(fn) {
418
+ if (typeof this === "object" && this !== null) assigned.set(this, fn);
419
+ const cb = callable(fn);
420
+ set.call(this, cb ? billed(busy, busy.capture(), cb, shut) : fn);
421
+ }, set)
422
+ });
423
+ }
424
+ const add = callable(Reflect.get(proto, "addEventListener"));
425
+ const remove = callable(Reflect.get(proto, "removeEventListener"));
426
+ if (!add || !remove) return;
427
+ /** Per port, per listener and capture flag: the wrapper `addEventListener` was given. */
428
+ const added = /* @__PURE__ */ new WeakMap();
429
+ Object.defineProperty(proto, "addEventListener", {
430
+ configurable: true,
431
+ writable: true,
432
+ enumerable: true,
433
+ value: like(function(...args) {
434
+ const [type, listener, options] = args;
435
+ if (type !== "message" && type !== "messageerror" || !isListener(listener) || typeof this !== "object" || this === null) return add.apply(this, args);
436
+ const capture = captureOf(options);
437
+ let byListener = added.get(this);
438
+ if (!byListener) added.set(this, byListener = /* @__PURE__ */ new Map());
439
+ let byCapture = byListener.get(listener);
440
+ if (!byCapture) byListener.set(listener, byCapture = /* @__PURE__ */ new Map());
441
+ let wrapper = byCapture.get(capture);
442
+ if (!wrapper) {
443
+ const fn = callable(listener);
444
+ const call = function(e) {
445
+ if (fn) return fn.call(this, e);
446
+ return callable(Reflect.get(listener, "handleEvent"))?.call(listener, e);
447
+ };
448
+ wrapper = billed(busy, busy.capture(), call, shut);
449
+ byCapture.set(capture, wrapper);
450
+ }
451
+ return add.apply(this, [
452
+ type,
453
+ wrapper,
454
+ ...args.slice(2)
455
+ ]);
456
+ }, add)
457
+ });
458
+ Object.defineProperty(proto, "removeEventListener", {
459
+ configurable: true,
460
+ writable: true,
461
+ enumerable: true,
462
+ value: like(function(...args) {
463
+ const [type, listener, options] = args;
464
+ const byCapture = typeof this === "object" && this !== null && isListener(listener) ? added.get(this)?.get(listener) : void 0;
465
+ const capture = captureOf(options);
466
+ const wrapper = byCapture?.get(capture);
467
+ if (!wrapper || type !== "message" && type !== "messageerror") return remove.apply(this, args);
468
+ byCapture?.delete(capture);
469
+ return remove.apply(this, [
470
+ type,
471
+ wrapper,
472
+ ...args.slice(2)
473
+ ]);
474
+ }, remove)
475
+ });
476
+ }
477
+ /**
478
+ * React's devtools hook, the smallest one react-dom accepts (production
479
+ * builds call it too): it reports each committed root's member, and each
480
+ * root whose passive effects just ran, to the current frame.
481
+ */
482
+ function installReactHook(scope, busy) {
483
+ const KEY = "__REACT_DEVTOOLS_GLOBAL_HOOK__";
484
+ if (Reflect.get(scope, KEY) !== void 0) return;
485
+ let renderers = 0;
486
+ const committed = (_renderer, root) => {
487
+ if (typeof root !== "object" || root === null) return;
488
+ const at = busy.rootOf(Reflect.get(root, "containerInfo"));
489
+ if (at !== null) busy.report(at.key, at.life);
490
+ };
491
+ Reflect.set(scope, KEY, {
492
+ supportsFiber: true,
493
+ inject: () => ++renderers,
494
+ onCommitFiberRoot: committed,
495
+ onPostCommitFiberRoot: committed,
496
+ onCommitFiberUnmount: () => {},
497
+ checkDCE: () => {}
498
+ });
499
+ }
500
+ /**
501
+ * Installs attribution on a worker's global, once, before any member loads:
502
+ * the scheduling functions, `MessagePort` listeners and React's hook.
503
+ */
504
+ function installBusy(scope, busy) {
505
+ const q = Reflect.get(scope, "queueMicrotask");
506
+ if (typeof q === "function") nativeQueueMicrotask = (fn) => {
507
+ Reflect.apply(q, scope, [fn]);
508
+ };
509
+ for (const name of SCHEDULERS) wrapScheduler(scope, name, busy);
510
+ wrapPorts(scope, busy);
511
+ installReactHook(scope, busy);
512
+ }
513
+ var PENDING, SCHEDULERS, captureOf, isListener, nativeQueueMicrotask, busy, BUSY;
514
+ var init_busy = __esmMin((() => {
515
+ PENDING = Symbol("pending");
516
+ SCHEDULERS = [
517
+ "setTimeout",
518
+ "setInterval",
519
+ "requestAnimationFrame",
520
+ "queueMicrotask",
521
+ "requestIdleCallback"
522
+ ];
523
+ captureOf = (options) => typeof options === "boolean" ? options : typeof options === "object" && options !== null && Reflect.get(options, "capture") === true;
524
+ isListener = (l) => typeof l === "function" || typeof l === "object" && l !== null && typeof Reflect.get(l, "handleEvent") === "function";
525
+ nativeQueueMicrotask = (fn) => {
526
+ queueMicrotask(fn);
527
+ };
528
+ busy = createBusy();
529
+ BUSY = Symbol.for("isoloop.busy");
530
+ }));
155
531
  // src/freeze.ts
156
532
  init_dist();
533
+ init_busy();
157
534
  /** Constructors whose `prototype` and statics are frozen, if this engine has them. */
158
535
  const NAMES = [
159
536
  "Object",
@@ -198,35 +575,86 @@ const NAMES = [
198
575
  /**
199
576
  * Freezing a prototype makes its data properties read-only, and in strict
200
577
  * code assigning a property of the same name on an instance then throws (the
201
- * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`).
202
- * As Hardened JS does, each data property becomes an accessor whose setter
203
- * defines the property on the instance instead, so overriding still works
204
- * while the prototype itself can't change.
578
+ * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`,
579
+ * or `Object.assign({}, { constructor: x })`). As Hardened JS does, each data
580
+ * property becomes an accessor whose setter defines the property on the
581
+ * instance instead, so overriding still works while the prototype itself
582
+ * can't change.
583
+ *
584
+ * Except the properties V8 guards with "protectors": while they are still the
585
+ * original data properties, V8 keeps fast paths for iteration (`for…of`,
586
+ * spread, destructuring), species lookups and promise resolution. An accessor
587
+ * returning the same function is enough to turn a protector off for the whole
588
+ * worker: array iteration alone made a pool's app code 1.4–2.5× slower
589
+ * (docs/investigations/plant-one-pool.md). These stay plain frozen data, so
590
+ * overriding one of them on an instance throws in strict code instead
591
+ * (ADR 0001, "Override taming without the protected properties").
205
592
  */
593
+ const ITERATOR = Symbol.iterator;
594
+ /** The protected properties, per prototype, that are left as frozen data. */
595
+ function protectedProperties() {
596
+ const out = /* @__PURE__ */ new Map();
597
+ const add = (o, ...keys) => {
598
+ if (typeof o !== "object" && typeof o !== "function" || o === null) return;
599
+ out.set(o, /* @__PURE__ */ new Set([...out.get(o) ?? [], ...keys]));
600
+ };
601
+ const typedArrayCtor = Object.getPrototypeOf(Int8Array);
602
+ const typedArray = typeof typedArrayCtor === "function" ? Reflect.get(typedArrayCtor, "prototype") : void 0;
603
+ add(Array.prototype, ITERATOR, "constructor");
604
+ add(Object.getPrototypeOf([][Symbol.iterator]()), "next");
605
+ add(Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())), ITERATOR);
606
+ add(typedArray, ITERATOR, "constructor");
607
+ for (const c of [
608
+ Int8Array,
609
+ Uint8Array,
610
+ Uint8ClampedArray,
611
+ Int16Array,
612
+ Uint16Array,
613
+ Int32Array,
614
+ Uint32Array,
615
+ Float32Array,
616
+ Float64Array,
617
+ BigInt64Array,
618
+ BigUint64Array
619
+ ]) add(c.prototype, "constructor");
620
+ add(Map.prototype, ITERATOR);
621
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()), "next");
622
+ add(Set.prototype, ITERATOR);
623
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()), "next");
624
+ add(String.prototype, ...Reflect.ownKeys(String.prototype));
625
+ add(Object.getPrototypeOf(""[Symbol.iterator]()), "next");
626
+ add(Promise.prototype, "then", "constructor");
627
+ add(RegExp.prototype, ...Reflect.ownKeys(RegExp.prototype));
628
+ return out;
629
+ }
630
+ let skip;
206
631
  function tameOverrides(proto) {
207
- for (const key of Reflect.ownKeys(proto)) {
208
- const d = Object.getOwnPropertyDescriptor(proto, key);
209
- if (!d || !("value" in d) || !d.configurable) continue;
210
- const value = d.value;
211
- Object.defineProperty(proto, key, {
212
- get() {
213
- return value;
214
- },
215
- set(v) {
216
- if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
217
- if (typeof this !== "object" && typeof this !== "function") return;
218
- if (this === null) return;
219
- Object.defineProperty(this, key, {
220
- value: v,
221
- writable: true,
222
- enumerable: true,
223
- configurable: true
224
- });
225
- },
226
- enumerable: d.enumerable ?? false,
227
- configurable: false
228
- });
229
- }
632
+ skip ??= protectedProperties();
633
+ const keep = skip.get(proto);
634
+ for (const key of Reflect.ownKeys(proto)) if (!keep?.has(key)) tameOverride(proto, key);
635
+ }
636
+ function tameOverride(proto, key) {
637
+ const d = Object.getOwnPropertyDescriptor(proto, key);
638
+ if (!d || !("value" in d) || !d.configurable) return;
639
+ const value = d.value;
640
+ Object.defineProperty(proto, key, {
641
+ get() {
642
+ return value;
643
+ },
644
+ set(v) {
645
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
646
+ if (typeof this !== "object" && typeof this !== "function") return;
647
+ if (this === null) return;
648
+ Object.defineProperty(this, key, {
649
+ value: v,
650
+ writable: true,
651
+ enumerable: true,
652
+ configurable: true
653
+ });
654
+ },
655
+ enumerable: d.enumerable ?? false,
656
+ configurable: false
657
+ });
230
658
  }
231
659
  function hardenProto(proto) {
232
660
  if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
@@ -301,15 +729,19 @@ function createBusClient(first, o = {}) {
301
729
  send(withId);
302
730
  });
303
731
  };
732
+ const committer = createCommitter({
733
+ send: (offsets) => {
734
+ send({
735
+ v: 1,
736
+ t: "commits",
737
+ p: { offsets }
738
+ });
739
+ },
740
+ ...o.commitIntervalMs === void 0 ? {} : { intervalMs: o.commitIntervalMs },
741
+ ...o.credit === void 0 ? {} : { credit: o.credit }
742
+ });
304
743
  const commit = (topic, offset) => {
305
- send({
306
- v: 1,
307
- t: "commit",
308
- p: {
309
- topic,
310
- offset
311
- }
312
- });
744
+ committer.settle(topic, offset);
313
745
  };
314
746
  const drain = async (sub) => {
315
747
  if (sub.running) return;
@@ -319,7 +751,8 @@ function createBusClient(first, o = {}) {
319
751
  if (!r) break;
320
752
  topicOf.set(r, sub.topic);
321
753
  try {
322
- await sub.fn(r);
754
+ const done = sub.fn(r);
755
+ if (isThenable(done)) await done;
323
756
  } catch (err) {
324
757
  sub.stuck = true;
325
758
  o.onError?.(err);
@@ -370,6 +803,7 @@ function createBusClient(first, o = {}) {
370
803
  const sub = subs.get(msg.p.topic);
371
804
  if (!sub) return;
372
805
  sub.queue.length = 0;
806
+ committer.drop(msg.p.topic);
373
807
  try {
374
808
  sub.opts.onReset?.();
375
809
  } catch (err) {
@@ -418,6 +852,7 @@ function createBusClient(first, o = {}) {
418
852
  return () => {
419
853
  if (subs.get(topic.name) !== sub) return;
420
854
  subs.delete(topic.name);
855
+ committer.flush();
421
856
  send({
422
857
  v: 1,
423
858
  t: "unsubscribe",
@@ -493,14 +928,27 @@ function createBusClient(first, o = {}) {
493
928
  value: null
494
929
  });
495
930
  }
931
+ committer.take();
496
932
  for (const sub of subs.values()) {
497
933
  sub.queue.length = 0;
498
934
  sendSubscribe(sub);
499
935
  }
500
936
  for (const p of unanswered) if (p.msg.t !== "subscribe") send(p.msg);
937
+ },
938
+ async close() {
939
+ const offsets = committer.take();
940
+ committer.dispose();
941
+ if (offsets) await call({
942
+ v: 1,
943
+ t: "commits",
944
+ p: { offsets }
945
+ });
501
946
  }
502
947
  };
503
948
  }
949
+ function isThenable(x) {
950
+ return (typeof x === "object" || typeof x === "function") && x !== null && typeof x.then === "function";
951
+ }
504
952
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
505
953
  var init_bus_client = __esmMin((() => {
506
954
  randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
@@ -1805,7 +2253,18 @@ function sharedDom(scope) {
1805
2253
  * `pooled`, the isolate gets its own root in the worker's shared document
1806
2254
  * instead (ADR 0015).
1807
2255
  */
1808
- function createRender(post, scope, pooled = false) {
2256
+ function createRender(post, scope, pooled = false, member = null) {
2257
+ const owner = member === null ? null : busy.of(member);
2258
+ const schedule = (flush) => {
2259
+ if (owner === null || member === null) {
2260
+ queueMicrotask(flush);
2261
+ return;
2262
+ }
2263
+ busy.report(member, owner.life);
2264
+ nativeQueueMicrotask(() => {
2265
+ busy.run(owner, flush, void 0, []);
2266
+ });
2267
+ };
1809
2268
  let pendingStyles = [];
1810
2269
  let pendingHead = [];
1811
2270
  /** Head tags already reported: each goes to the host once. */
@@ -1845,19 +2304,22 @@ function createRender(post, scope, pooled = false) {
1845
2304
  };
1846
2305
  let target;
1847
2306
  if (pooled) {
1848
- const member = sharedDom(scope).addRoot({ onBatch: postPatch });
2307
+ const own = sharedDom(scope).addRoot({
2308
+ onBatch: postPatch,
2309
+ schedule
2310
+ });
1849
2311
  headListeners.add(onHead);
1850
2312
  target = {
1851
- ...member,
2313
+ ...own,
1852
2314
  dispose() {
1853
2315
  headListeners.delete(onHead);
1854
- member.dispose();
2316
+ own.dispose();
1855
2317
  }
1856
2318
  };
1857
2319
  } else {
1858
2320
  const dom = createDom({
1859
2321
  onBatch: postPatch,
1860
- schedule: (flush) => queueMicrotask(flush),
2322
+ schedule,
1861
2323
  onHead
1862
2324
  });
1863
2325
  if (scope) install(dom, scope);
@@ -1924,8 +2386,8 @@ function defineIsolate(def) {
1924
2386
  };
1925
2387
  }
1926
2388
  /** Builds the context for `start(ctx)`. `scope` is the worker global the DOM subset installs on. */
1927
- function createVanillaIsolate(init, post, scope, pooled = false) {
1928
- const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled);
2389
+ function createVanillaIsolate(init, post, scope, pooled = false, member = null) {
2390
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled, member);
1929
2391
  const calls = createHostCalls({
1930
2392
  post,
1931
2393
  beforeCall: () => render?.flush(),
@@ -1936,6 +2398,7 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
1936
2398
  const awake = createKeepAwake();
1937
2399
  const bus = createBusClient(init.busPort, {
1938
2400
  ...init.wake ? { wake: true } : {},
2401
+ ...init.commitIntervalMs === void 0 ? {} : { commitIntervalMs: init.commitIntervalMs },
1939
2402
  onError: (err) => {
1940
2403
  post({
1941
2404
  v: 1,
@@ -1986,6 +2449,15 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
1986
2449
  },
1987
2450
  keepAwake: () => awake.hold()
1988
2451
  };
2452
+ if (member !== null) Object.defineProperty(ctx, BUSY, {
2453
+ value: {
2454
+ claim: (container) => {
2455
+ busy.claim(container, member);
2456
+ },
2457
+ bind: (fn) => busy.bind(fn)
2458
+ },
2459
+ enumerable: false
2460
+ });
1989
2461
  Object.defineProperty(ctx, "portalRoot", {
1990
2462
  enumerable: false,
1991
2463
  get() {
@@ -2022,6 +2494,7 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
2022
2494
  },
2023
2495
  async shutdown(reason) {
2024
2496
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
2497
+ await bus.close();
2025
2498
  render?.flush();
2026
2499
  render?.dispose();
2027
2500
  }
@@ -2031,6 +2504,7 @@ var REQUIRES;
2031
2504
  var init_vanilla = __esmMin((() => {
2032
2505
  init_dist();
2033
2506
  init_bus_client();
2507
+ init_busy();
2034
2508
  init_host_calls();
2035
2509
  init_keep_awake();
2036
2510
  init_worker();
@@ -2039,6 +2513,7 @@ var init_vanilla = __esmMin((() => {
2039
2513
  }));
2040
2514
  // src/bootstrap.ts
2041
2515
  init_dist();
2516
+ init_busy();
2042
2517
  let mode = null;
2043
2518
  const members = /* @__PURE__ */ new Map();
2044
2519
  const postWorker = (msg) => {
@@ -2102,9 +2577,11 @@ function startHeartbeat(everyMs) {
2102
2577
  function shutdownMember(m, graceMs, reason) {
2103
2578
  if (members.get(m.name) === m) members.delete(m.name);
2104
2579
  m.receive = null;
2105
- const done = m.shutdownHook?.(reason) ?? Promise.resolve();
2580
+ const hook = m.shutdownHook;
2581
+ const done = (hook ? busy.run(busy.of(m.name, m.life), hook, void 0, [reason]) : void 0) ?? Promise.resolve();
2106
2582
  const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2107
2583
  Promise.race([done, grace]).finally(() => {
2584
+ busy.end(m.life);
2108
2585
  m.post({
2109
2586
  v: 1,
2110
2587
  t: "bye",
@@ -2118,7 +2595,7 @@ function route(msg) {
2118
2595
  const m = members.get(mode === "pool" ? msg.isolate : void 0);
2119
2596
  if (!m) return;
2120
2597
  if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2121
- else m.receive?.(msg);
2598
+ else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2122
2599
  }
2123
2600
  async function boot(m, init) {
2124
2601
  if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
@@ -2127,7 +2604,13 @@ async function boot(m, init) {
2127
2604
  }
2128
2605
  startHeartbeat(init.heartbeatMs);
2129
2606
  const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
2130
- const runtime = createVanillaIsolate(init, m.post, self, mode === "pool");
2607
+ const runtime = busy.run(busy.of(m.name, m.life), createVanillaIsolate, void 0, [
2608
+ init,
2609
+ m.post,
2610
+ self,
2611
+ mode === "pool",
2612
+ m.name
2613
+ ]);
2131
2614
  let mod;
2132
2615
  try {
2133
2616
  mod = await import(
@@ -2156,7 +2639,10 @@ async function startIsolate(m, runtime, start, requires) {
2156
2639
  runtime.receive(msg);
2157
2640
  };
2158
2641
  m.shutdownHook = (reason) => runtime.shutdown(reason);
2159
- m.idleReport = () => runtime.idle();
2642
+ m.idleReport = () => ({
2643
+ ...runtime.idle(),
2644
+ busyMs: busy.take(m.name)
2645
+ });
2160
2646
  m.post({
2161
2647
  v: 1,
2162
2648
  t: "ready",
@@ -2168,7 +2654,7 @@ async function startIsolate(m, runtime, start, requires) {
2168
2654
  }
2169
2655
  });
2170
2656
  try {
2171
- await start(runtime.ctx);
2657
+ await busy.run(busy.of(m.name, m.life), start, void 0, [runtime.ctx]);
2172
2658
  } catch (err) {
2173
2659
  fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
2174
2660
  }
@@ -2191,6 +2677,7 @@ function onMessage(e) {
2191
2677
  if (members.has(name)) return;
2192
2678
  const m = {
2193
2679
  name,
2680
+ life: busy.begin(name),
2194
2681
  post: memberPost(name),
2195
2682
  shutdownHook: null,
2196
2683
  idleReport: null,
@@ -2203,6 +2690,7 @@ function onMessage(e) {
2203
2690
  }
2204
2691
  const STARTED = Symbol.for("isoloop.bootstrap");
2205
2692
  function startOnce() {
2693
+ installBusy(self, busy);
2206
2694
  self.addEventListener("message", onMessage);
2207
2695
  }
2208
2696
  if (Reflect.get(self, STARTED) === true) {