@isoloop/runtime 0.0.0-next.56111e3

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