@isoloop/runtime 0.0.0-next.69da74b → 0.0.0-next.d028bc1

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