@isoloop/runtime 0.0.0-next.5bbb503 → 0.0.0-next.f57e259

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
@@ -20,11 +20,12 @@ var __exportAll = (all, no_symbols) => {
20
20
  // ../protocol/dist/index.js
21
21
  /**
22
22
  * True for a well-formed envelope this build can read: `v` is a supported
23
- * version, `t` is a string, `id`/`re` are absent or strings, and `p` is present.
23
+ * version, `t` is a string, `id`/`re`/`isolate` are absent or strings, and `p`
24
+ * is present.
24
25
  * Says nothing about whether `t` is known; see the per-port guards.
25
26
  */
26
27
  function isEnvelope(x) {
27
- return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]);
28
+ return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
28
29
  }
29
30
  /**
30
31
  * Builds a guard for one port's union from its message types. Each side drops
@@ -151,6 +152,117 @@ var init_dist = __esmMin((() => {
151
152
  retention: { kind: "compacted" }
152
153
  });
153
154
  }));
155
+ // src/freeze.ts
156
+ init_dist();
157
+ /** Constructors whose `prototype` and statics are frozen, if this engine has them. */
158
+ const NAMES = [
159
+ "Object",
160
+ "Function",
161
+ "Array",
162
+ "String",
163
+ "Number",
164
+ "Boolean",
165
+ "Symbol",
166
+ "BigInt",
167
+ "Date",
168
+ "RegExp",
169
+ "Error",
170
+ "EvalError",
171
+ "RangeError",
172
+ "ReferenceError",
173
+ "SyntaxError",
174
+ "TypeError",
175
+ "URIError",
176
+ "AggregateError",
177
+ "Promise",
178
+ "Map",
179
+ "Set",
180
+ "WeakMap",
181
+ "WeakSet",
182
+ "WeakRef",
183
+ "FinalizationRegistry",
184
+ "ArrayBuffer",
185
+ "DataView",
186
+ "Int8Array",
187
+ "Uint8Array",
188
+ "Uint8ClampedArray",
189
+ "Int16Array",
190
+ "Uint16Array",
191
+ "Int32Array",
192
+ "Uint32Array",
193
+ "Float32Array",
194
+ "Float64Array",
195
+ "BigInt64Array",
196
+ "BigUint64Array"
197
+ ];
198
+ /**
199
+ * Freezing a prototype makes its data properties read-only, and in strict
200
+ * 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.
205
+ */
206
+ 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
+ }
230
+ }
231
+ function hardenProto(proto) {
232
+ if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
233
+ if (Object.isFrozen(proto)) return;
234
+ tameOverrides(proto);
235
+ Object.freeze(proto);
236
+ }
237
+ function freezeWithPrototype(c) {
238
+ if (typeof c !== "function") return;
239
+ hardenProto(Reflect.get(c, "prototype"));
240
+ if (c !== Error) Object.freeze(c);
241
+ }
242
+ /** Freezes the shared intrinsics. Call once, before any member module loads. */
243
+ function freezeBuiltins() {
244
+ const g = globalThis;
245
+ for (const name of NAMES) freezeWithPrototype(Reflect.get(g, name));
246
+ freezeWithPrototype(Object.getPrototypeOf(Int8Array));
247
+ const protos = [
248
+ Object.getPrototypeOf([][Symbol.iterator]()),
249
+ Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())),
250
+ Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()),
251
+ Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()),
252
+ Object.getPrototypeOf(""[Symbol.iterator]()),
253
+ Object.getPrototypeOf(function* () {}),
254
+ Object.getPrototypeOf(async function() {}),
255
+ Object.getPrototypeOf(async function* () {})
256
+ ];
257
+ for (const p of protos) {
258
+ if (typeof p !== "object" && typeof p !== "function" || p === null) continue;
259
+ hardenProto(Reflect.get(p, "prototype"));
260
+ hardenProto(p);
261
+ }
262
+ Object.freeze(Math);
263
+ Object.freeze(JSON);
264
+ Object.freeze(Reflect);
265
+ }
154
266
  // src/bus-client.ts
155
267
  function createBusClient(first, o = {}) {
156
268
  const limit = o.inboxLimit ?? 1e3;
@@ -391,7 +503,6 @@ function createBusClient(first, o = {}) {
391
503
  }
392
504
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
393
505
  var init_bus_client = __esmMin((() => {
394
- init_dist();
395
506
  randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
396
507
  check = (r) => {
397
508
  if (!r.ok) throw new BusError(r.error);
@@ -516,7 +627,7 @@ var ISOLOOP_DOM_FMT;
516
627
  var init_records_wVZrPpqr = __esmMin((() => {
517
628
  ISOLOOP_DOM_FMT = "isoloop-dom@1";
518
629
  }));
519
- // ../dom/dist/dom-7EzPoV0N.js
630
+ // ../dom/dist/dom-yLsf0Z4e.js
520
631
  function createStyle(el) {
521
632
  const decls = /* @__PURE__ */ new Map();
522
633
  const write = () => {
@@ -643,75 +754,124 @@ function serialize(n) {
643
754
  children: n.childNodes.map(serialize)
644
755
  };
645
756
  }
646
- function learn(n, core) {
757
+ /** Whether `n` or anything under it was rendered under a root other than `owner`. */
758
+ function ownedElsewhere(n, owner) {
759
+ if (n.isoOwner && n.isoOwner !== owner) return true;
760
+ return !n.isoKnown && n.childNodes.some((c) => ownedElsewhere(c, owner));
761
+ }
762
+ function learn(n, core, owner) {
647
763
  n.isoKnown = true;
764
+ n.isoOwner = owner;
648
765
  core.known.set(n.isoId, n);
649
- for (const c of n.childNodes) learn(c, core);
766
+ for (const c of n.childNodes) learn(c, core, owner);
650
767
  }
651
768
  function forget(n, core) {
652
769
  n.isoKnown = false;
653
770
  core.known.delete(n.isoId);
654
771
  for (const c of n.childNodes) forget(c, core);
655
772
  }
656
- function createDom(opts) {
657
- const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
773
+ function setValueOf(node, value, o) {
774
+ if (!isControl(node)) throw new TypeError("setValue: not an input, textarea or select");
775
+ if (!o.force) {
776
+ node.value = value;
777
+ return;
778
+ }
779
+ node.isoSetProp("value", value, false);
780
+ if (node.isoKnown) emit(node, [
781
+ "prop",
782
+ node.isoWire,
783
+ "value",
784
+ value,
785
+ true
786
+ ]);
787
+ }
788
+ function deliverTo(node, event) {
789
+ if (!node) return;
790
+ if (isControl(node) && event.value !== void 0) node.isoSetProp("value", event.value, false);
791
+ if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
792
+ if (event.type === "scroll" && node instanceof WElement) node.isoScroll = {
793
+ top: event.scrollTop ?? 0,
794
+ left: event.scrollLeft ?? 0
795
+ };
796
+ node.dispatchEvent(toEvent(event));
797
+ }
798
+ /** A root's recorder: records batched per microtask (or `schedule`) into `onBatch`. */
799
+ function recorder(root, onBatch, schedule) {
658
800
  let pending = [];
659
801
  let scheduled = false;
802
+ let live = true;
660
803
  const flush = () => {
661
804
  scheduled = false;
662
805
  if (pending.length === 0) return;
663
806
  const batch = pending;
664
807
  pending = [];
665
- opts.onBatch(batch);
808
+ if (live) onBatch(batch);
666
809
  };
810
+ return {
811
+ owner: {
812
+ root,
813
+ push(r) {
814
+ if (!live) return;
815
+ pending.push(r);
816
+ if (!scheduled) {
817
+ scheduled = true;
818
+ schedule(flush);
819
+ }
820
+ }
821
+ },
822
+ flush,
823
+ stop: () => {
824
+ live = false;
825
+ pending = [];
826
+ }
827
+ };
828
+ }
829
+ function createDom(opts) {
830
+ const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
667
831
  const core = {
668
- root: null,
832
+ roots: /* @__PURE__ */ new Set(),
669
833
  nextId: 1,
670
834
  known: /* @__PURE__ */ new Map(),
671
- onHead: opts.onHead ?? (() => {}),
672
- record(r) {
673
- pending.push(r);
674
- if (!scheduled) {
675
- scheduled = true;
676
- schedule(flush);
677
- }
678
- }
835
+ onHead: opts.onHead ?? (() => {})
679
836
  };
680
837
  const document = new WDocument(core);
681
- const root = new WHTMLElement(document, 0, "iso-root", "html");
682
- root.isoKnown = true;
683
- core.known.set(0, root);
684
- core.root = root;
838
+ const makeRoot = (id) => {
839
+ const root = new WHTMLElement(document, id, "iso-root", "html");
840
+ root.isoKnown = true;
841
+ core.known.set(id, root);
842
+ core.roots.add(root);
843
+ return root;
844
+ };
845
+ const root = makeRoot(0);
846
+ const main = recorder(root, (b) => opts.onBatch(b), schedule);
847
+ root.isoOwner = main.owner;
685
848
  return {
686
849
  document,
687
850
  root,
688
- flush,
851
+ flush: main.flush,
689
852
  idOf: (node) => node.isoId,
690
- setValue(node, value, o = {}) {
691
- if (!(node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement)) throw new TypeError("setValue: not an input, textarea or select");
692
- if (!o.force) {
693
- node.value = value;
694
- return;
695
- }
696
- node.isoSetProp("value", value, false);
697
- if (node.isoKnown) core.record([
698
- "prop",
699
- node.isoId,
700
- "value",
701
- value,
702
- true
703
- ]);
704
- },
705
- deliver(event) {
706
- const node = core.known.get(event.target);
707
- if (!node) return;
708
- if ((node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement) && event.value !== void 0) node.isoSetProp("value", event.value, false);
709
- if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
710
- if (event.type === "scroll" && node instanceof WElement) node.isoScroll = {
711
- top: event.scrollTop ?? 0,
712
- left: event.scrollLeft ?? 0
853
+ setValue: (node, value, o = {}) => setValueOf(node, value, o),
854
+ deliver: (event) => deliverTo(core.known.get(event.target), event),
855
+ addRoot(o) {
856
+ const member = makeRoot(core.nextId++);
857
+ const rec = recorder(member, (b) => o.onBatch(b), o.schedule ?? schedule);
858
+ member.isoOwner = rec.owner;
859
+ const mine = (node) => node?.isoKnown && node.isoOwner === rec.owner ? node : void 0;
860
+ return {
861
+ root: member,
862
+ flush: rec.flush,
863
+ idOf: (node) => mine(node) ? node.isoWire : void 0,
864
+ setValue(node, value, so = {}) {
865
+ if (node.isoOwner && node.isoOwner !== rec.owner) throw new TypeError("setValue: not a node of this member's root");
866
+ setValueOf(node, value, so);
867
+ },
868
+ deliver: (event) => deliverTo(mine(event.target === 0 ? member : core.known.get(event.target)), event),
869
+ dispose() {
870
+ rec.stop();
871
+ core.roots.delete(member);
872
+ forget(member, core);
873
+ }
713
874
  };
714
- node.dispatchEvent(toEvent(event));
715
875
  }
716
876
  };
717
877
  }
@@ -743,8 +903,8 @@ function toEvent(e) {
743
903
  });
744
904
  return ev;
745
905
  }
746
- var HTML_NS, SVG_NS, str, domError, WEventTarget, WNode, WCharacterData, WText, WComment, kebab, WDOMTokenList, dataAttr, dataKey, WParentNode, WDocumentFragment, WElement, HANDLER_EVENTS, WHTMLElement, WSVGElement, WHTMLIFrameElement, WHTMLInputElement, WHTMLTextAreaElement, WHTMLSelectElement, WHTMLOptionElement, HTML_CLASSES, WDocument;
747
- var init_dom_7EzPoV0N = __esmMin((() => {
906
+ var HTML_NS, SVG_NS, str, domError, emit, WEventTarget, WNode, WCharacterData, WText, WComment, kebab, WDOMTokenList, dataAttr, dataKey, WParentNode, WDocumentFragment, WElement, HANDLER_EVENTS, WHTMLElement, WSVGElement, WHTMLIFrameElement, WHTMLInputElement, WHTMLTextAreaElement, WHTMLSelectElement, WHTMLOptionElement, HTML_CLASSES, WDocument, isControl;
907
+ var init_dom_yLsf0Z4e = __esmMin((() => {
748
908
  HTML_NS = "http://www.w3.org/1999/xhtml";
749
909
  SVG_NS = "http://www.w3.org/2000/svg";
750
910
  str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : "";
@@ -753,6 +913,9 @@ var init_dom_7EzPoV0N = __esmMin((() => {
753
913
  e.name = name;
754
914
  return e;
755
915
  };
916
+ emit = (n, r) => {
917
+ n.isoOwner?.push(r);
918
+ };
756
919
  WEventTarget = class {
757
920
  /** @internal */ isoListeners = /* @__PURE__ */ new Map();
758
921
  /** @internal */ isoParentTarget() {
@@ -895,6 +1058,12 @@ var init_dom_7EzPoV0N = __esmMin((() => {
895
1058
  /** @internal */ isoNext = null;
896
1059
  /** @internal Whether the host knows this node (it's in the tree under the root). */
897
1060
  isoKnown = false;
1061
+ /**
1062
+ * @internal The root this node was rendered under, once it has been. Kept
1063
+ * after the node leaves the tree, so it can't move to another member's root
1064
+ * in a pool (ADR 0015, decision 3).
1065
+ */
1066
+ isoOwner = null;
898
1067
  constructor(doc, id) {
899
1068
  super();
900
1069
  this.ownerDocument = doc;
@@ -903,10 +1072,17 @@ var init_dom_7EzPoV0N = __esmMin((() => {
903
1072
  /** @internal */ isoParentTarget() {
904
1073
  return this.isoParent;
905
1074
  }
1075
+ /**
1076
+ * @internal The id the host knows this node by: a render root is always
1077
+ * `ROOT_ID` to its own surface, whatever its id in the document.
1078
+ */
1079
+ get isoWire() {
1080
+ return this.isoOwner?.root === this ? 0 : this.isoId;
1081
+ }
906
1082
  /** @internal */ isoListenChanged(type, on) {
907
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1083
+ if (this.isoKnown) emit(this, [
908
1084
  "listen",
909
- this.isoId,
1085
+ this.isoWire,
910
1086
  type,
911
1087
  on
912
1088
  ]);
@@ -959,9 +1135,9 @@ var init_dom_7EzPoV0N = __esmMin((() => {
959
1135
  const data = str(v);
960
1136
  if (data === this.isoData) return;
961
1137
  this.isoData = data;
962
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1138
+ if (this.isoKnown) emit(this, [
963
1139
  "text",
964
- this.isoId,
1140
+ this.isoWire,
965
1141
  data
966
1142
  ]);
967
1143
  }
@@ -1096,27 +1272,28 @@ var init_dom_7EzPoV0N = __esmMin((() => {
1096
1272
  return child;
1097
1273
  }
1098
1274
  if (this.ownerDocument.head === this && child instanceof WElement) this.ownerDocument.isoCore.onHead(child.localName);
1275
+ if (this.isoKnown && ownedElsewhere(child, this.isoOwner)) throw domError("HierarchyRequestError", "insertBefore: a node can't move to another member's root in a pool");
1099
1276
  const wasKnown = child.isoKnown;
1100
1277
  child.isoParent?.isoUnlink(child);
1101
1278
  this.isoLink(child, ref);
1102
1279
  const core = this.ownerDocument.isoCore;
1103
- if (wasKnown && this.isoKnown) core.record([
1280
+ if (wasKnown && this.isoKnown) emit(this, [
1104
1281
  "move",
1105
- this.isoId,
1282
+ this.isoWire,
1106
1283
  child.isoId,
1107
1284
  ref?.isoId ?? null
1108
1285
  ]);
1109
1286
  else if (wasKnown) {
1110
- core.record(["remove", child.isoId]);
1287
+ emit(child, ["remove", child.isoId]);
1111
1288
  forget(child, core);
1112
1289
  } else if (this.isoKnown) {
1113
- core.record([
1290
+ emit(this, [
1114
1291
  "insert",
1115
- this.isoId,
1292
+ this.isoWire,
1116
1293
  serialize(child),
1117
1294
  ref?.isoId ?? null
1118
1295
  ]);
1119
- learn(child, core);
1296
+ learn(child, core, this.isoOwner);
1120
1297
  }
1121
1298
  return child;
1122
1299
  }
@@ -1124,9 +1301,8 @@ var init_dom_7EzPoV0N = __esmMin((() => {
1124
1301
  if (child.isoParent !== this) throw domError("NotFoundError", "removeChild: not a child");
1125
1302
  this.isoUnlink(child);
1126
1303
  if (child.isoKnown) {
1127
- const core = this.ownerDocument.isoCore;
1128
- core.record(["remove", child.isoId]);
1129
- forget(child, core);
1304
+ emit(child, ["remove", child.isoId]);
1305
+ forget(child, this.ownerDocument.isoCore);
1130
1306
  }
1131
1307
  return child;
1132
1308
  }
@@ -1214,9 +1390,9 @@ var init_dom_7EzPoV0N = __esmMin((() => {
1214
1390
  const v = str(value);
1215
1391
  if (this.isoAttrs.get(n) === v) return;
1216
1392
  this.isoAttrs.set(n, v);
1217
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1393
+ if (this.isoKnown) emit(this, [
1218
1394
  "attr",
1219
- this.isoId,
1395
+ this.isoWire,
1220
1396
  n,
1221
1397
  v
1222
1398
  ]);
@@ -1224,9 +1400,9 @@ var init_dom_7EzPoV0N = __esmMin((() => {
1224
1400
  removeAttribute(name) {
1225
1401
  const n = this.isoAttrName(name);
1226
1402
  if (!this.isoAttrs.delete(n)) return;
1227
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1403
+ if (this.isoKnown) emit(this, [
1228
1404
  "attr",
1229
- this.isoId,
1405
+ this.isoWire,
1230
1406
  n,
1231
1407
  null
1232
1408
  ]);
@@ -1266,9 +1442,9 @@ var init_dom_7EzPoV0N = __esmMin((() => {
1266
1442
  /** @internal */ isoSetProp(name, value, record) {
1267
1443
  if (this.isoProps.get(name) === value) return;
1268
1444
  this.isoProps.set(name, value);
1269
- if (record && this.isoKnown) this.ownerDocument.isoCore.record([
1445
+ if (record && this.isoKnown) emit(this, [
1270
1446
  "prop",
1271
- this.isoId,
1447
+ this.isoWire,
1272
1448
  name,
1273
1449
  value
1274
1450
  ]);
@@ -1525,8 +1701,11 @@ var init_dom_7EzPoV0N = __esmMin((() => {
1525
1701
  }
1526
1702
  return null;
1527
1703
  };
1528
- const root = this.isoCore.root;
1529
- return (root ? walk(root) : null) ?? walk(this.head);
1704
+ for (const root of this.isoCore.roots) {
1705
+ const hit = walk(root);
1706
+ if (hit) return hit;
1707
+ }
1708
+ return walk(this.head);
1530
1709
  }
1531
1710
  /**
1532
1711
  * Type selectors only, alone or as a `head > title` child chain: what React
@@ -1561,8 +1740,9 @@ var init_dom_7EzPoV0N = __esmMin((() => {
1561
1740
  }
1562
1741
  };
1563
1742
  defineHandlers(WDocument.prototype);
1743
+ isControl = (node) => node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement;
1564
1744
  }));
1565
- // ../dom/dist/install-DE1VIvyG.js
1745
+ // ../dom/dist/install-D7m7By8i.js
1566
1746
  /**
1567
1747
  * Exposes `dom` as the worker's `document`, `window` and DOM classes, so
1568
1748
  * frameworks find them where they look. Only for isolates with a surface; a
@@ -1582,8 +1762,8 @@ function install(dom, scope) {
1582
1762
  dom.document.defaultView = scope;
1583
1763
  }
1584
1764
  var DOM_GLOBALS;
1585
- var init_install_DE1VIvyG = __esmMin((() => {
1586
- init_dom_7EzPoV0N();
1765
+ var init_install_D7m7By8i = __esmMin((() => {
1766
+ init_dom_yLsf0Z4e();
1587
1767
  DOM_GLOBALS = {
1588
1768
  Node: WNode,
1589
1769
  Element: WElement,
@@ -1603,15 +1783,29 @@ var init_install_DE1VIvyG = __esmMin((() => {
1603
1783
  // ../dom/dist/worker.js
1604
1784
  var init_worker = __esmMin((() => {
1605
1785
  init_records_wVZrPpqr();
1606
- init_dom_7EzPoV0N();
1607
- init_install_DE1VIvyG();
1786
+ init_dom_yLsf0Z4e();
1787
+ init_install_D7m7By8i();
1608
1788
  }));
1609
1789
  // src/render/index.ts
1790
+ function sharedDom(scope) {
1791
+ if (!shared) {
1792
+ shared = createDom({
1793
+ onBatch: () => {},
1794
+ onHead: (tag) => {
1795
+ for (const fn of headListeners) fn(tag);
1796
+ }
1797
+ });
1798
+ if (scope) install(shared, scope);
1799
+ }
1800
+ return shared;
1801
+ }
1610
1802
  /**
1611
1803
  * Builds the DOM subset and posts its batches. With `scope`, also installs it
1612
- * as that global's `document` and DOM classes, which frameworks need.
1804
+ * as that global's `document` and DOM classes, which frameworks need. With
1805
+ * `pooled`, the isolate gets its own root in the worker's shared document
1806
+ * instead (ADR 0015).
1613
1807
  */
1614
- function createRender(post, scope) {
1808
+ function createRender(post, scope, pooled = false) {
1615
1809
  let pendingStyles = [];
1616
1810
  let pendingHead = [];
1617
1811
  /** Head tags already reported: each goes to the host once. */
@@ -1639,47 +1833,77 @@ function createRender(post, scope) {
1639
1833
  extrasScheduled = true;
1640
1834
  queueMicrotask(() => {
1641
1835
  extrasScheduled = false;
1642
- dom.flush();
1836
+ target.flush();
1643
1837
  if (pendingStyles.length > 0 || pendingHead.length > 0) postPatch([]);
1644
1838
  });
1645
1839
  };
1646
- const dom = createDom({
1647
- onBatch: postPatch,
1648
- schedule: (flush) => queueMicrotask(flush),
1649
- onHead(tag) {
1650
- if (headSeen.has(tag)) return;
1651
- headSeen.add(tag);
1652
- pendingHead.push(tag);
1653
- scheduleExtras();
1654
- }
1655
- });
1656
- if (scope) install(dom, scope);
1840
+ const onHead = (tag) => {
1841
+ if (headSeen.has(tag)) return;
1842
+ headSeen.add(tag);
1843
+ pendingHead.push(tag);
1844
+ scheduleExtras();
1845
+ };
1846
+ let target;
1847
+ if (pooled) {
1848
+ const member = sharedDom(scope).addRoot({ onBatch: postPatch });
1849
+ headListeners.add(onHead);
1850
+ target = {
1851
+ ...member,
1852
+ dispose() {
1853
+ headListeners.delete(onHead);
1854
+ member.dispose();
1855
+ }
1856
+ };
1857
+ } else {
1858
+ const dom = createDom({
1859
+ onBatch: postPatch,
1860
+ schedule: (flush) => queueMicrotask(flush),
1861
+ onHead
1862
+ });
1863
+ if (scope) install(dom, scope);
1864
+ target = {
1865
+ root: dom.root,
1866
+ flush: () => dom.flush(),
1867
+ deliver: (event) => dom.deliver(event),
1868
+ idOf: (node) => node.isConnected ? dom.idOf(node) : void 0,
1869
+ setValue: (node, value, o) => dom.setValue(node, value, o),
1870
+ dispose: () => {}
1871
+ };
1872
+ }
1657
1873
  return {
1658
1874
  fmt: ISOLOOP_DOM_FMT,
1659
- root: dom.root,
1660
- dom,
1875
+ root: target.root,
1876
+ flush: () => target.flush(),
1877
+ setValue: (node, value, o) => target.setValue(node, value, o),
1878
+ dispose: () => target.dispose(),
1661
1879
  styles(css) {
1662
1880
  pendingStyles.push(...typeof css === "string" ? [css] : css);
1663
1881
  scheduleExtras();
1664
1882
  },
1665
- idOf: (node) => node instanceof WNode && node.isConnected ? String(dom.idOf(node)) : void 0,
1883
+ idOf(node) {
1884
+ if (!(node instanceof WNode)) return void 0;
1885
+ const id = target.idOf(node);
1886
+ return id === void 0 ? void 0 : String(id);
1887
+ },
1666
1888
  receive(e) {
1667
- const target = nodeId(e.target);
1668
- if (target === void 0) return;
1889
+ const t = nodeId(e.target);
1890
+ if (t === void 0) return;
1669
1891
  const currentTargets = e.currentTargets.map(nodeId).filter((n) => n !== void 0);
1670
1892
  const { target: _t, currentTargets: _c, ...rest } = e;
1671
- dom.deliver({
1893
+ target.deliver({
1672
1894
  ...rest,
1673
- target,
1895
+ target: t,
1674
1896
  currentTargets
1675
1897
  });
1676
1898
  }
1677
1899
  };
1678
1900
  }
1679
- var nodeId;
1901
+ var nodeId, shared, headListeners;
1680
1902
  var init_render = __esmMin((() => {
1681
1903
  init_worker();
1682
1904
  nodeId = (s) => /^\d+$/.test(s) ? Number(s) : void 0;
1905
+ shared = null;
1906
+ headListeners = /* @__PURE__ */ new Set();
1683
1907
  }));
1684
1908
  // package.json
1685
1909
  var version = "0.0.0";
@@ -1700,11 +1924,11 @@ function defineIsolate(def) {
1700
1924
  };
1701
1925
  }
1702
1926
  /** Builds the context for `start(ctx)`. `scope` is the worker global the DOM subset installs on. */
1703
- function createVanillaIsolate(init, post, scope) {
1704
- const render = init.renderFmt === "none" ? null : createRender(post, scope);
1927
+ function createVanillaIsolate(init, post, scope, pooled = false) {
1928
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled);
1705
1929
  const calls = createHostCalls({
1706
1930
  post,
1707
- beforeCall: () => render?.dom.flush(),
1931
+ beforeCall: () => render?.flush(),
1708
1932
  idOf: (node) => render ? render.idOf(node) : void 0,
1709
1933
  surface: render !== null,
1710
1934
  navigate: init.grants.navigate === true
@@ -1728,24 +1952,58 @@ function createVanillaIsolate(init, post, scope) {
1728
1952
  }
1729
1953
  });
1730
1954
  const onShutdown = [];
1731
- return {
1732
- ctx: {
1733
- id: init.isolateId,
1734
- config: init.config,
1735
- root: render?.root,
1736
- host: calls.api,
1737
- bus: bus.client,
1738
- styles: (css) => render?.styles(css),
1739
- setValue(node, value, o) {
1740
- if (!render) return;
1741
- if (!(node instanceof WNode)) throw new TypeError("setValue: not a node of this isolate");
1742
- render.dom.setValue(node, value, o);
1743
- },
1744
- onShutdown: (fn) => {
1745
- onShutdown.push(fn);
1746
- },
1747
- keepAwake: () => awake.hold()
1955
+ let portal;
1956
+ const ctx = {
1957
+ id: init.isolateId,
1958
+ config: init.config,
1959
+ root: render?.root,
1960
+ portalRoot: void 0,
1961
+ reportError(error, o = {}) {
1962
+ const fatal = o.fatal ?? true;
1963
+ post({
1964
+ v: 1,
1965
+ t: "error",
1966
+ p: error instanceof Error ? {
1967
+ message: error.message,
1968
+ ...error.stack === void 0 ? {} : { stack: error.stack },
1969
+ fatal
1970
+ } : {
1971
+ message: String(error),
1972
+ fatal
1973
+ }
1974
+ });
1975
+ },
1976
+ host: calls.api,
1977
+ bus: bus.client,
1978
+ styles: (css) => render?.styles(css),
1979
+ setValue(node, value, o) {
1980
+ if (!render) return;
1981
+ if (!(node instanceof WNode)) throw new TypeError("setValue: not a node of this isolate");
1982
+ render.setValue(node, value, o);
1748
1983
  },
1984
+ onShutdown: (fn) => {
1985
+ onShutdown.push(fn);
1986
+ },
1987
+ keepAwake: () => awake.hold()
1988
+ };
1989
+ Object.defineProperty(ctx, "portalRoot", {
1990
+ enumerable: false,
1991
+ get() {
1992
+ if (!render) return void 0;
1993
+ if (!portal) {
1994
+ const { root } = render;
1995
+ const div = root.ownerDocument.createElement("div");
1996
+ div.setAttribute("data-isoloop-portal", "");
1997
+ queueMicrotask(() => {
1998
+ if (div.parentNode !== root) root.appendChild(div);
1999
+ });
2000
+ portal = div;
2001
+ }
2002
+ return portal;
2003
+ }
2004
+ });
2005
+ return {
2006
+ ctx,
1749
2007
  renderFmt: render ? render.fmt : "none",
1750
2008
  receive(msg) {
1751
2009
  if (isHostToIsolate(msg)) {
@@ -1764,7 +2022,8 @@ function createVanillaIsolate(init, post, scope) {
1764
2022
  },
1765
2023
  async shutdown(reason) {
1766
2024
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
1767
- render?.dom.flush();
2025
+ render?.flush();
2026
+ render?.dispose();
1768
2027
  }
1769
2028
  };
1770
2029
  }
@@ -1780,11 +2039,19 @@ var init_vanilla = __esmMin((() => {
1780
2039
  }));
1781
2040
  // src/bootstrap.ts
1782
2041
  init_dist();
1783
- const post = (msg) => {
2042
+ let mode = null;
2043
+ const members = /* @__PURE__ */ new Map();
2044
+ const postWorker = (msg) => {
1784
2045
  self.postMessage(msg);
1785
2046
  };
1786
- const fatal = (message, code) => {
1787
- post({
2047
+ const memberPost = (name) => (msg) => {
2048
+ self.postMessage(name === void 0 ? msg : {
2049
+ ...msg,
2050
+ isolate: name
2051
+ });
2052
+ };
2053
+ const fatal = (m, message, code) => {
2054
+ m.post({
1788
2055
  v: 1,
1789
2056
  t: "error",
1790
2057
  p: code ? {
@@ -1797,46 +2064,70 @@ const fatal = (message, code) => {
1797
2064
  }
1798
2065
  });
1799
2066
  };
1800
- /** Set once the isolate has started: what the beat reports for suspension (ADR 0001). */
1801
- let idleReport = null;
2067
+ let beating = false;
2068
+ /** Once per worker, after the first isolate's protocol check. */
1802
2069
  function startHeartbeat(everyMs) {
2070
+ if (beating) return;
2071
+ beating = true;
1803
2072
  let last = performance.now();
1804
2073
  setInterval(() => {
1805
2074
  const now = performance.now();
1806
2075
  const lagMs = Math.max(0, now - last - everyMs);
1807
- post({
1808
- v: 1,
1809
- t: "beat",
1810
- p: idleReport ? {
1811
- lagMs,
1812
- idle: idleReport()
1813
- } : { lagMs }
1814
- });
2076
+ if (mode === "pool") {
2077
+ const reports = {};
2078
+ for (const m of members.values()) if (m.name !== void 0 && m.idleReport) reports[m.name] = m.idleReport();
2079
+ postWorker({
2080
+ v: 1,
2081
+ t: "beat",
2082
+ p: {
2083
+ lagMs,
2084
+ members: reports
2085
+ }
2086
+ });
2087
+ } else {
2088
+ const idle = members.get(void 0)?.idleReport?.();
2089
+ postWorker({
2090
+ v: 1,
2091
+ t: "beat",
2092
+ p: idle ? {
2093
+ lagMs,
2094
+ idle
2095
+ } : { lagMs }
2096
+ });
2097
+ }
1815
2098
  last = now;
1816
2099
  }, everyMs);
1817
2100
  }
1818
- async function boot(init) {
2101
+ /** `shutdown` for a member: `bye` once its handlers settle or the grace runs out. */
2102
+ function shutdownMember(m, graceMs, reason) {
2103
+ if (members.get(m.name) === m) members.delete(m.name);
2104
+ m.receive = null;
2105
+ const done = m.shutdownHook?.(reason) ?? Promise.resolve();
2106
+ const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2107
+ Promise.race([done, grace]).finally(() => {
2108
+ m.post({
2109
+ v: 1,
2110
+ t: "bye",
2111
+ p: {}
2112
+ });
2113
+ if (members.size === 0) self.close();
2114
+ });
2115
+ }
2116
+ /** Routes one message from the host to the member it is for. */
2117
+ function route(msg) {
2118
+ const m = members.get(mode === "pool" ? msg.isolate : void 0);
2119
+ if (!m) return;
2120
+ if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2121
+ else m.receive?.(msg);
2122
+ }
2123
+ async function boot(m, init) {
1819
2124
  if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
1820
- fatal(`Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
2125
+ fatal(m, `Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
1821
2126
  return;
1822
2127
  }
1823
- self.addEventListener("message", (e) => {
1824
- const msg = e.data;
1825
- if (!isHostToIsolate(msg) || msg.t !== "shutdown") return;
1826
- const done = shutdownHook?.(msg.p.reason) ?? Promise.resolve();
1827
- const grace = new Promise((r) => setTimeout(r, Math.max(0, msg.p.graceMs - 50)));
1828
- Promise.race([done, grace]).finally(() => {
1829
- post({
1830
- v: 1,
1831
- t: "bye",
1832
- p: {}
1833
- });
1834
- self.close();
1835
- });
1836
- });
1837
2128
  startHeartbeat(init.heartbeatMs);
1838
2129
  const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
1839
- const runtime = createVanillaIsolate(init, post, self);
2130
+ const runtime = createVanillaIsolate(init, m.post, self, mode === "pool");
1840
2131
  let mod;
1841
2132
  try {
1842
2133
  mod = await import(
@@ -1846,7 +2137,7 @@ async function boot(init) {
1846
2137
  } catch (err) {
1847
2138
  const why = err instanceof Error ? err.message : String(err);
1848
2139
  const cross = new URL(init.src).origin !== self.location.origin;
1849
- fatal(`Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
2140
+ fatal(m, `Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
1850
2141
  return;
1851
2142
  }
1852
2143
  const main = typeof mod === "object" && mod !== null && "default" in mod ? mod.default : void 0;
@@ -1854,21 +2145,19 @@ async function boot(init) {
1854
2145
  const start = main.start;
1855
2146
  if (typeof start === "function") {
1856
2147
  const requires = "requires" in main ? main.requires : void 0;
1857
- await startIsolate(runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
2148
+ await startIsolate(m, runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
1858
2149
  return;
1859
2150
  }
1860
2151
  }
1861
- fatal(`${init.src} has no default export with start(ctx)`);
2152
+ fatal(m, `${init.src} has no default export with start(ctx)`);
1862
2153
  }
1863
- /** Set by a `{ start(ctx) }` isolate: runs its onShutdown handlers. */
1864
- let shutdownHook = null;
1865
- async function startIsolate(runtime, start, requires) {
1866
- self.addEventListener("message", (e) => {
1867
- runtime.receive(e.data);
1868
- });
1869
- shutdownHook = (reason) => runtime.shutdown(reason);
1870
- idleReport = () => runtime.idle();
1871
- post({
2154
+ async function startIsolate(m, runtime, start, requires) {
2155
+ m.receive = (msg) => {
2156
+ runtime.receive(msg);
2157
+ };
2158
+ m.shutdownHook = (reason) => runtime.shutdown(reason);
2159
+ m.idleReport = () => runtime.idle();
2160
+ m.post({
1872
2161
  v: 1,
1873
2162
  t: "ready",
1874
2163
  p: {
@@ -1881,15 +2170,33 @@ async function startIsolate(runtime, start, requires) {
1881
2170
  try {
1882
2171
  await start(runtime.ctx);
1883
2172
  } catch (err) {
1884
- fatal(`start() threw: ${err instanceof Error ? err.message : String(err)}`);
2173
+ fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
1885
2174
  }
1886
2175
  }
1887
- const onInit = (e) => {
2176
+ self.addEventListener("message", (e) => {
1888
2177
  const msg = e.data;
1889
- if (!isHostToIsolate(msg) || msg.t !== "init") return;
1890
- self.removeEventListener("message", onInit);
1891
- boot(msg.p).catch((err) => {
1892
- fatal(err instanceof Error ? err.message : String(err));
2178
+ if (!isHostToIsolate(msg)) return;
2179
+ if (msg.t !== "init") {
2180
+ route(msg);
2181
+ return;
2182
+ }
2183
+ const name = msg.isolate;
2184
+ const wants = name === void 0 ? "own" : "pool";
2185
+ if (mode === "own" || mode === "pool" && wants === "own") return;
2186
+ if (mode === null) {
2187
+ mode = wants;
2188
+ if (mode === "pool") freezeBuiltins();
2189
+ }
2190
+ if (members.has(name)) return;
2191
+ const m = {
2192
+ name,
2193
+ post: memberPost(name),
2194
+ shutdownHook: null,
2195
+ idleReport: null,
2196
+ receive: null
2197
+ };
2198
+ members.set(name, m);
2199
+ boot(m, msg.p).catch((err) => {
2200
+ fatal(m, err instanceof Error ? err.message : String(err));
1893
2201
  });
1894
- };
1895
- self.addEventListener("message", onInit);
2202
+ });
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { a as defineIsolate, c as ScrollIntoViewOptionsLike, i as REQUIRES, l as BusClient, n as IsolateDefinition, o as HostApi, r as IsolateRoot, s as HostCallError, t as IsolateContext, u as SubscribeOptions } from "./vanilla-NeyOhMib.js";
1
+ import { a as defineIsolate, c as ScrollIntoViewOptionsLike, i as REQUIRES, l as BusClient, n as IsolateDefinition, o as HostApi, r as IsolateRoot, s as HostCallError, t as IsolateContext, u as SubscribeOptions } from "./vanilla-nAEAFMUP.js";
2
2
  import { BusError } from "@isoloop/protocol";
3
3
  export { type BusClient, BusError, type HostApi, HostCallError, type IsolateContext, type IsolateDefinition, type IsolateRoot, REQUIRES, type ScrollIntoViewOptionsLike, type SubscribeOptions, defineIsolate };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as HostApi, t as IsolateContext } from "./vanilla-NeyOhMib.js";
1
+ import { o as HostApi, t as IsolateContext } from "./vanilla-nAEAFMUP.js";
2
2
  import { ShutdownReason } from "@isoloop/protocol";
3
3
  export type TestContextOptions = {
4
4
  id?: string;
@@ -12,6 +12,11 @@ export type TestContextOptions = {
12
12
  };
13
13
  export type TestContext = {
14
14
  readonly ctx: IsolateContext;
15
+ /** What `ctx.reportError` got, in order. */
16
+ readonly errors: {
17
+ error: unknown;
18
+ fatal: boolean;
19
+ }[];
15
20
  /** Delivers a record to every subscription on `topic`, in order. */
16
21
  emit: (topic: string, value: unknown, key?: string) => void;
17
22
  /** Runs `onReset` of every subscription on `topic` (a bus restart lost it, ADR 0007). */
package/dist/testing.js CHANGED
@@ -10,7 +10,9 @@ function createTestContext(o = {}) {
10
10
  const subs = /* @__PURE__ */ new Set();
11
11
  const published = [];
12
12
  const shutdownFns = [];
13
+ const errors = [];
13
14
  let offset = 0;
15
+ let portal;
14
16
  const bus = {
15
17
  publish(topic, rec) {
16
18
  published.push(rec.key === void 0 ? {
@@ -57,20 +59,52 @@ function createTestContext(o = {}) {
57
59
  requestCanvas: () => Promise.resolve(new OffscreenCanvas(1, 1)),
58
60
  ...o.host
59
61
  };
60
- return {
61
- ctx: {
62
- id: o.id ?? "test",
63
- config: o.config ?? null,
64
- root: o.root,
65
- host,
66
- bus,
67
- styles: () => {},
68
- setValue: () => {},
69
- onShutdown: (fn) => {
70
- shutdownFns.push(fn);
71
- },
72
- keepAwake: () => () => {}
62
+ const ctx = {
63
+ id: o.id ?? "test",
64
+ config: o.config ?? null,
65
+ root: o.root,
66
+ portalRoot: void 0,
67
+ reportError: (error, ro = {}) => {
68
+ errors.push({
69
+ error,
70
+ fatal: ro.fatal ?? true
71
+ });
72
+ },
73
+ host,
74
+ bus,
75
+ styles: () => {},
76
+ setValue: () => {},
77
+ onShutdown: (fn) => {
78
+ shutdownFns.push(fn);
73
79
  },
80
+ keepAwake: () => () => {}
81
+ };
82
+ Object.defineProperty(ctx, "portalRoot", {
83
+ enumerable: false,
84
+ get() {
85
+ const root = o.root;
86
+ if (!root) return void 0;
87
+ if (!portal) {
88
+ const doc = Reflect.get(root, "ownerDocument");
89
+ const make = doc ? Reflect.get(doc, "createElement") : void 0;
90
+ if (typeof make !== "function") return void 0;
91
+ const div = Reflect.apply(make, doc, ["div"]);
92
+ if (typeof div !== "object" || div === null) return void 0;
93
+ const set = Reflect.get(div, "setAttribute");
94
+ const add = Reflect.get(root, "appendChild");
95
+ if (typeof set !== "function" || typeof add !== "function") return void 0;
96
+ Reflect.apply(set, div, ["data-isoloop-portal", ""]);
97
+ queueMicrotask(() => {
98
+ if (Reflect.get(div, "parentNode") !== root) Reflect.apply(add, root, [div]);
99
+ });
100
+ portal = div;
101
+ }
102
+ return portal;
103
+ }
104
+ });
105
+ return {
106
+ ctx,
107
+ errors,
74
108
  published,
75
109
  emit(topic, value, key) {
76
110
  const rec = {
@@ -95,6 +95,14 @@ type IsolateContext<Root = IsolateRoot> = {
95
95
  readonly config: unknown;
96
96
  /** The render target; `undefined` for a headless isolate (ADR 0008). */
97
97
  readonly root: Root | undefined;
98
+ /**
99
+ * A container inside `root` for modals, tooltips, toasts and menus that
100
+ * libraries would otherwise render into `document.body`, which reaches no
101
+ * surface (ADR 0015, decision 11). Made on first use, typically from a
102
+ * component while it renders, and added as `root`'s last child once that
103
+ * render has committed; `undefined` for a headless isolate.
104
+ */
105
+ readonly portalRoot: Root | undefined;
98
106
  readonly host: HostApi;
99
107
  /** The log bus, on its own port to the bus worker (design §5). */
100
108
  readonly bus: BusClient;
@@ -109,6 +117,15 @@ type IsolateContext<Root = IsolateRoot> = {
109
117
  setValue(node: unknown, value: string, opts?: {
110
118
  force?: boolean;
111
119
  }): void;
120
+ /**
121
+ * Reports an error as this isolate's own: framework adapters call it for a
122
+ * render error their boundary caught, so in a pool it crashes only this
123
+ * member, not the whole worker (ADR 0015, decision 8). `fatal` (the
124
+ * default) crashes the isolate, which the host restarts as usual.
125
+ */
126
+ reportError(error: unknown, opts?: {
127
+ fatal?: boolean;
128
+ }): void;
112
129
  /** Runs on stop, within the host's grace period, before the worker goes. */
113
130
  onShutdown(fn: (reason: ShutdownReason) => void | Promise<void>): void;
114
131
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isoloop/runtime",
3
- "version": "0.0.0-next.5bbb503",
3
+ "version": "0.0.0-next.f57e259",
4
4
  "description": "Isolate-side runtime that runs inside each worker.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -27,8 +27,8 @@
27
27
  }
28
28
  },
29
29
  "dependencies": {
30
- "@isoloop/dom": "0.0.0-next.5bbb503",
31
- "@isoloop/protocol": "0.0.0-next.5bbb503"
30
+ "@isoloop/dom": "0.0.0-next.f57e259",
31
+ "@isoloop/protocol": "0.0.0-next.f57e259"
32
32
  },
33
33
  "devDependencies": {
34
34
  "typescript": "7.0.2"