@isoloop/runtime 0.0.0 → 0.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2751 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __esmMin = (fn, res, err) => () => {
4
+ if (err) throw err[0];
5
+ try {
6
+ return fn && (res = fn(fn = 0)), res;
7
+ } catch (e) {
8
+ throw err = [e], e;
9
+ }
10
+ };
11
+ var __exportAll = (all, flags) => {
12
+ let target = Object.setPrototypeOf({}, null);
13
+ for (var name in all) __defProp(target, name, {
14
+ get: all[name],
15
+ enumerable: true
16
+ });
17
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ return flags & 2 ? target : Object.preventExtensions(target);
19
+ };
20
+ // ../protocol/dist/index.js
21
+ /**
22
+ * True for a well-formed envelope this build can read: `v` is a supported
23
+ * version, `t` is a string, `id`/`re`/`isolate` are absent or strings, and `p`
24
+ * is present.
25
+ * Says nothing about whether `t` is known; see the per-port guards.
26
+ */
27
+ function isEnvelope(x) {
28
+ return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
29
+ }
30
+ /**
31
+ * Builds a guard for one port's union from its message types. Each side drops
32
+ * (and counts) envelopes with an unknown `v` or `t` (design §3), so a guard
33
+ * only checks the envelope and the type, not the payload.
34
+ */
35
+ function envelopeGuard(types) {
36
+ return (x) => isEnvelope(x) && Object.hasOwn(types, x.t);
37
+ }
38
+ function isSystemTopic(topic) {
39
+ return topic.startsWith(SYSTEM_TOPIC_PREFIX);
40
+ }
41
+ /**
42
+ * The commit point each record of one `deliver` settles to, in order. A
43
+ * record settles its delivery `seq` only as the delivery's last record, and
44
+ * `seq − 1` before that: a delivery counts once all its records are settled,
45
+ * and records settle in the order they arrived. Its offset is the highest
46
+ * delivered on the subscription up to it, `highest` being the highest before
47
+ * this delivery (`-1` for none), so a commit that counts a delivery settled
48
+ * also reaches every offset in it.
49
+ */
50
+ function deliveryPoints(seq, offsets, highest) {
51
+ let top = highest;
52
+ return offsets.map((offset, i) => {
53
+ top = Math.max(top, offset);
54
+ return {
55
+ offset: top,
56
+ seq: i === offsets.length - 1 ? seq : seq - 1
57
+ };
58
+ });
59
+ }
60
+ function createCommitter(o) {
61
+ const intervalMs = o.intervalMs ?? 100;
62
+ const half = Math.max(1, Math.floor((o.credit ?? 1e3) / 2));
63
+ /** Highest settled offset and delivery per topic, not yet sent. */
64
+ const offsets = /* @__PURE__ */ new Map();
65
+ /** Records settled per topic since its last send: the early send at half the credit. */
66
+ const counts = /* @__PURE__ */ new Map();
67
+ let timer;
68
+ let queued = false;
69
+ const take = () => {
70
+ if (timer !== void 0) {
71
+ clearTimeout(timer);
72
+ timer = void 0;
73
+ }
74
+ queued = false;
75
+ if (offsets.size === 0) return void 0;
76
+ const out = [];
77
+ for (const [topic, { offset, seq }] of offsets) out.push({
78
+ topic,
79
+ offset,
80
+ seq
81
+ });
82
+ offsets.clear();
83
+ counts.clear();
84
+ return out;
85
+ };
86
+ const flush = () => {
87
+ const out = take();
88
+ if (out) o.send(out);
89
+ };
90
+ const schedule = () => {
91
+ if (intervalMs === 0) {
92
+ if (queued) return;
93
+ queued = true;
94
+ queueMicrotask(() => {
95
+ if (queued) flush();
96
+ });
97
+ return;
98
+ }
99
+ timer ??= setTimeout(flush, intervalMs);
100
+ };
101
+ return {
102
+ settle(topic, at, records = 1) {
103
+ const prev = offsets.get(topic);
104
+ offsets.set(topic, prev === void 0 ? {
105
+ offset: at.offset,
106
+ seq: at.seq
107
+ } : {
108
+ offset: Math.max(prev.offset, at.offset),
109
+ seq: Math.max(prev.seq, at.seq)
110
+ });
111
+ const n = (counts.get(topic) ?? 0) + records;
112
+ counts.set(topic, n);
113
+ if (n >= half) flush();
114
+ else schedule();
115
+ },
116
+ flush,
117
+ take,
118
+ drop(topic) {
119
+ offsets.delete(topic);
120
+ counts.delete(topic);
121
+ },
122
+ pending: () => offsets,
123
+ dispose() {
124
+ if (timer !== void 0) clearTimeout(timer);
125
+ timer = void 0;
126
+ queued = false;
127
+ }
128
+ };
129
+ }
130
+ /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
131
+ function systemSchema(check) {
132
+ return { "~standard": {
133
+ version: 1,
134
+ vendor: "isoloop",
135
+ validate: (value) => {
136
+ const issues = check(value, []);
137
+ return issues.length === 0 ? { value } : { issues };
138
+ }
139
+ } };
140
+ }
141
+ /** Defines a system topic. The name must start with `isoloop.`. */
142
+ function systemTopic(name, def) {
143
+ if (!isSystemTopic(name)) throw new Error(`system topic names start with isoloop.: ${name}`);
144
+ return Object.freeze({
145
+ ...def,
146
+ name
147
+ });
148
+ }
149
+ /** `"0.4.2"` → `"0.4"`. Anything that isn't `major.minor[.patch…]` gives `undefined`. */
150
+ function majorMinor(version) {
151
+ const m = /^(\d+)\.(\d+)(?:[.+-].*)?$/.exec(version);
152
+ return m ? `${Number(m[1])}.${Number(m[2])}` : void 0;
153
+ }
154
+ var PROTOCOL, isRecord, isOptionalString, ERROR_CODES, SYSTEM_TOPIC_PREFIX, HOST_TO_ISOLATE, isHostToIsolate, BUS_TO_ISOLATE, isBusToIsolate, BusError, isObject, issue, checks, stringOrNull;
155
+ var init_dist = __esmMin((() => {
156
+ PROTOCOL = {
157
+ v: 1,
158
+ min: 1
159
+ };
160
+ isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
161
+ isOptionalString = (x) => x === void 0 || typeof x === "string";
162
+ ERROR_CODES = [
163
+ "protocol_mismatch",
164
+ "timeout",
165
+ "no_surface",
166
+ "forbidden",
167
+ "not_found",
168
+ "unsupported",
169
+ "cross_origin",
170
+ "routing_disabled",
171
+ "navigate_failed",
172
+ "unknown_topic",
173
+ "too_large",
174
+ "invalid",
175
+ "not_encodable",
176
+ "quota_exceeded",
177
+ "bus_unavailable",
178
+ "not_requestable",
179
+ "already_replied",
180
+ "reply_invalid",
181
+ "contracts_failed",
182
+ "contracts_invalid",
183
+ "contracts_mismatch",
184
+ "reserved_topic",
185
+ "seed_async",
186
+ "seed_pending"
187
+ ];
188
+ new Set(ERROR_CODES);
189
+ SYSTEM_TOPIC_PREFIX = "isoloop.";
190
+ HOST_TO_ISOLATE = {
191
+ init: true,
192
+ event: true,
193
+ result: true,
194
+ shutdown: true,
195
+ reattach: true
196
+ };
197
+ isHostToIsolate = envelopeGuard(HOST_TO_ISOLATE);
198
+ BUS_TO_ISOLATE = {
199
+ deliver: true,
200
+ reset: true,
201
+ result: true
202
+ };
203
+ isBusToIsolate = envelopeGuard(BUS_TO_ISOLATE);
204
+ BusError = class extends Error {
205
+ code;
206
+ issues;
207
+ constructor(error) {
208
+ super(error.message);
209
+ this.name = "BusError";
210
+ this.code = error.code;
211
+ this.issues = error.issues;
212
+ }
213
+ };
214
+ isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
215
+ issue = (path, message) => [{
216
+ message,
217
+ path
218
+ }];
219
+ checks = {
220
+ string: (v, path) => typeof v === "string" ? [] : issue(path, "expected a string"),
221
+ optionalString: (v, path) => v === void 0 || typeof v === "string" ? [] : issue(path, "expected a string or nothing"),
222
+ object: (fields) => (v, path) => {
223
+ if (!isObject(v)) return issue(path, "expected an object");
224
+ return Object.entries(fields).flatMap(([k, check]) => check(v[k], [...path, k]));
225
+ },
226
+ any: () => []
227
+ };
228
+ stringOrNull = (v, path) => v === null || typeof v === "string" ? [] : [{
229
+ message: "expected a string or null",
230
+ path
231
+ }];
232
+ systemTopic("isoloop.route.v1", {
233
+ schema: systemSchema(checks.object({
234
+ href: checks.string,
235
+ pathname: checks.string,
236
+ path: stringOrNull,
237
+ search: checks.string,
238
+ hash: checks.string,
239
+ state: checks.any
240
+ })),
241
+ retention: { kind: "compacted" }
242
+ });
243
+ }));
244
+ // src/busy.ts
245
+ function createBusy(now = () => performance.now()) {
246
+ let frame = null;
247
+ const spent = /* @__PURE__ */ new Map();
248
+ const containers = /* @__PURE__ */ new WeakMap();
249
+ /** Each key's current life. */
250
+ const lives = /* @__PURE__ */ new Map();
251
+ const lifeOf = (key) => lives.get(key) ?? null;
252
+ const bill = (key, ms) => {
253
+ spent.set(key, (spent.get(key) ?? 0) + ms);
254
+ };
255
+ const settle = (f) => {
256
+ const fallback = f.owner.key === PENDING ? null : f.owner.key;
257
+ if (f.pending) for (const o of f.pending) {
258
+ o.key = fallback;
259
+ o.life = f.owner.life;
260
+ }
261
+ if (f.roots && f.roots.length > 0) {
262
+ const unique = [...new Set(f.roots)];
263
+ const share = f.spent / unique.length;
264
+ for (const key of unique) bill(key, share);
265
+ } else if (fallback !== null) bill(fallback, f.spent);
266
+ };
267
+ const busy = {
268
+ run(owner, fn, self, args) {
269
+ const t = now();
270
+ const outer = frame;
271
+ if (outer) outer.spent += t - outer.start;
272
+ const f = {
273
+ owner,
274
+ start: t,
275
+ spent: 0,
276
+ parent: outer,
277
+ roots: null,
278
+ pending: null
279
+ };
280
+ frame = f;
281
+ try {
282
+ return fn.apply(self, args);
283
+ } finally {
284
+ const end = now();
285
+ f.spent += end - f.start;
286
+ frame = outer;
287
+ if (outer) outer.start = end;
288
+ settle(f);
289
+ }
290
+ },
291
+ capture() {
292
+ const f = frame;
293
+ if (!f) return {
294
+ key: null,
295
+ life: null
296
+ };
297
+ const o = {
298
+ key: PENDING,
299
+ life: null
300
+ };
301
+ (f.pending ??= []).push(o);
302
+ return o;
303
+ },
304
+ of: (key, life) => ({
305
+ key,
306
+ life: life === void 0 ? lifeOf(key) : life
307
+ }),
308
+ begin(key) {
309
+ const life = {
310
+ key,
311
+ ended: false
312
+ };
313
+ lives.set(key, life);
314
+ return life;
315
+ },
316
+ end(life) {
317
+ life.ended = true;
318
+ if (lives.get(life.key) === life) {
319
+ lives.delete(life.key);
320
+ spent.delete(life.key);
321
+ }
322
+ },
323
+ bind(fn) {
324
+ const owner = busy.capture();
325
+ return (...args) => busy.run(owner, fn, void 0, args);
326
+ },
327
+ report(key, life) {
328
+ const f = frame;
329
+ if (!f) return;
330
+ (f.roots ??= []).push(key);
331
+ if (f.pending) {
332
+ const l = life === void 0 ? lifeOf(key) : life;
333
+ for (const o of f.pending) {
334
+ o.key = key;
335
+ o.life = l;
336
+ }
337
+ f.pending = null;
338
+ }
339
+ },
340
+ take(key) {
341
+ const ms = spent.get(key) ?? 0;
342
+ spent.delete(key);
343
+ return ms;
344
+ },
345
+ claim(container, key) {
346
+ containers.set(container, {
347
+ key,
348
+ life: lifeOf(key)
349
+ });
350
+ },
351
+ keyOf(container) {
352
+ return busy.rootOf(container)?.key ?? null;
353
+ },
354
+ rootOf(container) {
355
+ if (typeof container !== "object" || container === null) return null;
356
+ return containers.get(container) ?? null;
357
+ }
358
+ };
359
+ return busy;
360
+ }
361
+ /** Keeps a wrapper's `name` and `length` the native function's. */
362
+ function like(wrapper, native) {
363
+ Object.defineProperty(wrapper, "name", {
364
+ value: native.name,
365
+ configurable: true
366
+ });
367
+ Object.defineProperty(wrapper, "length", {
368
+ value: native.length,
369
+ configurable: true
370
+ });
371
+ return wrapper;
372
+ }
373
+ /** `f` as a callback, when it is a function: schedulers call any function. */
374
+ function callable(f) {
375
+ return typeof f === "function" ? f : null;
376
+ }
377
+ /**
378
+ * `cb` run as `owner` when the scheduler calls it, with the scheduler's `this`
379
+ * and arguments. Always in a frame, even for nobody: a shared framework's
380
+ * task (React's scheduler port, set up while its module loaded) still splits
381
+ * among the roots it reports. Once the owner's life ended it doesn't run;
382
+ * `stale` gets the scheduler's `this` instead, to stop what would call it
383
+ * again (ADR 0015, decision 9).
384
+ */
385
+ function billed(busy, owner, cb, stale) {
386
+ return function(...args) {
387
+ if (owner.life?.ended === true) {
388
+ stale?.(this);
389
+ return;
390
+ }
391
+ return busy.run(owner, cb, this, args);
392
+ };
393
+ }
394
+ /**
395
+ * Wraps a scheduling function on `scope` so the callback in argument 0 is
396
+ * billed to the owner current at registration. Everything else (the return
397
+ * value, ids, `clear*`, other arguments) is the native's.
398
+ */
399
+ function wrapScheduler(scope, name, busy) {
400
+ const native = Reflect.get(scope, name);
401
+ if (typeof native !== "function") return;
402
+ const clear = name === "setInterval" ? callable(Reflect.get(scope, "clearInterval")) : null;
403
+ const wrapper = like(function(...args) {
404
+ const cb = callable(args[0]);
405
+ let id;
406
+ if (cb) args[0] = billed(busy, busy.capture(), cb, clear ? () => {
407
+ clear.call(scope, id);
408
+ } : void 0);
409
+ const r = Reflect.apply(native, this ?? scope, args);
410
+ id = r;
411
+ return r;
412
+ }, native);
413
+ Reflect.set(scope, name, wrapper);
414
+ }
415
+ /**
416
+ * Wraps `MessagePort`'s `onmessage` and its `message` listeners, so a port
417
+ * a member creates (a scheduler's `MessageChannel`, say) bills its messages
418
+ * to that member. `onmessage` still reads back the function that was set,
419
+ * and `removeEventListener` still removes what `addEventListener` added.
420
+ */
421
+ function wrapPorts(scope, busy) {
422
+ const Port = Reflect.get(scope, "MessagePort");
423
+ if (typeof Port !== "function") return;
424
+ const proto = Reflect.get(Port, "prototype");
425
+ if (typeof proto !== "object" || proto === null) return;
426
+ const close = callable(Reflect.get(proto, "close"));
427
+ const shut = (port) => {
428
+ if (close && typeof port === "object" && port !== null) close.call(port);
429
+ };
430
+ const on = Object.getOwnPropertyDescriptor(proto, "onmessage");
431
+ const get = callable(on ? Reflect.get(on, "get") : void 0);
432
+ const set = callable(on ? Reflect.get(on, "set") : void 0);
433
+ if (on && get && set) {
434
+ /** What each port's `onmessage` was set to, as read back. */
435
+ const assigned = /* @__PURE__ */ new WeakMap();
436
+ Object.defineProperty(proto, "onmessage", {
437
+ configurable: true,
438
+ enumerable: on.enumerable ?? true,
439
+ get: like(function() {
440
+ if (typeof this === "object" && this !== null && assigned.has(this)) return assigned.get(this);
441
+ return get.call(this);
442
+ }, get),
443
+ set: like(function(fn) {
444
+ if (typeof this === "object" && this !== null) assigned.set(this, fn);
445
+ const cb = callable(fn);
446
+ set.call(this, cb ? billed(busy, busy.capture(), cb, shut) : fn);
447
+ }, set)
448
+ });
449
+ }
450
+ const add = callable(Reflect.get(proto, "addEventListener"));
451
+ const remove = callable(Reflect.get(proto, "removeEventListener"));
452
+ if (!add || !remove) return;
453
+ /** Per port, per listener and capture flag: the wrapper `addEventListener` was given. */
454
+ const added = /* @__PURE__ */ new WeakMap();
455
+ Object.defineProperty(proto, "addEventListener", {
456
+ configurable: true,
457
+ writable: true,
458
+ enumerable: true,
459
+ value: like(function(...args) {
460
+ const [type, listener, options] = args;
461
+ if (type !== "message" && type !== "messageerror" || !isListener(listener) || typeof this !== "object" || this === null) return add.apply(this, args);
462
+ const capture = captureOf(options);
463
+ let byListener = added.get(this);
464
+ if (!byListener) added.set(this, byListener = /* @__PURE__ */ new Map());
465
+ let byCapture = byListener.get(listener);
466
+ if (!byCapture) byListener.set(listener, byCapture = /* @__PURE__ */ new Map());
467
+ let wrapper = byCapture.get(capture);
468
+ if (!wrapper) {
469
+ const fn = callable(listener);
470
+ const call = function(e) {
471
+ if (fn) return fn.call(this, e);
472
+ return callable(Reflect.get(listener, "handleEvent"))?.call(listener, e);
473
+ };
474
+ wrapper = billed(busy, busy.capture(), call, shut);
475
+ byCapture.set(capture, wrapper);
476
+ }
477
+ return add.apply(this, [
478
+ type,
479
+ wrapper,
480
+ ...args.slice(2)
481
+ ]);
482
+ }, add)
483
+ });
484
+ Object.defineProperty(proto, "removeEventListener", {
485
+ configurable: true,
486
+ writable: true,
487
+ enumerable: true,
488
+ value: like(function(...args) {
489
+ const [type, listener, options] = args;
490
+ const byCapture = typeof this === "object" && this !== null && isListener(listener) ? added.get(this)?.get(listener) : void 0;
491
+ const capture = captureOf(options);
492
+ const wrapper = byCapture?.get(capture);
493
+ if (!wrapper || type !== "message" && type !== "messageerror") return remove.apply(this, args);
494
+ byCapture?.delete(capture);
495
+ return remove.apply(this, [
496
+ type,
497
+ wrapper,
498
+ ...args.slice(2)
499
+ ]);
500
+ }, remove)
501
+ });
502
+ }
503
+ /**
504
+ * React's devtools hook, the smallest one react-dom accepts (production
505
+ * builds call it too): it reports each committed root's member, and each
506
+ * root whose passive effects just ran, to the current frame.
507
+ */
508
+ function installReactHook(scope, busy) {
509
+ const KEY = "__REACT_DEVTOOLS_GLOBAL_HOOK__";
510
+ if (Reflect.get(scope, KEY) !== void 0) return;
511
+ let renderers = 0;
512
+ const committed = (_renderer, root) => {
513
+ if (typeof root !== "object" || root === null) return;
514
+ const at = busy.rootOf(Reflect.get(root, "containerInfo"));
515
+ if (at !== null) busy.report(at.key, at.life);
516
+ };
517
+ Reflect.set(scope, KEY, {
518
+ supportsFiber: true,
519
+ inject: () => ++renderers,
520
+ onCommitFiberRoot: committed,
521
+ onPostCommitFiberRoot: committed,
522
+ onCommitFiberUnmount: () => {},
523
+ checkDCE: () => {}
524
+ });
525
+ }
526
+ /**
527
+ * Installs attribution on a worker's global, once, before any member loads:
528
+ * the scheduling functions, `MessagePort` listeners and React's hook.
529
+ */
530
+ function installBusy(scope, busy) {
531
+ const q = Reflect.get(scope, "queueMicrotask");
532
+ if (typeof q === "function") nativeQueueMicrotask = (fn) => {
533
+ Reflect.apply(q, scope, [fn]);
534
+ };
535
+ for (const name of SCHEDULERS) wrapScheduler(scope, name, busy);
536
+ wrapPorts(scope, busy);
537
+ installReactHook(scope, busy);
538
+ }
539
+ var PENDING, SCHEDULERS, captureOf, isListener, nativeQueueMicrotask, busy, BUSY;
540
+ var init_busy = __esmMin((() => {
541
+ PENDING = Symbol("pending");
542
+ SCHEDULERS = [
543
+ "setTimeout",
544
+ "setInterval",
545
+ "requestAnimationFrame",
546
+ "queueMicrotask",
547
+ "requestIdleCallback"
548
+ ];
549
+ captureOf = (options) => typeof options === "boolean" ? options : typeof options === "object" && options !== null && Reflect.get(options, "capture") === true;
550
+ isListener = (l) => typeof l === "function" || typeof l === "object" && l !== null && typeof Reflect.get(l, "handleEvent") === "function";
551
+ nativeQueueMicrotask = (fn) => {
552
+ queueMicrotask(fn);
553
+ };
554
+ busy = createBusy();
555
+ BUSY = Symbol.for("isoloop.busy");
556
+ }));
557
+ // src/freeze.ts
558
+ init_dist();
559
+ init_busy();
560
+ /** Constructors whose `prototype` and statics are frozen, if this engine has them. */
561
+ const NAMES = [
562
+ "Object",
563
+ "Function",
564
+ "Array",
565
+ "String",
566
+ "Number",
567
+ "Boolean",
568
+ "Symbol",
569
+ "BigInt",
570
+ "Date",
571
+ "RegExp",
572
+ "Error",
573
+ "EvalError",
574
+ "RangeError",
575
+ "ReferenceError",
576
+ "SyntaxError",
577
+ "TypeError",
578
+ "URIError",
579
+ "AggregateError",
580
+ "Promise",
581
+ "Map",
582
+ "Set",
583
+ "WeakMap",
584
+ "WeakSet",
585
+ "WeakRef",
586
+ "FinalizationRegistry",
587
+ "ArrayBuffer",
588
+ "DataView",
589
+ "Int8Array",
590
+ "Uint8Array",
591
+ "Uint8ClampedArray",
592
+ "Int16Array",
593
+ "Uint16Array",
594
+ "Int32Array",
595
+ "Uint32Array",
596
+ "Float32Array",
597
+ "Float64Array",
598
+ "BigInt64Array",
599
+ "BigUint64Array"
600
+ ];
601
+ /**
602
+ * Freezing a prototype makes its data properties read-only, and in strict
603
+ * code assigning a property of the same name on an instance then throws (the
604
+ * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`,
605
+ * or `Object.assign({}, { constructor: x })`). As Hardened JS does, each data
606
+ * property becomes an accessor whose setter defines the property on the
607
+ * instance instead, so overriding still works while the prototype itself
608
+ * can't change.
609
+ *
610
+ * Except the properties V8 guards with "protectors": while they are still the
611
+ * original data properties, V8 keeps fast paths for iteration (`for…of`,
612
+ * spread, destructuring), species lookups and promise resolution. An accessor
613
+ * returning the same function is enough to turn a protector off for the whole
614
+ * worker: array iteration alone made a pool's app code 1.4–2.5× slower
615
+ * (docs/investigations/plant-one-pool.md). These stay plain frozen data, so
616
+ * overriding one of them on an instance throws in strict code instead
617
+ * (ADR 0001, "Override taming without the protected properties").
618
+ */
619
+ const ITERATOR = Symbol.iterator;
620
+ /** The protected properties, per prototype, that are left as frozen data. */
621
+ function protectedProperties() {
622
+ const out = /* @__PURE__ */ new Map();
623
+ const add = (o, ...keys) => {
624
+ if (typeof o !== "object" && typeof o !== "function" || o === null) return;
625
+ out.set(o, /* @__PURE__ */ new Set([...out.get(o) ?? [], ...keys]));
626
+ };
627
+ const typedArrayCtor = Object.getPrototypeOf(Int8Array);
628
+ const typedArray = typeof typedArrayCtor === "function" ? Reflect.get(typedArrayCtor, "prototype") : void 0;
629
+ add(Array.prototype, ITERATOR, "constructor");
630
+ add(Object.getPrototypeOf([][Symbol.iterator]()), "next");
631
+ add(Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())), ITERATOR);
632
+ add(typedArray, ITERATOR, "constructor");
633
+ for (const c of [
634
+ Int8Array,
635
+ Uint8Array,
636
+ Uint8ClampedArray,
637
+ Int16Array,
638
+ Uint16Array,
639
+ Int32Array,
640
+ Uint32Array,
641
+ Float32Array,
642
+ Float64Array,
643
+ BigInt64Array,
644
+ BigUint64Array
645
+ ]) add(c.prototype, "constructor");
646
+ add(Map.prototype, ITERATOR);
647
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()), "next");
648
+ add(Set.prototype, ITERATOR);
649
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()), "next");
650
+ add(String.prototype, ...Reflect.ownKeys(String.prototype));
651
+ add(Object.getPrototypeOf(""[Symbol.iterator]()), "next");
652
+ add(Promise.prototype, "then", "constructor");
653
+ add(RegExp.prototype, ...Reflect.ownKeys(RegExp.prototype));
654
+ return out;
655
+ }
656
+ let skip;
657
+ function tameOverrides(proto) {
658
+ skip ??= protectedProperties();
659
+ const keep = skip.get(proto);
660
+ for (const key of Reflect.ownKeys(proto)) if (!keep?.has(key)) tameOverride(proto, key);
661
+ }
662
+ function tameOverride(proto, key) {
663
+ const d = Object.getOwnPropertyDescriptor(proto, key);
664
+ if (!d || !("value" in d) || !d.configurable) return;
665
+ const value = d.value;
666
+ Object.defineProperty(proto, key, {
667
+ get() {
668
+ return value;
669
+ },
670
+ set(v) {
671
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
672
+ if (typeof this !== "object" && typeof this !== "function") return;
673
+ if (this === null) return;
674
+ Object.defineProperty(this, key, {
675
+ value: v,
676
+ writable: true,
677
+ enumerable: true,
678
+ configurable: true
679
+ });
680
+ },
681
+ enumerable: d.enumerable ?? false,
682
+ configurable: false
683
+ });
684
+ }
685
+ function hardenProto(proto) {
686
+ if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
687
+ if (Object.isFrozen(proto)) return;
688
+ tameOverrides(proto);
689
+ Object.freeze(proto);
690
+ }
691
+ function freezeWithPrototype(c) {
692
+ if (typeof c !== "function") return;
693
+ hardenProto(Reflect.get(c, "prototype"));
694
+ if (c !== Error) Object.freeze(c);
695
+ }
696
+ /** Freezes the shared intrinsics. Call once, before any member module loads. */
697
+ function freezeBuiltins() {
698
+ const g = globalThis;
699
+ for (const name of NAMES) freezeWithPrototype(Reflect.get(g, name));
700
+ freezeWithPrototype(Object.getPrototypeOf(Int8Array));
701
+ const protos = [
702
+ Object.getPrototypeOf([][Symbol.iterator]()),
703
+ Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())),
704
+ Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()),
705
+ Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()),
706
+ Object.getPrototypeOf(""[Symbol.iterator]()),
707
+ Object.getPrototypeOf(function* () {}),
708
+ Object.getPrototypeOf(async function() {}),
709
+ Object.getPrototypeOf(async function* () {})
710
+ ];
711
+ for (const p of protos) {
712
+ if (typeof p !== "object" && typeof p !== "function" || p === null) continue;
713
+ hardenProto(Reflect.get(p, "prototype"));
714
+ hardenProto(p);
715
+ }
716
+ Object.freeze(Math);
717
+ Object.freeze(JSON);
718
+ Object.freeze(Reflect);
719
+ }
720
+ // src/bus-client.ts
721
+ function createBusClient(first, o = {}) {
722
+ const limit = o.inboxLimit ?? 1e3;
723
+ const now = o.now ?? (() => performance.now());
724
+ let lastDelivery = now();
725
+ let port = first;
726
+ let nextId = 0;
727
+ const epoch = o.epoch ?? randomEpoch();
728
+ /** Publishes and requests sent by this instance: the `seq` of publish ids. */
729
+ let seq = 0;
730
+ const pending = /* @__PURE__ */ new Map();
731
+ const subs = /* @__PURE__ */ new Map();
732
+ /** Where each delivered record came from and what it settles, for `reply` and `commit`. */
733
+ const delivered = /* @__PURE__ */ new WeakMap();
734
+ /** Counts bus ports: a new one after each bus restart. */
735
+ let ports = 0;
736
+ const send = (msg) => {
737
+ port.postMessage(msg);
738
+ };
739
+ const call = (msg) => {
740
+ if (pending.size >= limit) return Promise.resolve({
741
+ ok: false,
742
+ error: {
743
+ code: "bus_unavailable",
744
+ message: "Too many bus calls waiting for an answer"
745
+ }
746
+ });
747
+ const id = `b${++nextId}`;
748
+ return new Promise((settle) => {
749
+ const withId = {
750
+ ...msg,
751
+ id
752
+ };
753
+ pending.set(id, {
754
+ msg: withId,
755
+ settle
756
+ });
757
+ send(withId);
758
+ });
759
+ };
760
+ const committer = createCommitter({
761
+ send: (offsets) => {
762
+ send({
763
+ v: 1,
764
+ t: "commits",
765
+ p: { offsets }
766
+ });
767
+ },
768
+ ...o.commitIntervalMs === void 0 ? {} : { intervalMs: o.commitIntervalMs },
769
+ ...o.credit === void 0 ? {} : { credit: o.credit }
770
+ });
771
+ /**
772
+ * Settles a record, and with it every record delivered before it on its
773
+ * subscription. One from a replaced subscription or an old port is
774
+ * dropped: its delivery `seq` means nothing to the broker now.
775
+ */
776
+ const commit = (d) => {
777
+ if (subs.get(d.topic) !== d.sub || d.port !== ports) return;
778
+ committer.settle(d.topic, d.at);
779
+ };
780
+ const drain = async (sub) => {
781
+ if (sub.running) return;
782
+ sub.running = true;
783
+ while (sub.queue.length > 0 && subs.get(sub.topic) === sub) {
784
+ const r = sub.queue.shift();
785
+ if (!r) break;
786
+ try {
787
+ const done = sub.fn(r);
788
+ if (isThenable(done)) await done;
789
+ } catch (err) {
790
+ sub.stuck = true;
791
+ o.onError?.(err);
792
+ }
793
+ const d = delivered.get(r);
794
+ if (sub.opts.autoCommit !== false && !sub.stuck && d) commit(d);
795
+ }
796
+ sub.running = false;
797
+ };
798
+ const sendSubscribe = (sub) => {
799
+ const p = {
800
+ topic: sub.topic,
801
+ from: sub.opts.from ?? "latest"
802
+ };
803
+ if (o.wake && p.from === "latest") p.from = "committed";
804
+ if (sub.opts.group !== void 0) p.group = sub.opts.group;
805
+ call({
806
+ v: 1,
807
+ t: "subscribe",
808
+ p
809
+ }).then((r) => {
810
+ if (!r.ok) o.onError?.(new BusError(r.error));
811
+ });
812
+ };
813
+ const receive = (msg) => {
814
+ switch (msg.t) {
815
+ case "result": {
816
+ const p = msg.re === void 0 ? void 0 : pending.get(msg.re);
817
+ if (!p || msg.re === void 0) return;
818
+ pending.delete(msg.re);
819
+ p.settle(msg.p);
820
+ return;
821
+ }
822
+ case "deliver": {
823
+ const sub = subs.get(msg.p.topic);
824
+ if (!sub) return;
825
+ lastDelivery = now();
826
+ const { gap } = msg.p;
827
+ if (gap) try {
828
+ sub.opts.onGap?.(gap);
829
+ } catch (err) {
830
+ o.onError?.(err);
831
+ }
832
+ const { records } = msg.p;
833
+ const points = deliveryPoints(msg.p.seq, records.map((r) => r.offset), sub.highest);
834
+ records.forEach((r, i) => {
835
+ const at = points[i];
836
+ if (at) delivered.set(r, {
837
+ topic: sub.topic,
838
+ sub,
839
+ port: ports,
840
+ at
841
+ });
842
+ });
843
+ sub.highest = points.at(-1)?.offset ?? sub.highest;
844
+ sub.queue.push(...records);
845
+ drain(sub);
846
+ return;
847
+ }
848
+ case "reset": {
849
+ const sub = subs.get(msg.p.topic);
850
+ if (!sub) return;
851
+ sub.queue.length = 0;
852
+ sub.highest = -1;
853
+ committer.drop(msg.p.topic);
854
+ try {
855
+ sub.opts.onReset?.();
856
+ } catch (err) {
857
+ o.onError?.(err);
858
+ }
859
+ return;
860
+ }
861
+ default: return msg;
862
+ }
863
+ };
864
+ const listen = (p) => {
865
+ p.addEventListener("message", (e) => {
866
+ if (port === p && isBusToIsolate(e.data)) receive(e.data);
867
+ });
868
+ p.start();
869
+ };
870
+ listen(first);
871
+ return {
872
+ client: {
873
+ async publish(topic, rec) {
874
+ const p = {
875
+ topic: topic.name,
876
+ value: rec.value,
877
+ epoch,
878
+ seq: ++seq
879
+ };
880
+ if (rec.key !== void 0) p.key = rec.key;
881
+ check(await call({
882
+ v: 1,
883
+ t: "publish",
884
+ p
885
+ }));
886
+ },
887
+ subscribe(topic, fn, opts = {}) {
888
+ subs.get(topic.name)?.queue.splice(0);
889
+ const sub = {
890
+ topic: topic.name,
891
+ fn,
892
+ opts,
893
+ queue: [],
894
+ running: false,
895
+ stuck: false,
896
+ highest: -1
897
+ };
898
+ subs.set(topic.name, sub);
899
+ sendSubscribe(sub);
900
+ return () => {
901
+ if (subs.get(topic.name) !== sub) return;
902
+ subs.delete(topic.name);
903
+ committer.flush();
904
+ send({
905
+ v: 1,
906
+ t: "unsubscribe",
907
+ p: { topic: topic.name }
908
+ });
909
+ };
910
+ },
911
+ async request(topic, value, opts = {}) {
912
+ const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
913
+ const p = {
914
+ topic: topic.name,
915
+ value,
916
+ timeoutMs,
917
+ epoch,
918
+ seq: ++seq
919
+ };
920
+ if (opts.key !== void 0) p.key = opts.key;
921
+ let timer;
922
+ const timeout = new Promise((resolve) => {
923
+ timer = setTimeout(() => {
924
+ resolve({
925
+ ok: false,
926
+ error: {
927
+ code: "timeout",
928
+ message: `No reply on ${topic.name} within ${timeoutMs} ms`
929
+ }
930
+ });
931
+ }, timeoutMs);
932
+ });
933
+ const r = await Promise.race([call({
934
+ v: 1,
935
+ t: "request",
936
+ p
937
+ }), timeout]);
938
+ clearTimeout(timer);
939
+ check(r);
940
+ return r.value;
941
+ },
942
+ async reply(record, value) {
943
+ const topic = delivered.get(record)?.topic;
944
+ if (topic === void 0) throw new Error("reply: this record was not delivered to this isolate");
945
+ check(await call({
946
+ v: 1,
947
+ t: "reply",
948
+ p: {
949
+ topic,
950
+ offset: record.offset,
951
+ value
952
+ }
953
+ }));
954
+ },
955
+ commit(record) {
956
+ const d = delivered.get(record);
957
+ if (d === void 0) throw new Error("commit: this record was not delivered to this isolate");
958
+ commit(d);
959
+ }
960
+ },
961
+ idle: () => ({
962
+ sinceDeliveryMs: now() - lastDelivery,
963
+ inFlight: pending.size
964
+ }),
965
+ reattach(next) {
966
+ const old = port;
967
+ port = next;
968
+ ports++;
969
+ old.close();
970
+ listen(next);
971
+ const unanswered = [...pending.values()];
972
+ for (const p of unanswered) {
973
+ if (p.msg.t !== "subscribe") continue;
974
+ pending.delete(p.msg.id);
975
+ p.settle({
976
+ ok: true,
977
+ value: null
978
+ });
979
+ }
980
+ committer.take();
981
+ for (const sub of subs.values()) {
982
+ sub.queue.length = 0;
983
+ sub.highest = -1;
984
+ sendSubscribe(sub);
985
+ }
986
+ for (const p of unanswered) if (p.msg.t !== "subscribe") send(p.msg);
987
+ },
988
+ async close() {
989
+ const offsets = committer.take();
990
+ committer.dispose();
991
+ if (offsets) await call({
992
+ v: 1,
993
+ t: "commits",
994
+ p: { offsets }
995
+ });
996
+ }
997
+ };
998
+ }
999
+ function isThenable(x) {
1000
+ return (typeof x === "object" || typeof x === "function") && x !== null && typeof x.then === "function";
1001
+ }
1002
+ var randomEpoch, check, REQUEST_TIMEOUT_MS;
1003
+ var init_bus_client = __esmMin((() => {
1004
+ randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
1005
+ check = (r) => {
1006
+ if (!r.ok) throw new BusError(r.error);
1007
+ };
1008
+ REQUEST_TIMEOUT_MS = 3e4;
1009
+ }));
1010
+ // src/host-calls.ts
1011
+ function createHostCalls(opts) {
1012
+ const timeoutMs = opts.timeoutMs ?? 5e3;
1013
+ const pending = /* @__PURE__ */ new Map();
1014
+ let seq = 0;
1015
+ const send = (method, args) => {
1016
+ const id = `c${++seq}`;
1017
+ return new Promise((resolve, reject) => {
1018
+ const timer = setTimeout(() => {
1019
+ pending.delete(id);
1020
+ reject(new HostCallError("timeout", `${method}: no answer within ${timeoutMs} ms`));
1021
+ }, timeoutMs);
1022
+ pending.set(id, {
1023
+ resolve,
1024
+ reject,
1025
+ timer
1026
+ });
1027
+ opts.post({
1028
+ v: 1,
1029
+ t: "call",
1030
+ id,
1031
+ p: {
1032
+ method,
1033
+ args
1034
+ }
1035
+ });
1036
+ });
1037
+ };
1038
+ const call = (method, node, extra = []) => {
1039
+ const nodeId = opts.idOf(node);
1040
+ if (opts.surface && nodeId === void 0) return Promise.reject(new HostCallError("not_found", `${method}: not a rendered node`));
1041
+ opts.beforeCall();
1042
+ return send(method, [nodeId ?? null, ...extra]);
1043
+ };
1044
+ return {
1045
+ api: {
1046
+ async navigate(href, o = {}) {
1047
+ if (!opts.navigate) throw new HostCallError("forbidden", "navigate: this isolate has no navigate grant (ADR 0002)");
1048
+ return await send("navigate", [href, {
1049
+ replace: o.replace ?? false,
1050
+ state: o.state
1051
+ }]) === true;
1052
+ },
1053
+ async measure(node) {
1054
+ const value = await call("measure", node);
1055
+ if (!isRect(value)) throw new HostCallError("invalid", "measure: the host sent no rect");
1056
+ return value;
1057
+ },
1058
+ async focus(node) {
1059
+ await call("focus", node);
1060
+ },
1061
+ async scrollIntoView(node, o) {
1062
+ await call("scrollIntoView", node, o === void 0 ? [] : [o]);
1063
+ },
1064
+ async requestCanvas(node, size) {
1065
+ const value = await call("requestCanvas", node, size === void 0 ? [] : [size]);
1066
+ if (!(value instanceof OffscreenCanvas)) throw new HostCallError("invalid", "requestCanvas: the host sent no OffscreenCanvas");
1067
+ return value;
1068
+ }
1069
+ },
1070
+ pending: () => pending.size,
1071
+ receive(re, result) {
1072
+ const p = pending.get(re);
1073
+ if (!p) return;
1074
+ pending.delete(re);
1075
+ clearTimeout(p.timer);
1076
+ if (result.ok) p.resolve(result.value);
1077
+ else p.reject(new HostCallError(result.error.code, result.error.message));
1078
+ }
1079
+ };
1080
+ }
1081
+ var HostCallError, isRect;
1082
+ var init_host_calls = __esmMin((() => {
1083
+ HostCallError = class extends Error {
1084
+ code;
1085
+ constructor(code, message) {
1086
+ super(message);
1087
+ this.name = "HostCallError";
1088
+ this.code = code;
1089
+ }
1090
+ };
1091
+ isRect = (x) => typeof x === "object" && x !== null && [
1092
+ "x",
1093
+ "y",
1094
+ "width",
1095
+ "height"
1096
+ ].every((k) => typeof Reflect.get(x, k) === "number");
1097
+ }));
1098
+ // src/keep-awake.ts
1099
+ function createKeepAwake(now = () => performance.now()) {
1100
+ const holds = /* @__PURE__ */ new Map();
1101
+ let next = 0;
1102
+ return {
1103
+ hold() {
1104
+ const id = ++next;
1105
+ const stack = (/* @__PURE__ */ new Error("keepAwake")).stack?.split("\n").slice(2).join("\n");
1106
+ holds.set(id, {
1107
+ since: now(),
1108
+ stack
1109
+ });
1110
+ return () => {
1111
+ holds.delete(id);
1112
+ };
1113
+ },
1114
+ report(at) {
1115
+ return [...holds.values()].map((h) => h.stack === void 0 ? { ageMs: at - h.since } : {
1116
+ ageMs: at - h.since,
1117
+ stack: h.stack
1118
+ });
1119
+ }
1120
+ };
1121
+ }
1122
+ var init_keep_awake = __esmMin((() => {}));
1123
+ // ../dom/dist/records-wVZrPpqr.js
1124
+ var ISOLOOP_DOM_FMT;
1125
+ var init_records_wVZrPpqr = __esmMin((() => {
1126
+ ISOLOOP_DOM_FMT = "isoloop-dom@1";
1127
+ }));
1128
+ // ../dom/dist/dom-yLsf0Z4e.js
1129
+ function createStyle(el) {
1130
+ const decls = /* @__PURE__ */ new Map();
1131
+ const write = () => {
1132
+ const text = [...decls].map(([k, v]) => `${k}: ${v};`).join(" ");
1133
+ if (text) el.setAttribute("style", text);
1134
+ else el.removeAttribute("style");
1135
+ };
1136
+ const set = (name, value) => {
1137
+ const v = str(value);
1138
+ if (v === "") decls.delete(name);
1139
+ else decls.set(name, v);
1140
+ };
1141
+ return new Proxy({
1142
+ setProperty(name, value) {
1143
+ set(kebab(name), value);
1144
+ write();
1145
+ },
1146
+ removeProperty(name) {
1147
+ const old = decls.get(kebab(name)) ?? "";
1148
+ decls.delete(kebab(name));
1149
+ write();
1150
+ return old;
1151
+ },
1152
+ getPropertyValue(name) {
1153
+ return decls.get(kebab(name)) ?? "";
1154
+ },
1155
+ get cssText() {
1156
+ return [...decls].map(([k, v]) => `${k}: ${v};`).join(" ");
1157
+ },
1158
+ set cssText(text) {
1159
+ decls.clear();
1160
+ for (const part of text.split(";")) {
1161
+ const i = part.indexOf(":");
1162
+ if (i > 0) set(part.slice(0, i).trim(), part.slice(i + 1).trim());
1163
+ }
1164
+ write();
1165
+ }
1166
+ }, {
1167
+ get(t, key, receiver) {
1168
+ if (typeof key !== "string" || key in t) return Reflect.get(t, key, receiver);
1169
+ return decls.get(kebab(key === "cssFloat" ? "float" : key)) ?? "";
1170
+ },
1171
+ set(t, key, value, receiver) {
1172
+ if (typeof key !== "string" || key in t) return Reflect.set(t, key, value, receiver);
1173
+ set(kebab(key === "cssFloat" ? "float" : key), value);
1174
+ write();
1175
+ return true;
1176
+ }
1177
+ });
1178
+ }
1179
+ /**
1180
+ * `element.dataset` (DOM group 1, ADR 0010): camelCase keys over the
1181
+ * `data-*` attributes, so every write travels as an `attr` record.
1182
+ */
1183
+ function createDataset(el) {
1184
+ return new Proxy({}, {
1185
+ get: (_t, key) => typeof key === "string" ? el.getAttribute(dataAttr(key)) ?? void 0 : void 0,
1186
+ set(_t, key, value) {
1187
+ if (typeof key !== "string") return false;
1188
+ el.setAttribute(dataAttr(key), value);
1189
+ return true;
1190
+ },
1191
+ deleteProperty(_t, key) {
1192
+ if (typeof key === "string") el.removeAttribute(dataAttr(key));
1193
+ return true;
1194
+ },
1195
+ has: (_t, key) => typeof key === "string" && el.hasAttribute(dataAttr(key)),
1196
+ ownKeys: () => [...el.isoAttrs.keys()].filter((n) => n.startsWith("data-")).map(dataKey),
1197
+ getOwnPropertyDescriptor(_t, key) {
1198
+ if (typeof key !== "string" || !el.hasAttribute(dataAttr(key))) return void 0;
1199
+ return {
1200
+ value: el.getAttribute(dataAttr(key)),
1201
+ writable: true,
1202
+ enumerable: true,
1203
+ configurable: true
1204
+ };
1205
+ }
1206
+ });
1207
+ }
1208
+ function defineHandlers(proto) {
1209
+ const handlers = /* @__PURE__ */ new WeakMap();
1210
+ for (const type of HANDLER_EVENTS) Object.defineProperty(proto, `on${type}`, {
1211
+ configurable: true,
1212
+ enumerable: true,
1213
+ get() {
1214
+ return handlers.get(this)?.get(type) ?? null;
1215
+ },
1216
+ set(fn) {
1217
+ const own = handlers.get(this) ?? /* @__PURE__ */ new Map();
1218
+ handlers.set(this, own);
1219
+ const old = own.get(type);
1220
+ if (old) this.removeEventListener(type, old);
1221
+ if (typeof fn === "function") {
1222
+ const handler = (e) => {
1223
+ Reflect.apply(fn, this, [e]);
1224
+ };
1225
+ own.set(type, handler);
1226
+ this.addEventListener(type, handler);
1227
+ } else own.delete(type);
1228
+ }
1229
+ });
1230
+ }
1231
+ /** The subtree as `insert` sends it. */
1232
+ function serialize(n) {
1233
+ if (n instanceof WText) return {
1234
+ k: "text",
1235
+ id: n.isoId,
1236
+ data: n.isoData
1237
+ };
1238
+ if (n instanceof WComment) return {
1239
+ k: "comment",
1240
+ id: n.isoId,
1241
+ data: n.isoData
1242
+ };
1243
+ if (!(n instanceof WElement)) throw new TypeError("serialize: unknown node");
1244
+ return {
1245
+ k: "el",
1246
+ id: n.isoId,
1247
+ tag: n.localName,
1248
+ ns: n.isoNs,
1249
+ attrs: [...n.isoAttrs],
1250
+ props: [...n.isoProps],
1251
+ listen: [...n.isoListeners.keys()],
1252
+ children: n.childNodes.map(serialize)
1253
+ };
1254
+ }
1255
+ /** Whether `n` or anything under it was rendered under a root other than `owner`. */
1256
+ function ownedElsewhere(n, owner) {
1257
+ if (n.isoOwner && n.isoOwner !== owner) return true;
1258
+ return !n.isoKnown && n.childNodes.some((c) => ownedElsewhere(c, owner));
1259
+ }
1260
+ function learn(n, core, owner) {
1261
+ n.isoKnown = true;
1262
+ n.isoOwner = owner;
1263
+ core.known.set(n.isoId, n);
1264
+ for (const c of n.childNodes) learn(c, core, owner);
1265
+ }
1266
+ function forget(n, core) {
1267
+ n.isoKnown = false;
1268
+ core.known.delete(n.isoId);
1269
+ for (const c of n.childNodes) forget(c, core);
1270
+ }
1271
+ function setValueOf(node, value, o) {
1272
+ if (!isControl(node)) throw new TypeError("setValue: not an input, textarea or select");
1273
+ if (!o.force) {
1274
+ node.value = value;
1275
+ return;
1276
+ }
1277
+ node.isoSetProp("value", value, false);
1278
+ if (node.isoKnown) emit(node, [
1279
+ "prop",
1280
+ node.isoWire,
1281
+ "value",
1282
+ value,
1283
+ true
1284
+ ]);
1285
+ }
1286
+ function deliverTo(node, event) {
1287
+ if (!node) return;
1288
+ if (isControl(node) && event.value !== void 0) node.isoSetProp("value", event.value, false);
1289
+ if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
1290
+ if (event.type === "scroll" && node instanceof WElement) node.isoScroll = {
1291
+ top: event.scrollTop ?? 0,
1292
+ left: event.scrollLeft ?? 0
1293
+ };
1294
+ node.dispatchEvent(toEvent(event));
1295
+ }
1296
+ /** A root's recorder: records batched per microtask (or `schedule`) into `onBatch`. */
1297
+ function recorder(root, onBatch, schedule) {
1298
+ let pending = [];
1299
+ let scheduled = false;
1300
+ let live = true;
1301
+ const flush = () => {
1302
+ scheduled = false;
1303
+ if (pending.length === 0) return;
1304
+ const batch = pending;
1305
+ pending = [];
1306
+ if (live) onBatch(batch);
1307
+ };
1308
+ return {
1309
+ owner: {
1310
+ root,
1311
+ push(r) {
1312
+ if (!live) return;
1313
+ pending.push(r);
1314
+ if (!scheduled) {
1315
+ scheduled = true;
1316
+ schedule(flush);
1317
+ }
1318
+ }
1319
+ },
1320
+ flush,
1321
+ stop: () => {
1322
+ live = false;
1323
+ pending = [];
1324
+ }
1325
+ };
1326
+ }
1327
+ function createDom(opts) {
1328
+ const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
1329
+ const core = {
1330
+ roots: /* @__PURE__ */ new Set(),
1331
+ nextId: 1,
1332
+ known: /* @__PURE__ */ new Map(),
1333
+ onHead: opts.onHead ?? (() => {})
1334
+ };
1335
+ const document = new WDocument(core);
1336
+ const makeRoot = (id) => {
1337
+ const root = new WHTMLElement(document, id, "iso-root", "html");
1338
+ root.isoKnown = true;
1339
+ core.known.set(id, root);
1340
+ core.roots.add(root);
1341
+ return root;
1342
+ };
1343
+ const root = makeRoot(0);
1344
+ const main = recorder(root, (b) => opts.onBatch(b), schedule);
1345
+ root.isoOwner = main.owner;
1346
+ return {
1347
+ document,
1348
+ root,
1349
+ flush: main.flush,
1350
+ idOf: (node) => node.isoId,
1351
+ setValue: (node, value, o = {}) => setValueOf(node, value, o),
1352
+ deliver: (event) => deliverTo(core.known.get(event.target), event),
1353
+ addRoot(o) {
1354
+ const member = makeRoot(core.nextId++);
1355
+ const rec = recorder(member, (b) => o.onBatch(b), o.schedule ?? schedule);
1356
+ member.isoOwner = rec.owner;
1357
+ const mine = (node) => node?.isoKnown && node.isoOwner === rec.owner ? node : void 0;
1358
+ return {
1359
+ root: member,
1360
+ flush: rec.flush,
1361
+ idOf: (node) => mine(node) ? node.isoWire : void 0,
1362
+ setValue(node, value, so = {}) {
1363
+ if (node.isoOwner && node.isoOwner !== rec.owner) throw new TypeError("setValue: not a node of this member's root");
1364
+ setValueOf(node, value, so);
1365
+ },
1366
+ deliver: (event) => deliverTo(mine(event.target === 0 ? member : core.known.get(event.target)), event),
1367
+ dispose() {
1368
+ rec.stop();
1369
+ core.roots.delete(member);
1370
+ forget(member, core);
1371
+ }
1372
+ };
1373
+ }
1374
+ };
1375
+ }
1376
+ /** A real `Event` with the fields frameworks read from mouse and keyboard events. */
1377
+ function toEvent(e) {
1378
+ const ev = new Event(e.type, {
1379
+ bubbles: e.type !== "scroll",
1380
+ cancelable: true
1381
+ });
1382
+ const mods = {
1383
+ Alt: e.mods.alt,
1384
+ Control: e.mods.ctrl,
1385
+ Meta: e.mods.meta,
1386
+ Shift: e.mods.shift
1387
+ };
1388
+ Object.defineProperties(ev, {
1389
+ altKey: { value: e.mods.alt },
1390
+ ctrlKey: { value: e.mods.ctrl },
1391
+ metaKey: { value: e.mods.meta },
1392
+ shiftKey: { value: e.mods.shift },
1393
+ getModifierState: { value: (k) => mods[k] ?? false },
1394
+ key: { value: e.key },
1395
+ code: { value: e.code },
1396
+ button: { value: e.button ?? 0 },
1397
+ clientX: { value: e.x ?? 0 },
1398
+ clientY: { value: e.y ?? 0 },
1399
+ width: { value: e.width },
1400
+ height: { value: e.height }
1401
+ });
1402
+ return ev;
1403
+ }
1404
+ 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;
1405
+ var init_dom_yLsf0Z4e = __esmMin((() => {
1406
+ HTML_NS = "http://www.w3.org/1999/xhtml";
1407
+ SVG_NS = "http://www.w3.org/2000/svg";
1408
+ str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : "";
1409
+ domError = (name, message) => {
1410
+ const e = new Error(message);
1411
+ e.name = name;
1412
+ return e;
1413
+ };
1414
+ emit = (n, r) => {
1415
+ n.isoOwner?.push(r);
1416
+ };
1417
+ WEventTarget = class {
1418
+ /** @internal */ isoListeners = /* @__PURE__ */ new Map();
1419
+ /** @internal */ isoParentTarget() {
1420
+ return null;
1421
+ }
1422
+ /** @internal Called when the first listener of `type` is added, or the last removed. */
1423
+ isoListenChanged(_type, _on) {}
1424
+ addEventListener(type, fn, options) {
1425
+ if (!fn) return;
1426
+ const capture = typeof options === "boolean" ? options : Boolean(options?.capture);
1427
+ const once = typeof options === "object" && Boolean(options.once);
1428
+ const list = this.isoListeners.get(type) ?? [];
1429
+ if (list.some((l) => l.fn === fn && l.capture === capture)) return;
1430
+ list.push({
1431
+ fn,
1432
+ capture,
1433
+ once
1434
+ });
1435
+ this.isoListeners.set(type, list);
1436
+ if (list.length === 1) this.isoListenChanged(type, true);
1437
+ }
1438
+ removeEventListener(type, fn, options) {
1439
+ const capture = typeof options === "boolean" ? options : Boolean(options?.capture);
1440
+ const list = this.isoListeners.get(type);
1441
+ if (!list) return;
1442
+ const i = list.findIndex((l) => l.fn === fn && l.capture === capture);
1443
+ if (i < 0) return;
1444
+ list.splice(i, 1);
1445
+ if (list.length === 0) {
1446
+ this.isoListeners.delete(type);
1447
+ this.isoListenChanged(type, false);
1448
+ }
1449
+ }
1450
+ /** Capture from the top, then the target, then bubble (if `bubbles`). */
1451
+ dispatchEvent(event) {
1452
+ const path = [this];
1453
+ for (let t = this.isoParentTarget(); t; t = t.isoParentTarget()) path.push(t);
1454
+ let stopped = false;
1455
+ let stoppedNow = false;
1456
+ const stop = event.stopPropagation.bind(event);
1457
+ const stopNow = event.stopImmediatePropagation.bind(event);
1458
+ Object.defineProperties(event, {
1459
+ target: {
1460
+ value: this,
1461
+ configurable: true
1462
+ },
1463
+ srcElement: {
1464
+ value: this,
1465
+ configurable: true
1466
+ },
1467
+ stopPropagation: {
1468
+ value: () => {
1469
+ stopped = true;
1470
+ stop();
1471
+ },
1472
+ configurable: true
1473
+ },
1474
+ stopImmediatePropagation: {
1475
+ value: () => {
1476
+ stopped = true;
1477
+ stoppedNow = true;
1478
+ stopNow();
1479
+ },
1480
+ configurable: true
1481
+ },
1482
+ composedPath: {
1483
+ value: () => path.slice(),
1484
+ configurable: true
1485
+ }
1486
+ });
1487
+ const invoke = (t, phase, capture) => {
1488
+ Object.defineProperties(event, {
1489
+ currentTarget: {
1490
+ value: t,
1491
+ configurable: true
1492
+ },
1493
+ eventPhase: {
1494
+ value: phase,
1495
+ configurable: true
1496
+ }
1497
+ });
1498
+ for (const l of (t.isoListeners.get(event.type) ?? []).slice()) {
1499
+ if (capture !== null && l.capture !== capture) continue;
1500
+ if (l.once) t.removeEventListener(event.type, l.fn, l.capture);
1501
+ if (typeof l.fn === "function") l.fn.call(t, event);
1502
+ else l.fn.handleEvent(event);
1503
+ if (stoppedNow) return;
1504
+ }
1505
+ };
1506
+ const phases = [];
1507
+ for (let i = path.length - 1; i > 0; i--) {
1508
+ const t = path[i];
1509
+ if (t) phases.push([
1510
+ t,
1511
+ 1,
1512
+ true
1513
+ ]);
1514
+ }
1515
+ phases.push([
1516
+ this,
1517
+ 2,
1518
+ null
1519
+ ]);
1520
+ if (event.bubbles) for (const t of path.slice(1)) phases.push([
1521
+ t,
1522
+ 3,
1523
+ false
1524
+ ]);
1525
+ for (const [t, phase, capture] of phases) {
1526
+ if (stopped) break;
1527
+ invoke(t, phase, capture);
1528
+ }
1529
+ Object.defineProperties(event, {
1530
+ currentTarget: {
1531
+ value: null,
1532
+ configurable: true
1533
+ },
1534
+ eventPhase: {
1535
+ value: 0,
1536
+ configurable: true
1537
+ }
1538
+ });
1539
+ return !event.defaultPrevented;
1540
+ }
1541
+ };
1542
+ WNode = class extends WEventTarget {
1543
+ static ELEMENT_NODE = 1;
1544
+ static TEXT_NODE = 3;
1545
+ static COMMENT_NODE = 8;
1546
+ static DOCUMENT_NODE = 9;
1547
+ static DOCUMENT_FRAGMENT_NODE = 11;
1548
+ ELEMENT_NODE = 1;
1549
+ TEXT_NODE = 3;
1550
+ COMMENT_NODE = 8;
1551
+ DOCUMENT_FRAGMENT_NODE = 11;
1552
+ ownerDocument;
1553
+ /** @internal */ isoId;
1554
+ /** @internal */ isoParent = null;
1555
+ /** @internal */ isoPrev = null;
1556
+ /** @internal */ isoNext = null;
1557
+ /** @internal Whether the host knows this node (it's in the tree under the root). */
1558
+ isoKnown = false;
1559
+ /**
1560
+ * @internal The root this node was rendered under, once it has been. Kept
1561
+ * after the node leaves the tree, so it can't move to another member's root
1562
+ * in a pool (ADR 0015, decision 3).
1563
+ */
1564
+ isoOwner = null;
1565
+ constructor(doc, id) {
1566
+ super();
1567
+ this.ownerDocument = doc;
1568
+ this.isoId = id;
1569
+ }
1570
+ /** @internal */ isoParentTarget() {
1571
+ return this.isoParent;
1572
+ }
1573
+ /**
1574
+ * @internal The id the host knows this node by: a render root is always
1575
+ * `ROOT_ID` to its own surface, whatever its id in the document.
1576
+ */
1577
+ get isoWire() {
1578
+ return this.isoOwner?.root === this ? 0 : this.isoId;
1579
+ }
1580
+ /** @internal */ isoListenChanged(type, on) {
1581
+ if (this.isoKnown) emit(this, [
1582
+ "listen",
1583
+ this.isoWire,
1584
+ type,
1585
+ on
1586
+ ]);
1587
+ }
1588
+ get parentNode() {
1589
+ return this.isoParent;
1590
+ }
1591
+ get parentElement() {
1592
+ return this.isoParent instanceof WElement ? this.isoParent : null;
1593
+ }
1594
+ get nextSibling() {
1595
+ return this.isoNext;
1596
+ }
1597
+ get previousSibling() {
1598
+ return this.isoPrev;
1599
+ }
1600
+ get firstChild() {
1601
+ return null;
1602
+ }
1603
+ get lastChild() {
1604
+ return null;
1605
+ }
1606
+ get childNodes() {
1607
+ return [];
1608
+ }
1609
+ get isConnected() {
1610
+ return this.isoKnown;
1611
+ }
1612
+ hasChildNodes() {
1613
+ return this.firstChild !== null;
1614
+ }
1615
+ contains(other) {
1616
+ for (let n = other; n; n = n.isoParent) if (n === this) return true;
1617
+ return false;
1618
+ }
1619
+ remove() {
1620
+ this.isoParent?.removeChild(this);
1621
+ }
1622
+ };
1623
+ WCharacterData = class extends WNode {
1624
+ /** @internal */ isoData;
1625
+ constructor(doc, id, data) {
1626
+ super(doc, id);
1627
+ this.isoData = data;
1628
+ }
1629
+ get data() {
1630
+ return this.isoData;
1631
+ }
1632
+ set data(v) {
1633
+ const data = str(v);
1634
+ if (data === this.isoData) return;
1635
+ this.isoData = data;
1636
+ if (this.isoKnown) emit(this, [
1637
+ "text",
1638
+ this.isoWire,
1639
+ data
1640
+ ]);
1641
+ }
1642
+ get length() {
1643
+ return this.isoData.length;
1644
+ }
1645
+ get textContent() {
1646
+ return this.isoData;
1647
+ }
1648
+ set textContent(v) {
1649
+ this.data = v ?? "";
1650
+ }
1651
+ get nodeValue() {
1652
+ return this.isoData;
1653
+ }
1654
+ set nodeValue(v) {
1655
+ this.data = v ?? "";
1656
+ }
1657
+ };
1658
+ WText = class extends WCharacterData {
1659
+ nodeType = 3;
1660
+ nodeName = "#text";
1661
+ };
1662
+ WComment = class extends WCharacterData {
1663
+ nodeType = 8;
1664
+ nodeName = "#comment";
1665
+ };
1666
+ kebab = (name) => name.startsWith("--") ? name : name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
1667
+ WDOMTokenList = class {
1668
+ /** @internal */ isoEl;
1669
+ constructor(el) {
1670
+ this.isoEl = el;
1671
+ }
1672
+ /** @internal */ isoTokens() {
1673
+ const tokens = [];
1674
+ for (const t of (this.isoEl.getAttribute("class") ?? "").split(/[\t\n\f\r ]+/)) if (t !== "" && !tokens.includes(t)) tokens.push(t);
1675
+ return tokens;
1676
+ }
1677
+ /** @internal */ isoWrite(tokens) {
1678
+ this.isoEl.setAttribute("class", tokens.join(" "));
1679
+ }
1680
+ get length() {
1681
+ return this.isoTokens().length;
1682
+ }
1683
+ get value() {
1684
+ return this.isoEl.getAttribute("class") ?? "";
1685
+ }
1686
+ set value(v) {
1687
+ this.isoEl.setAttribute("class", v);
1688
+ }
1689
+ item(i) {
1690
+ return this.isoTokens()[i] ?? null;
1691
+ }
1692
+ contains(token) {
1693
+ return this.isoTokens().includes(token);
1694
+ }
1695
+ add(...tokens) {
1696
+ const list = this.isoTokens();
1697
+ for (const t of tokens) if (!list.includes(t)) list.push(t);
1698
+ this.isoWrite(list);
1699
+ }
1700
+ remove(...tokens) {
1701
+ this.isoWrite(this.isoTokens().filter((t) => !tokens.includes(t)));
1702
+ }
1703
+ toggle(token, force) {
1704
+ const has = this.contains(token);
1705
+ const on = force ?? !has;
1706
+ if (on && !has) this.add(token);
1707
+ else if (!on && has) this.remove(token);
1708
+ return on;
1709
+ }
1710
+ replace(token, next) {
1711
+ const list = this.isoTokens();
1712
+ const i = list.indexOf(token);
1713
+ if (i < 0) return false;
1714
+ list[i] = next;
1715
+ this.isoWrite(list.filter((t, j) => list.indexOf(t) === j));
1716
+ return true;
1717
+ }
1718
+ toString() {
1719
+ return this.value;
1720
+ }
1721
+ [Symbol.iterator]() {
1722
+ return this.isoTokens()[Symbol.iterator]();
1723
+ }
1724
+ };
1725
+ dataAttr = (key) => `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
1726
+ dataKey = (attr) => attr.slice(5).replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
1727
+ WParentNode = class extends WNode {
1728
+ /** @internal */ isoFirst = null;
1729
+ /** @internal */ isoLast = null;
1730
+ /** @internal */ isoChildCache = null;
1731
+ get firstChild() {
1732
+ return this.isoFirst;
1733
+ }
1734
+ get lastChild() {
1735
+ return this.isoLast;
1736
+ }
1737
+ get childNodes() {
1738
+ if (!this.isoChildCache) {
1739
+ const list = [];
1740
+ for (let n = this.isoFirst; n; n = n.isoNext) list.push(n);
1741
+ this.isoChildCache = list;
1742
+ }
1743
+ return this.isoChildCache;
1744
+ }
1745
+ get children() {
1746
+ return this.childNodes.filter((n) => n instanceof WElement);
1747
+ }
1748
+ get firstElementChild() {
1749
+ return this.children[0] ?? null;
1750
+ }
1751
+ /** Text of the subtree; comments don't count, as in the DOM. */
1752
+ get textContent() {
1753
+ let out = "";
1754
+ for (let n = this.isoFirst; n; n = n.isoNext) if (!(n instanceof WComment)) out += n.textContent;
1755
+ return out;
1756
+ }
1757
+ set textContent(v) {
1758
+ this.replaceChildren(...v ? [this.ownerDocument.createTextNode(v)] : []);
1759
+ }
1760
+ appendChild(child) {
1761
+ return this.insertBefore(child, null);
1762
+ }
1763
+ insertBefore(child, ref) {
1764
+ if (!(child instanceof WNode)) throw new TypeError("insertBefore: not a node");
1765
+ if (ref && ref.isoParent !== this) throw domError("NotFoundError", "insertBefore: the reference node is not a child");
1766
+ if (child.contains(this)) throw domError("HierarchyRequestError", "insertBefore: would create a cycle");
1767
+ if (ref === child) ref = child.isoNext;
1768
+ if (child instanceof WDocumentFragment) {
1769
+ for (const c of child.childNodes) this.insertBefore(c, ref);
1770
+ return child;
1771
+ }
1772
+ if (this.ownerDocument.head === this && child instanceof WElement) this.ownerDocument.isoCore.onHead(child.localName);
1773
+ if (this.isoKnown && ownedElsewhere(child, this.isoOwner)) throw domError("HierarchyRequestError", "insertBefore: a node can't move to another member's root in a pool");
1774
+ const wasKnown = child.isoKnown;
1775
+ child.isoParent?.isoUnlink(child);
1776
+ this.isoLink(child, ref);
1777
+ const core = this.ownerDocument.isoCore;
1778
+ if (wasKnown && this.isoKnown) emit(this, [
1779
+ "move",
1780
+ this.isoWire,
1781
+ child.isoId,
1782
+ ref?.isoId ?? null
1783
+ ]);
1784
+ else if (wasKnown) {
1785
+ emit(child, ["remove", child.isoId]);
1786
+ forget(child, core);
1787
+ } else if (this.isoKnown) {
1788
+ emit(this, [
1789
+ "insert",
1790
+ this.isoWire,
1791
+ serialize(child),
1792
+ ref?.isoId ?? null
1793
+ ]);
1794
+ learn(child, core, this.isoOwner);
1795
+ }
1796
+ return child;
1797
+ }
1798
+ removeChild(child) {
1799
+ if (child.isoParent !== this) throw domError("NotFoundError", "removeChild: not a child");
1800
+ this.isoUnlink(child);
1801
+ if (child.isoKnown) {
1802
+ emit(child, ["remove", child.isoId]);
1803
+ forget(child, this.ownerDocument.isoCore);
1804
+ }
1805
+ return child;
1806
+ }
1807
+ replaceChildren(...nodes) {
1808
+ while (this.isoLast) this.removeChild(this.isoLast);
1809
+ this.append(...nodes);
1810
+ }
1811
+ append(...nodes) {
1812
+ for (const n of nodes) this.appendChild(typeof n === "string" ? this.ownerDocument.createTextNode(n) : n);
1813
+ }
1814
+ /** @internal */ isoUnlink(child) {
1815
+ if (child.isoPrev) child.isoPrev.isoNext = child.isoNext;
1816
+ else this.isoFirst = child.isoNext;
1817
+ if (child.isoNext) child.isoNext.isoPrev = child.isoPrev;
1818
+ else this.isoLast = child.isoPrev;
1819
+ child.isoParent = null;
1820
+ child.isoPrev = null;
1821
+ child.isoNext = null;
1822
+ this.isoChildCache = null;
1823
+ }
1824
+ /** @internal */ isoLink(child, ref) {
1825
+ child.isoParent = this;
1826
+ child.isoNext = ref;
1827
+ child.isoPrev = ref ? ref.isoPrev : this.isoLast;
1828
+ if (child.isoPrev) child.isoPrev.isoNext = child;
1829
+ else this.isoFirst = child;
1830
+ if (ref) ref.isoPrev = child;
1831
+ else this.isoLast = child;
1832
+ this.isoChildCache = null;
1833
+ }
1834
+ };
1835
+ WDocumentFragment = class extends WParentNode {
1836
+ nodeType = 11;
1837
+ nodeName = "#document-fragment";
1838
+ get nodeValue() {
1839
+ return null;
1840
+ }
1841
+ set nodeValue(_v) {}
1842
+ };
1843
+ WElement = class extends WParentNode {
1844
+ nodeType = 1;
1845
+ localName;
1846
+ namespaceURI;
1847
+ /** @internal */ isoNs;
1848
+ /** @internal */ isoAttrs = /* @__PURE__ */ new Map();
1849
+ /** @internal */ isoProps = /* @__PURE__ */ new Map();
1850
+ /** @internal */ isoStyle = null;
1851
+ /** @internal */ isoClassList = null;
1852
+ /** @internal */ isoDataset = null;
1853
+ /** @internal The offsets the last `scroll` event brought (design §4.6). */
1854
+ isoScroll = {
1855
+ top: 0,
1856
+ left: 0
1857
+ };
1858
+ constructor(doc, id, localName, ns) {
1859
+ super(doc, id);
1860
+ this.localName = localName;
1861
+ this.isoNs = ns;
1862
+ this.namespaceURI = ns === "svg" ? SVG_NS : HTML_NS;
1863
+ }
1864
+ get tagName() {
1865
+ return this.isoNs === "html" ? this.localName.toUpperCase() : this.localName;
1866
+ }
1867
+ get nodeName() {
1868
+ return this.tagName;
1869
+ }
1870
+ get nodeValue() {
1871
+ return null;
1872
+ }
1873
+ set nodeValue(_v) {}
1874
+ get attributes() {
1875
+ return [...this.isoAttrs].map(([name, value]) => ({
1876
+ name,
1877
+ value
1878
+ }));
1879
+ }
1880
+ getAttribute(name) {
1881
+ return this.isoAttrs.get(this.isoAttrName(name)) ?? null;
1882
+ }
1883
+ hasAttribute(name) {
1884
+ return this.isoAttrs.has(this.isoAttrName(name));
1885
+ }
1886
+ setAttribute(name, value) {
1887
+ const n = this.isoAttrName(name);
1888
+ const v = str(value);
1889
+ if (this.isoAttrs.get(n) === v) return;
1890
+ this.isoAttrs.set(n, v);
1891
+ if (this.isoKnown) emit(this, [
1892
+ "attr",
1893
+ this.isoWire,
1894
+ n,
1895
+ v
1896
+ ]);
1897
+ }
1898
+ removeAttribute(name) {
1899
+ const n = this.isoAttrName(name);
1900
+ if (!this.isoAttrs.delete(n)) return;
1901
+ if (this.isoKnown) emit(this, [
1902
+ "attr",
1903
+ this.isoWire,
1904
+ n,
1905
+ null
1906
+ ]);
1907
+ }
1908
+ /** @internal HTML attribute names are case-insensitive; SVG ones aren't. */
1909
+ isoAttrName(name) {
1910
+ return this.isoNs === "html" ? name.toLowerCase() : name;
1911
+ }
1912
+ get style() {
1913
+ this.isoStyle ??= createStyle(this);
1914
+ return this.isoStyle;
1915
+ }
1916
+ get classList() {
1917
+ this.isoClassList ??= new WDOMTokenList(this);
1918
+ return this.isoClassList;
1919
+ }
1920
+ get dataset() {
1921
+ this.isoDataset ??= createDataset(this);
1922
+ return this.isoDataset;
1923
+ }
1924
+ /**
1925
+ * Read only, and as of the last `scroll` event the element got: the host
1926
+ * owns scrolling. 0 until the element is scrolled and listens for `scroll`.
1927
+ */
1928
+ get scrollTop() {
1929
+ return this.isoScroll.top;
1930
+ }
1931
+ get scrollLeft() {
1932
+ return this.isoScroll.left;
1933
+ }
1934
+ get id() {
1935
+ return this.getAttribute("id") ?? "";
1936
+ }
1937
+ set id(v) {
1938
+ this.setAttribute("id", v);
1939
+ }
1940
+ /** @internal */ isoSetProp(name, value, record) {
1941
+ if (this.isoProps.get(name) === value) return;
1942
+ this.isoProps.set(name, value);
1943
+ if (record && this.isoKnown) emit(this, [
1944
+ "prop",
1945
+ this.isoWire,
1946
+ name,
1947
+ value
1948
+ ]);
1949
+ }
1950
+ };
1951
+ HANDLER_EVENTS = [
1952
+ "abort",
1953
+ "animationend",
1954
+ "animationiteration",
1955
+ "animationstart",
1956
+ "auxclick",
1957
+ "beforeinput",
1958
+ "blur",
1959
+ "cancel",
1960
+ "change",
1961
+ "click",
1962
+ "close",
1963
+ "contextmenu",
1964
+ "copy",
1965
+ "cut",
1966
+ "dblclick",
1967
+ "drag",
1968
+ "dragend",
1969
+ "dragenter",
1970
+ "dragleave",
1971
+ "dragover",
1972
+ "dragstart",
1973
+ "drop",
1974
+ "error",
1975
+ "focus",
1976
+ "input",
1977
+ "invalid",
1978
+ "keydown",
1979
+ "keypress",
1980
+ "keyup",
1981
+ "load",
1982
+ "mousedown",
1983
+ "mouseenter",
1984
+ "mouseleave",
1985
+ "mousemove",
1986
+ "mouseout",
1987
+ "mouseover",
1988
+ "mouseup",
1989
+ "paste",
1990
+ "pointercancel",
1991
+ "pointerdown",
1992
+ "pointerenter",
1993
+ "pointerleave",
1994
+ "pointermove",
1995
+ "pointerout",
1996
+ "pointerover",
1997
+ "pointerup",
1998
+ "reset",
1999
+ "resize",
2000
+ "scroll",
2001
+ "select",
2002
+ "submit",
2003
+ "toggle",
2004
+ "touchcancel",
2005
+ "touchend",
2006
+ "touchmove",
2007
+ "touchstart",
2008
+ "transitionend",
2009
+ "wheel"
2010
+ ];
2011
+ defineHandlers(WElement.prototype);
2012
+ WHTMLElement = class extends WElement {};
2013
+ WSVGElement = class extends WElement {};
2014
+ WHTMLIFrameElement = class extends WHTMLElement {};
2015
+ WHTMLInputElement = class extends WHTMLElement {
2016
+ get value() {
2017
+ const v = this.isoProps.get("value");
2018
+ return typeof v === "string" ? v : this.getAttribute("value") ?? "";
2019
+ }
2020
+ set value(v) {
2021
+ this.isoSetProp("value", str(v), true);
2022
+ }
2023
+ get checked() {
2024
+ const v = this.isoProps.get("checked");
2025
+ return typeof v === "boolean" ? v : this.hasAttribute("checked");
2026
+ }
2027
+ set checked(v) {
2028
+ this.isoSetProp("checked", Boolean(v), true);
2029
+ }
2030
+ get defaultValue() {
2031
+ return this.getAttribute("value") ?? "";
2032
+ }
2033
+ set defaultValue(v) {
2034
+ this.setAttribute("value", v);
2035
+ }
2036
+ get defaultChecked() {
2037
+ return this.hasAttribute("checked");
2038
+ }
2039
+ set defaultChecked(v) {
2040
+ if (v) this.setAttribute("checked", "");
2041
+ else this.removeAttribute("checked");
2042
+ }
2043
+ get name() {
2044
+ return this.getAttribute("name") ?? "";
2045
+ }
2046
+ set name(v) {
2047
+ this.setAttribute("name", v);
2048
+ }
2049
+ get type() {
2050
+ return this.getAttribute("type") ?? "text";
2051
+ }
2052
+ set type(v) {
2053
+ this.setAttribute("type", v);
2054
+ }
2055
+ };
2056
+ WHTMLTextAreaElement = class extends WHTMLElement {
2057
+ get value() {
2058
+ const v = this.isoProps.get("value");
2059
+ return typeof v === "string" ? v : this.textContent;
2060
+ }
2061
+ set value(v) {
2062
+ this.isoSetProp("value", str(v), true);
2063
+ }
2064
+ get defaultValue() {
2065
+ return this.textContent;
2066
+ }
2067
+ set defaultValue(v) {
2068
+ this.textContent = v;
2069
+ }
2070
+ get name() {
2071
+ return this.getAttribute("name") ?? "";
2072
+ }
2073
+ set name(v) {
2074
+ this.setAttribute("name", v);
2075
+ }
2076
+ };
2077
+ WHTMLSelectElement = class extends WHTMLElement {
2078
+ /** The `<option>`s under the select, `<optgroup>`s included, in tree order. React walks it. */
2079
+ get options() {
2080
+ const out = [];
2081
+ const walk = (el) => {
2082
+ for (const c of el.children) if (c instanceof WHTMLOptionElement) out.push(c);
2083
+ else if (c.localName === "optgroup") walk(c);
2084
+ };
2085
+ walk(this);
2086
+ return out;
2087
+ }
2088
+ get multiple() {
2089
+ return this.hasAttribute("multiple");
2090
+ }
2091
+ set multiple(v) {
2092
+ if (v) this.setAttribute("multiple", "");
2093
+ else this.removeAttribute("multiple");
2094
+ }
2095
+ get value() {
2096
+ const v = this.isoProps.get("value");
2097
+ return typeof v === "string" ? v : "";
2098
+ }
2099
+ set value(v) {
2100
+ this.isoSetProp("value", str(v), true);
2101
+ }
2102
+ get name() {
2103
+ return this.getAttribute("name") ?? "";
2104
+ }
2105
+ set name(v) {
2106
+ this.setAttribute("name", v);
2107
+ }
2108
+ };
2109
+ WHTMLOptionElement = class extends WHTMLElement {
2110
+ /** The `value` attribute, or the text when there's none, as in the DOM. */
2111
+ get value() {
2112
+ return this.getAttribute("value") ?? this.textContent;
2113
+ }
2114
+ set value(v) {
2115
+ this.setAttribute("value", v);
2116
+ }
2117
+ get selected() {
2118
+ const v = this.isoProps.get("selected");
2119
+ return typeof v === "boolean" ? v : this.hasAttribute("selected");
2120
+ }
2121
+ set selected(v) {
2122
+ this.isoSetProp("selected", Boolean(v), true);
2123
+ }
2124
+ get defaultSelected() {
2125
+ return this.hasAttribute("selected");
2126
+ }
2127
+ set defaultSelected(v) {
2128
+ if (v) this.setAttribute("selected", "");
2129
+ else this.removeAttribute("selected");
2130
+ }
2131
+ get disabled() {
2132
+ return this.hasAttribute("disabled");
2133
+ }
2134
+ set disabled(v) {
2135
+ if (v) this.setAttribute("disabled", "");
2136
+ else this.removeAttribute("disabled");
2137
+ }
2138
+ };
2139
+ HTML_CLASSES = {
2140
+ input: WHTMLInputElement,
2141
+ textarea: WHTMLTextAreaElement,
2142
+ select: WHTMLSelectElement,
2143
+ option: WHTMLOptionElement,
2144
+ iframe: WHTMLIFrameElement
2145
+ };
2146
+ WDocument = class extends WEventTarget {
2147
+ nodeType = 9;
2148
+ nodeName = "#document";
2149
+ /** @internal */ isoCore;
2150
+ /** Set by `install()`: the worker global. */
2151
+ defaultView = null;
2152
+ activeElement = null;
2153
+ /** `null`, as for every document. */
2154
+ ownerDocument = null;
2155
+ /** A detached body, for code that falls back to `document.body`. */
2156
+ body;
2157
+ /**
2158
+ * A detached head: React 19 hoists `<title>`, `<meta>` and `<link>` into
2159
+ * it. The bridge doesn't render it (M3a task 3).
2160
+ */
2161
+ head;
2162
+ constructor(core) {
2163
+ super();
2164
+ this.isoCore = core;
2165
+ this.body = new WHTMLElement(this, -1, "body", "html");
2166
+ this.head = new WHTMLElement(this, -2, "head", "html");
2167
+ }
2168
+ createElement(tag) {
2169
+ const t = tag.toLowerCase();
2170
+ return new ((Object.hasOwn(HTML_CLASSES, t) ? HTML_CLASSES[t] : void 0) ?? WHTMLElement)(this, this.isoCore.nextId++, t, "html");
2171
+ }
2172
+ createElementNS(ns, tag) {
2173
+ if (ns === SVG_NS) return new WSVGElement(this, this.isoCore.nextId++, tag, "svg");
2174
+ if (ns === HTML_NS || ns === null) return this.createElement(tag);
2175
+ throw domError("NotSupportedError", `createElementNS: namespace ${ns} isn't supported`);
2176
+ }
2177
+ /** `data` is converted with `String()`, as in the DOM: Preact passes numbers. */
2178
+ createTextNode(data) {
2179
+ return new WText(this, this.isoCore.nextId++, String(data));
2180
+ }
2181
+ createComment(data) {
2182
+ return new WComment(this, this.isoCore.nextId++, String(data));
2183
+ }
2184
+ /** Fragments never reach the host, so they take no id from the shared counter. */
2185
+ createDocumentFragment() {
2186
+ return new WDocumentFragment(this, -3);
2187
+ }
2188
+ /**
2189
+ * The first element in tree order with this `id` (DOM group 1, ADR 0010):
2190
+ * under the render root, then the detached head. Nodes not yet inserted
2191
+ * aren't in the document, so they aren't found.
2192
+ */
2193
+ getElementById(id) {
2194
+ const walk = (el) => {
2195
+ for (const c of el.children) {
2196
+ if (c.getAttribute("id") === id) return c;
2197
+ const deeper = walk(c);
2198
+ if (deeper) return deeper;
2199
+ }
2200
+ return null;
2201
+ };
2202
+ for (const root of this.isoCore.roots) {
2203
+ const hit = walk(root);
2204
+ if (hit) return hit;
2205
+ }
2206
+ return walk(this.head);
2207
+ }
2208
+ /**
2209
+ * Type selectors only, alone or as a `head > title` child chain: what React
2210
+ * 19 asks when it hoists a `<title>`. Queries in general are DOM group 2
2211
+ * (ADR 0010), built when a library needs them; anything else throws.
2212
+ */
2213
+ querySelector(selector) {
2214
+ const steps = selector.split(">").map((t) => t.trim().toLowerCase());
2215
+ if (!steps.every((t) => /^[a-z][a-z0-9-]*$/.test(t))) throw domError("NotSupportedError", `querySelector: "${selector}" isn't supported yet`);
2216
+ const matches = (el) => {
2217
+ let n = el;
2218
+ for (let i = steps.length - 1; i >= 0; i--) {
2219
+ if (!n || n.localName !== steps[i]) return false;
2220
+ n = i > 0 ? n.parentElement : null;
2221
+ }
2222
+ return true;
2223
+ };
2224
+ const walk = (el) => {
2225
+ for (const c of el.children) {
2226
+ if (matches(c)) return c;
2227
+ const deeper = walk(c);
2228
+ if (deeper) return deeper;
2229
+ }
2230
+ return null;
2231
+ };
2232
+ for (const top of [this.head, this.body]) {
2233
+ if (matches(top)) return top;
2234
+ const hit = walk(top);
2235
+ if (hit) return hit;
2236
+ }
2237
+ return null;
2238
+ }
2239
+ };
2240
+ defineHandlers(WDocument.prototype);
2241
+ isControl = (node) => node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement;
2242
+ }));
2243
+ // ../dom/dist/install-D7m7By8i.js
2244
+ /**
2245
+ * Exposes `dom` as the worker's `document`, `window` and DOM classes, so
2246
+ * frameworks find them where they look. Only for isolates with a surface; a
2247
+ * headless isolate never calls this.
2248
+ */
2249
+ function install(dom, scope) {
2250
+ const define = (name, value) => {
2251
+ Object.defineProperty(scope, name, {
2252
+ value,
2253
+ configurable: true,
2254
+ writable: true
2255
+ });
2256
+ };
2257
+ define("document", dom.document);
2258
+ if (!("window" in scope)) define("window", scope);
2259
+ for (const [name, value] of Object.entries(DOM_GLOBALS)) define(name, value);
2260
+ dom.document.defaultView = scope;
2261
+ }
2262
+ var DOM_GLOBALS;
2263
+ var init_install_D7m7By8i = __esmMin((() => {
2264
+ init_dom_yLsf0Z4e();
2265
+ DOM_GLOBALS = {
2266
+ Node: WNode,
2267
+ Element: WElement,
2268
+ HTMLElement: WHTMLElement,
2269
+ SVGElement: WSVGElement,
2270
+ Text: WText,
2271
+ Comment: WComment,
2272
+ DocumentFragment: WDocumentFragment,
2273
+ HTMLInputElement: WHTMLInputElement,
2274
+ HTMLTextAreaElement: WHTMLTextAreaElement,
2275
+ HTMLSelectElement: WHTMLSelectElement,
2276
+ HTMLOptionElement: WHTMLOptionElement,
2277
+ HTMLIFrameElement: WHTMLIFrameElement,
2278
+ DOMTokenList: WDOMTokenList
2279
+ };
2280
+ }));
2281
+ // ../dom/dist/worker.js
2282
+ var init_worker = __esmMin((() => {
2283
+ init_records_wVZrPpqr();
2284
+ init_dom_yLsf0Z4e();
2285
+ init_install_D7m7By8i();
2286
+ }));
2287
+ // src/render/index.ts
2288
+ function sharedDom(scope) {
2289
+ if (!shared) {
2290
+ shared = createDom({
2291
+ onBatch: () => {},
2292
+ onHead: (tag) => {
2293
+ for (const fn of headListeners) fn(tag);
2294
+ }
2295
+ });
2296
+ if (scope) install(shared, scope);
2297
+ }
2298
+ return shared;
2299
+ }
2300
+ /**
2301
+ * Builds the DOM subset and posts its batches. With `scope`, also installs it
2302
+ * as that global's `document` and DOM classes, which frameworks need. With
2303
+ * `pooled`, the isolate gets its own root in the worker's shared document
2304
+ * instead (ADR 0015).
2305
+ */
2306
+ function createRender(post, scope, pooled = false, member = null) {
2307
+ const owner = member === null ? null : busy.of(member);
2308
+ const schedule = (flush) => {
2309
+ if (owner === null || member === null) {
2310
+ queueMicrotask(flush);
2311
+ return;
2312
+ }
2313
+ busy.report(member, owner.life);
2314
+ nativeQueueMicrotask(() => {
2315
+ busy.run(owner, flush, void 0, []);
2316
+ });
2317
+ };
2318
+ let pendingStyles = [];
2319
+ let pendingHead = [];
2320
+ /** Head tags already reported: each goes to the host once. */
2321
+ const headSeen = /* @__PURE__ */ new Set();
2322
+ let extrasScheduled = false;
2323
+ const postPatch = (batch) => {
2324
+ const styles = pendingStyles;
2325
+ const head = pendingHead;
2326
+ pendingStyles = [];
2327
+ pendingHead = [];
2328
+ post({
2329
+ v: 1,
2330
+ t: "patch",
2331
+ p: {
2332
+ fmt: ISOLOOP_DOM_FMT,
2333
+ batch,
2334
+ ...styles.length > 0 ? { styles } : {},
2335
+ ...head.length > 0 ? { head } : {}
2336
+ }
2337
+ });
2338
+ };
2339
+ /** Styles or head tags with no DOM change still need a patch to travel in. */
2340
+ const scheduleExtras = () => {
2341
+ if (extrasScheduled) return;
2342
+ extrasScheduled = true;
2343
+ queueMicrotask(() => {
2344
+ extrasScheduled = false;
2345
+ target.flush();
2346
+ if (pendingStyles.length > 0 || pendingHead.length > 0) postPatch([]);
2347
+ });
2348
+ };
2349
+ const onHead = (tag) => {
2350
+ if (headSeen.has(tag)) return;
2351
+ headSeen.add(tag);
2352
+ pendingHead.push(tag);
2353
+ scheduleExtras();
2354
+ };
2355
+ let target;
2356
+ if (pooled) {
2357
+ const own = sharedDom(scope).addRoot({
2358
+ onBatch: postPatch,
2359
+ schedule
2360
+ });
2361
+ headListeners.add(onHead);
2362
+ target = {
2363
+ ...own,
2364
+ dispose() {
2365
+ headListeners.delete(onHead);
2366
+ own.dispose();
2367
+ }
2368
+ };
2369
+ } else {
2370
+ const dom = createDom({
2371
+ onBatch: postPatch,
2372
+ schedule,
2373
+ onHead
2374
+ });
2375
+ if (scope) install(dom, scope);
2376
+ target = {
2377
+ root: dom.root,
2378
+ flush: () => dom.flush(),
2379
+ deliver: (event) => dom.deliver(event),
2380
+ idOf: (node) => node.isConnected ? dom.idOf(node) : void 0,
2381
+ setValue: (node, value, o) => dom.setValue(node, value, o),
2382
+ dispose: () => {}
2383
+ };
2384
+ }
2385
+ return {
2386
+ fmt: ISOLOOP_DOM_FMT,
2387
+ root: target.root,
2388
+ flush: () => target.flush(),
2389
+ setValue: (node, value, o) => target.setValue(node, value, o),
2390
+ dispose: () => target.dispose(),
2391
+ styles(css) {
2392
+ pendingStyles.push(...typeof css === "string" ? [css] : css);
2393
+ scheduleExtras();
2394
+ },
2395
+ idOf(node) {
2396
+ if (!(node instanceof WNode)) return void 0;
2397
+ const id = target.idOf(node);
2398
+ return id === void 0 ? void 0 : String(id);
2399
+ },
2400
+ receive(e) {
2401
+ const t = nodeId(e.target);
2402
+ if (t === void 0) return;
2403
+ const currentTargets = e.currentTargets.map(nodeId).filter((n) => n !== void 0);
2404
+ const { target: _t, currentTargets: _c, ...rest } = e;
2405
+ target.deliver({
2406
+ ...rest,
2407
+ target: t,
2408
+ currentTargets
2409
+ });
2410
+ }
2411
+ };
2412
+ }
2413
+ var nodeId, shared, headListeners;
2414
+ var init_render = __esmMin((() => {
2415
+ init_worker();
2416
+ nodeId = (s) => /^\d+$/.test(s) ? Number(s) : void 0;
2417
+ shared = null;
2418
+ headListeners = /* @__PURE__ */ new Set();
2419
+ }));
2420
+ // package.json
2421
+ var version = "0.1.0-next.0";
2422
+ // src/vanilla.ts
2423
+ var vanilla_exports = /* @__PURE__ */ __exportAll({
2424
+ REQUIRES: () => REQUIRES,
2425
+ createVanillaIsolate: () => createVanillaIsolate,
2426
+ defineIsolate: () => defineIsolate
2427
+ });
2428
+ /**
2429
+ * Types an isolate module's default export and stamps it with the version
2430
+ * it was built against. `Root` defaults to the structural `IsolateRoot`.
2431
+ */
2432
+ function defineIsolate(def) {
2433
+ return {
2434
+ requires: REQUIRES,
2435
+ ...def
2436
+ };
2437
+ }
2438
+ /** Builds the context for `start(ctx)`. `scope` is the worker global the DOM subset installs on. */
2439
+ function createVanillaIsolate(init, post, scope, pooled = false, member = null) {
2440
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled, member);
2441
+ const calls = createHostCalls({
2442
+ post,
2443
+ beforeCall: () => render?.flush(),
2444
+ idOf: (node) => render ? render.idOf(node) : void 0,
2445
+ surface: render !== null,
2446
+ navigate: init.grants.navigate === true
2447
+ });
2448
+ const awake = createKeepAwake();
2449
+ const bus = createBusClient(init.busPort, {
2450
+ ...init.wake ? { wake: true } : {},
2451
+ ...init.commitIntervalMs === void 0 ? {} : { commitIntervalMs: init.commitIntervalMs },
2452
+ onError: (err) => {
2453
+ post({
2454
+ v: 1,
2455
+ t: "error",
2456
+ p: err instanceof Error && err.stack !== void 0 ? {
2457
+ message: err.message,
2458
+ stack: err.stack,
2459
+ fatal: false
2460
+ } : {
2461
+ message: String(err),
2462
+ fatal: false
2463
+ }
2464
+ });
2465
+ }
2466
+ });
2467
+ const onShutdown = [];
2468
+ let portal;
2469
+ const ctx = {
2470
+ id: init.isolateId,
2471
+ config: init.config,
2472
+ root: render?.root,
2473
+ portalRoot: void 0,
2474
+ reportError(error, o = {}) {
2475
+ const fatal = o.fatal ?? true;
2476
+ post({
2477
+ v: 1,
2478
+ t: "error",
2479
+ p: error instanceof Error ? {
2480
+ message: error.message,
2481
+ ...error.stack === void 0 ? {} : { stack: error.stack },
2482
+ fatal
2483
+ } : {
2484
+ message: String(error),
2485
+ fatal
2486
+ }
2487
+ });
2488
+ },
2489
+ host: calls.api,
2490
+ bus: bus.client,
2491
+ styles: (css) => render?.styles(css),
2492
+ setValue(node, value, o) {
2493
+ if (!render) return;
2494
+ if (!(node instanceof WNode)) throw new TypeError("setValue: not a node of this isolate");
2495
+ render.setValue(node, value, o);
2496
+ },
2497
+ onShutdown: (fn) => {
2498
+ onShutdown.push(fn);
2499
+ },
2500
+ keepAwake: () => awake.hold()
2501
+ };
2502
+ if (member !== null) Object.defineProperty(ctx, BUSY, {
2503
+ value: {
2504
+ claim: (container) => {
2505
+ busy.claim(container, member);
2506
+ },
2507
+ bind: (fn) => busy.bind(fn)
2508
+ },
2509
+ enumerable: false
2510
+ });
2511
+ Object.defineProperty(ctx, "portalRoot", {
2512
+ enumerable: false,
2513
+ get() {
2514
+ if (!render) return void 0;
2515
+ if (!portal) {
2516
+ const { root } = render;
2517
+ const div = root.ownerDocument.createElement("div");
2518
+ div.setAttribute("data-isoloop-portal", "");
2519
+ queueMicrotask(() => {
2520
+ if (div.parentNode !== root) root.appendChild(div);
2521
+ });
2522
+ portal = div;
2523
+ }
2524
+ return portal;
2525
+ }
2526
+ });
2527
+ return {
2528
+ ctx,
2529
+ renderFmt: render ? render.fmt : "none",
2530
+ receive(msg) {
2531
+ if (isHostToIsolate(msg)) {
2532
+ if (msg.t === "event") render?.receive(msg.p);
2533
+ else if (msg.t === "reattach") bus.reattach(msg.p.busPort);
2534
+ else if (msg.t === "result" && msg.re !== void 0) calls.receive(msg.re, msg.p);
2535
+ }
2536
+ },
2537
+ idle() {
2538
+ const b = bus.idle();
2539
+ return {
2540
+ sinceDeliveryMs: b.sinceDeliveryMs,
2541
+ inFlight: b.inFlight + calls.pending(),
2542
+ holds: awake.report(performance.now())
2543
+ };
2544
+ },
2545
+ async shutdown(reason) {
2546
+ await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
2547
+ await bus.close();
2548
+ render?.flush();
2549
+ render?.dispose();
2550
+ }
2551
+ };
2552
+ }
2553
+ var REQUIRES;
2554
+ var init_vanilla = __esmMin((() => {
2555
+ init_dist();
2556
+ init_bus_client();
2557
+ init_busy();
2558
+ init_host_calls();
2559
+ init_keep_awake();
2560
+ init_worker();
2561
+ init_render();
2562
+ REQUIRES = majorMinor(version) ?? "0.0";
2563
+ }));
2564
+ // src/bootstrap.ts
2565
+ init_dist();
2566
+ init_busy();
2567
+ let mode = null;
2568
+ const members = /* @__PURE__ */ new Map();
2569
+ const postWorker = (msg) => {
2570
+ self.postMessage(msg);
2571
+ };
2572
+ const memberPost = (name) => (msg) => {
2573
+ self.postMessage(name === void 0 ? msg : {
2574
+ ...msg,
2575
+ isolate: name
2576
+ });
2577
+ };
2578
+ const fatal = (m, message, code) => {
2579
+ m.post({
2580
+ v: 1,
2581
+ t: "error",
2582
+ p: code ? {
2583
+ message,
2584
+ fatal: true,
2585
+ code
2586
+ } : {
2587
+ message,
2588
+ fatal: true
2589
+ }
2590
+ });
2591
+ };
2592
+ let beating = false;
2593
+ /** Once per worker, after the first isolate's protocol check. */
2594
+ function startHeartbeat(everyMs) {
2595
+ if (beating) return;
2596
+ beating = true;
2597
+ let last = performance.now();
2598
+ setInterval(() => {
2599
+ const now = performance.now();
2600
+ const lagMs = Math.max(0, now - last - everyMs);
2601
+ if (mode === "pool") {
2602
+ const reports = {};
2603
+ for (const m of members.values()) if (m.name !== void 0 && m.idleReport) reports[m.name] = m.idleReport();
2604
+ postWorker({
2605
+ v: 1,
2606
+ t: "beat",
2607
+ p: {
2608
+ lagMs,
2609
+ members: reports
2610
+ }
2611
+ });
2612
+ } else {
2613
+ const idle = members.get(void 0)?.idleReport?.();
2614
+ postWorker({
2615
+ v: 1,
2616
+ t: "beat",
2617
+ p: idle ? {
2618
+ lagMs,
2619
+ idle
2620
+ } : { lagMs }
2621
+ });
2622
+ }
2623
+ last = now;
2624
+ }, everyMs);
2625
+ }
2626
+ /** `shutdown` for a member: `bye` once its handlers settle or the grace runs out. */
2627
+ function shutdownMember(m, graceMs, reason) {
2628
+ if (members.get(m.name) === m) members.delete(m.name);
2629
+ m.receive = null;
2630
+ const hook = m.shutdownHook;
2631
+ const done = (hook ? busy.run(busy.of(m.name, m.life), hook, void 0, [reason]) : void 0) ?? Promise.resolve();
2632
+ const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2633
+ Promise.race([done, grace]).finally(() => {
2634
+ busy.end(m.life);
2635
+ m.post({
2636
+ v: 1,
2637
+ t: "bye",
2638
+ p: {}
2639
+ });
2640
+ if (members.size === 0) self.close();
2641
+ });
2642
+ }
2643
+ /** Routes one message from the host to the member it is for. */
2644
+ function route(msg) {
2645
+ const m = members.get(mode === "pool" ? msg.isolate : void 0);
2646
+ if (!m) return;
2647
+ if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2648
+ else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2649
+ }
2650
+ async function boot(m, init) {
2651
+ if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
2652
+ fatal(m, `Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
2653
+ return;
2654
+ }
2655
+ startHeartbeat(init.heartbeatMs);
2656
+ const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
2657
+ const runtime = busy.run(busy.of(m.name, m.life), createVanillaIsolate, void 0, [
2658
+ init,
2659
+ m.post,
2660
+ self,
2661
+ mode === "pool",
2662
+ m.name
2663
+ ]);
2664
+ let mod;
2665
+ try {
2666
+ mod = await import(
2667
+ /* @vite-ignore */
2668
+ init.src
2669
+ );
2670
+ } catch (err) {
2671
+ const why = err instanceof Error ? err.message : String(err);
2672
+ const cross = new URL(init.src).origin !== self.location.origin;
2673
+ fatal(m, `Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
2674
+ return;
2675
+ }
2676
+ const main = typeof mod === "object" && mod !== null && "default" in mod ? mod.default : void 0;
2677
+ if (typeof main === "object" && main !== null && "start" in main) {
2678
+ const start = main.start;
2679
+ if (typeof start === "function") {
2680
+ const requires = "requires" in main ? main.requires : void 0;
2681
+ await startIsolate(m, runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
2682
+ return;
2683
+ }
2684
+ }
2685
+ fatal(m, `${init.src} has no default export with start(ctx)`);
2686
+ }
2687
+ async function startIsolate(m, runtime, start, requires) {
2688
+ m.receive = (msg) => {
2689
+ runtime.receive(msg);
2690
+ };
2691
+ m.shutdownHook = (reason) => runtime.shutdown(reason);
2692
+ m.idleReport = () => ({
2693
+ ...runtime.idle(),
2694
+ busyMs: busy.take(m.name)
2695
+ });
2696
+ m.post({
2697
+ v: 1,
2698
+ t: "ready",
2699
+ p: {
2700
+ runtime: "@isoloop/runtime",
2701
+ adapter: "vanilla",
2702
+ renderFmt: runtime.renderFmt,
2703
+ ...requires === void 0 ? {} : { requires }
2704
+ }
2705
+ });
2706
+ try {
2707
+ await busy.run(busy.of(m.name, m.life), start, void 0, [runtime.ctx]);
2708
+ } catch (err) {
2709
+ fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
2710
+ }
2711
+ }
2712
+ /** Handles one message from the host: `init` boots a member, the rest is routed. */
2713
+ function onMessage(e) {
2714
+ const msg = e.data;
2715
+ if (!isHostToIsolate(msg)) return;
2716
+ if (msg.t !== "init") {
2717
+ route(msg);
2718
+ return;
2719
+ }
2720
+ const name = msg.isolate;
2721
+ const wants = name === void 0 ? "own" : "pool";
2722
+ if (mode === "own" || mode === "pool" && wants === "own") return;
2723
+ if (mode === null) {
2724
+ mode = wants;
2725
+ if (mode === "pool") freezeBuiltins();
2726
+ }
2727
+ if (members.has(name)) return;
2728
+ const m = {
2729
+ name,
2730
+ life: busy.begin(name),
2731
+ post: memberPost(name),
2732
+ shutdownHook: null,
2733
+ idleReport: null,
2734
+ receive: null
2735
+ };
2736
+ members.set(name, m);
2737
+ boot(m, msg.p).catch((err) => {
2738
+ fatal(m, err instanceof Error ? err.message : String(err));
2739
+ });
2740
+ }
2741
+ const STARTED = Symbol.for("isoloop.bootstrap");
2742
+ function startOnce() {
2743
+ installBusy(self, busy);
2744
+ self.addEventListener("message", onMessage);
2745
+ }
2746
+ if (Reflect.get(self, STARTED) === true) {
2747
+ if (import.meta.env?.DEV === true) console.warn("isoloop: worker entry evaluated twice; ignoring");
2748
+ } else {
2749
+ Reflect.set(self, STARTED, true);
2750
+ startOnce();
2751
+ }