@ewe-studios/foundation-wasm-ui 0.0.0-stage → 0.1.13

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,2164 @@
1
+ // Browser document registry, events, transport and component lifecycle.
2
+ import { ConnectionManager } from "./foundation-ui-connections.js";
3
+
4
+ // Reserved node ids (gap inventory G1): 0=<head>, 1=<body>, 2=<html>. Macro ids ≥ 1000.
5
+ export const RESERVED = Object.freeze({ HEAD: 0, BODY: 1, HTML: 2 });
6
+
7
+ export class NodeRegistry {
8
+ constructor() {
9
+ this.nodes = new Map();
10
+ // Created-but-not-yet-registered nodes (CreateElement/CreateTextNode do NOT
11
+ // auto-register — feature 01): REGISTER_NODE promotes them into `nodes`.
12
+ this.pending = new Map();
13
+ }
14
+
15
+ /** Seed the reserved ambient nodes from a document (browser) — optional in tests. */
16
+ seedDocument(doc) {
17
+ if (doc.head) this.nodes.set(RESERVED.HEAD, doc.head);
18
+ if (doc.body) this.nodes.set(RESERVED.BODY, doc.body);
19
+ if (doc.documentElement) this.nodes.set(RESERVED.HTML, doc.documentElement);
20
+ return this;
21
+ }
22
+
23
+ register(id, node) {
24
+ this.nodes.set(id, node);
25
+ return node;
26
+ }
27
+
28
+ get(id) {
29
+ return this.nodes.get(id);
30
+ }
31
+
32
+ /** Look up `id`, throwing a clear error if it isn't registered. */
33
+ expect(id) {
34
+ const node = this.nodes.get(id);
35
+ if (node === undefined) throw new Error(`NodeRegistry: unknown node id ${id}`);
36
+ return node;
37
+ }
38
+
39
+ unregister(id) {
40
+ this.nodes.delete(id);
41
+ }
42
+
43
+ /** Park a freshly created node until an explicit REGISTER_NODE promotes it. */
44
+ stage(id, node) {
45
+ this.pending.set(id, node);
46
+ return node;
47
+ }
48
+
49
+ /**
50
+ * REGISTER_NODE semantics: promote a staged node, keep an existing
51
+ * registration (no-op), or find a pre-existing element in the document via
52
+ * `[primal-id="<id>"]`. Throws if the id is nowhere to be found.
53
+ */
54
+ applyRegister(id, document) {
55
+ if (this.nodes.has(id)) return this.nodes.get(id); // re-register = no-op
56
+ const staged = this.pending.get(id);
57
+ if (staged !== undefined) {
58
+ this.pending.delete(id);
59
+ return this.register(id, staged);
60
+ }
61
+ const found = document.querySelector?.(`[primal-id="${id}"]`);
62
+ if (found) return this.register(id, found);
63
+ throw new Error(`NodeRegistry: REGISTER_NODE ${id} matches no staged node or [primal-id]`);
64
+ }
65
+
66
+ /**
67
+ * Resolve an id that is allowed to still be staged — REPLACE_NODE's `new_id`
68
+ * (its implicit registration) is the one consumer. Promotes staged nodes.
69
+ */
70
+ expectOrStaged(id) {
71
+ const node = this.nodes.get(id);
72
+ if (node !== undefined) return node;
73
+ const staged = this.pending.get(id);
74
+ if (staged !== undefined) {
75
+ this.pending.delete(id);
76
+ return staged;
77
+ }
78
+ throw new Error(`NodeRegistry: unknown node id ${id}`);
79
+ }
80
+
81
+ get size() {
82
+ return this.nodes.size;
83
+ }
84
+ }
85
+
86
+ // ─── MorphDom (feature 07 — decision 027, Datastar-style morphing) ───────────
87
+
88
+ /**
89
+ * WHY: Server/WASM HTML patches (MORPH_NODE, op 16) must update a live subtree
90
+ * WITHOUT destroying user state — focus, form values, CSS animations, element
91
+ * identity. Hard replacement (op 12) loses all of it; morphing reconciles.
92
+ *
93
+ * WHAT: A morphdom/idiomorph-style reconciler: persistent-ID tracking with
94
+ * tag-mismatch and duplicate exclusion, bottom-up ID maps, best-match scanning
95
+ * with pantry retrieval and equality-lookahead anti-churn, a pantry for parked
96
+ * nodes (retrievable within the same morph), form-state preservation, script
97
+ * re-execution with a WeakSet guard, and the `data-ignore-morph` /
98
+ * `data-preserve-attr` escape hatches.
99
+ *
100
+ * HOW: All per-morph state lives on a fresh MorphContext (G31 — re-entrant
101
+ * morphs can't corrupt each other); `cleanup()` runs in `finally` (G33 — the
102
+ * pantry never leaks). Node access is duck-typed (tagName/tag,
103
+ * children/childNodes, getAttribute…) so the algorithm runs identically on
104
+ * the real DOM and the test mock.
105
+ */
106
+
107
+ const morphIsElement = (n) => {
108
+ if (!n) return false;
109
+ if (n.nodeType !== undefined) return n.nodeType === 1; // real DOM
110
+ // Mocks: text nodes carry tag "#text" but still expose attribute methods.
111
+ return typeof n.getAttributeNames === "function" && (n.tag ?? "") !== "#text";
112
+ };
113
+ const morphTag = (n) => (n.tagName ?? n.tag ?? "").toUpperCase();
114
+ const morphKids = (n) => Array.from(n.childNodes ?? n.children ?? []);
115
+ const morphText = (n) => (n.nodeValue !== undefined && n.nodeValue !== null ? n.nodeValue : n.textContent);
116
+ const morphSetText = (n, v) => {
117
+ if (n.nodeValue !== undefined && n.nodeValue !== null) n.nodeValue = v;
118
+ else n.textContent = v;
119
+ };
120
+ const morphAttr = (n, name) => (n.getAttribute ? n.getAttribute(name) : null);
121
+ // Morph identity: `id` wins, else `primal-id` (spec-42 feature 00 §4 — slot
122
+ // spans and template nodes carry primal-id; server re-renders of the same
123
+ // template have STABLE primal-ids, so they anchor preservation exactly like
124
+ // user ids do).
125
+ const morphIdentity = (n) => morphAttr(n, "id") ?? morphAttr(n, "primal-id");
126
+
127
+ /** Walk every element in a subtree (root included), depth-first. */
128
+ function morphWalk(root, fn) {
129
+ if (morphIsElement(root)) fn(root);
130
+ for (const child of morphKids(root)) morphWalk(child, fn);
131
+ }
132
+
133
+ /**
134
+ * `moveBefore` keeps focus/animations/lifecycle when the platform has it
135
+ * (G32 — Chromium 115+, Firefox 125+, Safari TP 185); the fallback is
136
+ * structurally correct but loses that state.
137
+ */
138
+ export function moveBefore(parent, node, ref) {
139
+ if (typeof parent.moveBefore === "function") parent.moveBefore(node, ref);
140
+ else {
141
+ node.parentNode?.removeChild?.(node);
142
+ parent.insertBefore(node, ref);
143
+ }
144
+ }
145
+
146
+ class MorphContext {
147
+ constructor(doc) {
148
+ this.doc = doc;
149
+ this.idMap = new Map(); // Node -> Set<string> (persistent ids in subtree)
150
+ this.persistentIds = new Set();
151
+ this.oldIdTagMap = new Map(); // id -> tagName (old tree)
152
+ this.duplicates = new Set();
153
+ this.pantry = null; // created lazily on first park
154
+ }
155
+
156
+ // Phase 1 — ids that exist in BOTH trees with the SAME tag, no duplicates.
157
+ computePersistentIds(oldRoot, newRoot) {
158
+ morphWalk(oldRoot, (el) => {
159
+ const id = morphIdentity(el);
160
+ if (!id) return;
161
+ if (this.oldIdTagMap.has(id)) this.duplicates.add(id);
162
+ else this.oldIdTagMap.set(id, morphTag(el));
163
+ });
164
+ morphWalk(newRoot, (el) => {
165
+ const id = morphIdentity(el);
166
+ if (!id || this.duplicates.has(id)) return;
167
+ if (this.oldIdTagMap.get(id) === morphTag(el)) this.persistentIds.add(id);
168
+ });
169
+ }
170
+
171
+ // Phase 2 — bottom-up: each node -> the persistent ids inside its subtree.
172
+ populateIdMap(root) {
173
+ const build = (node) => {
174
+ const ids = new Set();
175
+ const own = morphIsElement(node) ? morphIdentity(node) : null;
176
+ if (own && this.persistentIds.has(own)) ids.add(own);
177
+ for (const child of morphKids(node)) {
178
+ for (const id of build(child)) ids.add(id);
179
+ }
180
+ if (ids.size > 0) this.idMap.set(node, ids);
181
+ return ids;
182
+ };
183
+ build(root);
184
+ }
185
+
186
+ hasConflictingId(node) {
187
+ const id = morphIsElement(node) ? morphIdentity(node) : null;
188
+ return !!id && !this.persistentIds.has(id);
189
+ }
190
+
191
+ // §3 — priority 1: ID-set intersection. The scan is UNBOUNDED over the
192
+ // remaining siblings AND the pantry: an id match is an anchor, and anchors
193
+ // are always worth moving for (the spec's own reorder test demands it; its
194
+ // displacement-limit example is the newIds-EMPTY case, which never enters
195
+ // this scan at all). Priority 2: soft match guarded by anti-churn.
196
+ findBestMatch(oldCursor, newChild) {
197
+ if (!morphIsElement(newChild)) {
198
+ // Text/comment: soft-match a same-kind node at the cursor.
199
+ return oldCursor && !morphIsElement(oldCursor) ? oldCursor : null;
200
+ }
201
+ const newIds = this.idMap.get(newChild) ?? new Set();
202
+
203
+ if (newIds.size > 0) {
204
+ const intersects = (candidate) => {
205
+ if (
206
+ !morphIsElement(candidate) ||
207
+ morphTag(candidate) !== morphTag(newChild) ||
208
+ !this.idMap.has(candidate)
209
+ ) {
210
+ return false;
211
+ }
212
+ const ids = this.idMap.get(candidate);
213
+ for (const id of newIds) {
214
+ if (ids.has(id)) return true;
215
+ }
216
+ return false;
217
+ };
218
+ for (let candidate = oldCursor; candidate; candidate = candidate.nextSibling) {
219
+ if (intersects(candidate)) return candidate;
220
+ }
221
+ // Parked earlier in THIS morph — retrievable (§4).
222
+ if (this.pantry) {
223
+ for (const candidate of morphKids(this.pantry)) {
224
+ if (intersects(candidate)) return candidate;
225
+ }
226
+ }
227
+ }
228
+
229
+ if (
230
+ oldCursor &&
231
+ morphIsElement(oldCursor) === morphIsElement(newChild) &&
232
+ morphTag(oldCursor) === morphTag(newChild) &&
233
+ !this.hasConflictingId(oldCursor)
234
+ ) {
235
+ // Anti-churn: the spec's future-sibling counter blocks EVERY element of
236
+ // a homogeneous list (its own narrative contradicts it). The rule that
237
+ // satisfies both spec examples is an equality lookahead: if the NEXT new
238
+ // sibling is structurally equal to the cursor, `newChild` is an
239
+ // INSERTION before it — create fresh instead of morphing the cursor
240
+ // into its successor (prepend churn) or dragging anchors (displacement).
241
+ if (typeof oldCursor.isEqualNode === "function") {
242
+ if (oldCursor.isEqualNode(newChild)) return oldCursor;
243
+ const nextNew = newChild.nextSibling ?? null;
244
+ if (nextNew && oldCursor.isEqualNode(nextNew)) return null;
245
+ }
246
+ return oldCursor;
247
+ }
248
+ return null;
249
+ }
250
+
251
+ // §4 — park id-bearing nodes (retrievable this morph), drop the rest.
252
+ removeNode(node) {
253
+ if (this.idMap.has(node)) {
254
+ if (!this.pantry) this.pantry = this.doc.createElement("div");
255
+ moveBefore(this.pantry, node, null);
256
+ } else {
257
+ node.parentNode?.removeChild?.(node);
258
+ }
259
+ }
260
+
261
+ morphChildren(oldParent, newParent) {
262
+ let oldCursor = oldParent.firstChild ?? null;
263
+ for (const newChild of morphKids(newParent)) {
264
+ // Escape hatch: BOTH sides carry data-ignore-morph -> leave untouched.
265
+ if (
266
+ oldCursor &&
267
+ morphAttr(oldCursor, "data-ignore-morph") !== null &&
268
+ morphAttr(newChild, "data-ignore-morph") !== null
269
+ ) {
270
+ oldCursor = oldCursor.nextSibling;
271
+ continue;
272
+ }
273
+
274
+ const match = this.findBestMatch(oldCursor, newChild);
275
+ if (match) {
276
+ // Park/remove everything between the cursor and the match.
277
+ while (oldCursor && oldCursor !== match) {
278
+ const next = oldCursor.nextSibling;
279
+ this.removeNode(oldCursor);
280
+ oldCursor = next;
281
+ }
282
+ if (match !== oldCursor) moveBefore(oldParent, match, oldCursor);
283
+ this.morphNode(match, newChild);
284
+ oldCursor = match.nextSibling;
285
+ } else {
286
+ const clone = cloneNode(this.doc, newChild);
287
+ oldParent.insertBefore(clone, oldCursor);
288
+ }
289
+ }
290
+ while (oldCursor) {
291
+ const next = oldCursor.nextSibling;
292
+ this.removeNode(oldCursor);
293
+ oldCursor = next;
294
+ }
295
+ }
296
+
297
+ morphNode(oldNode, newNode) {
298
+ if (!morphIsElement(oldNode) || !morphIsElement(newNode)) {
299
+ if (morphText(oldNode) !== morphText(newNode)) {
300
+ morphSetText(oldNode, morphText(newNode));
301
+ }
302
+ return;
303
+ }
304
+ if (typeof oldNode.isEqualNode === "function" && oldNode.isEqualNode(newNode)) {
305
+ return; // identical subtree — skip entirely
306
+ }
307
+ this.syncAttributes(oldNode, newNode);
308
+ preserveFormState(oldNode, newNode);
309
+ const tag = morphTag(oldNode);
310
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return; // leaves
311
+ this.morphChildren(oldNode, newNode);
312
+ }
313
+
314
+ syncAttributes(oldEl, newEl) {
315
+ const preserved = (morphAttr(oldEl, "data-preserve-attr") || "")
316
+ .split(",")
317
+ .map((sliver) => sliver.trim())
318
+ .filter(Boolean);
319
+ for (const name of newEl.getAttributeNames()) {
320
+ if (!preserved.includes(name)) oldEl.setAttribute(name, newEl.getAttribute(name));
321
+ }
322
+ for (const name of oldEl.getAttributeNames()) {
323
+ if (!preserved.includes(name) && newEl.getAttribute(name) === null) {
324
+ oldEl.removeAttribute(name);
325
+ }
326
+ }
327
+ }
328
+
329
+ cleanup() {
330
+ if (this.pantry) {
331
+ while (this.pantry.firstChild) this.pantry.removeChild(this.pantry.firstChild);
332
+ }
333
+ this.idMap.clear();
334
+ this.persistentIds.clear();
335
+ this.oldIdTagMap.clear();
336
+ this.duplicates.clear();
337
+ }
338
+ }
339
+
340
+ /** §5 — keep what the USER did to form controls across the morph. */
341
+ function preserveFormState(oldEl, newEl) {
342
+ if (morphTag(oldEl) !== morphTag(newEl)) return;
343
+ switch (morphTag(oldEl)) {
344
+ case "INPUT": {
345
+ const type = morphAttr(oldEl, "type");
346
+ if (type === "checkbox" || type === "radio") newEl.checked = oldEl.checked;
347
+ else if (type !== "file") newEl.value = oldEl.value;
348
+ break;
349
+ }
350
+ case "TEXTAREA":
351
+ newEl.value = oldEl.value;
352
+ break;
353
+ case "SELECT":
354
+ newEl.selectedIndex = oldEl.selectedIndex;
355
+ break;
356
+ default:
357
+ }
358
+ }
359
+
360
+ /** Deep clone for newly created content (mock-aware). */
361
+ function cloneNode(doc, node) {
362
+ if (typeof node.cloneNode === "function") return node.cloneNode(true);
363
+ if (!morphIsElement(node)) return doc.createTextNode(morphText(node) ?? "");
364
+ const el = doc.createElement(node.tag ?? node.tagName);
365
+ for (const name of node.getAttributeNames()) el.setAttribute(name, node.getAttribute(name));
366
+ if (node.value != null) el.value = node.value;
367
+ if (node.checked != null) el.checked = node.checked;
368
+ for (const child of morphKids(node)) el.appendChild(cloneNode(doc, child));
369
+ return el;
370
+ }
371
+
372
+ export class MorphDom {
373
+ /** Executed scripts — never re-run across morphs (browser concern). */
374
+ static scripts = new WeakSet();
375
+
376
+ /**
377
+ * Morph `target`'s children to mirror `newContent`'s children.
378
+ * @param {Element} target live element
379
+ * @param {Element|DocumentFragment} newContent desired tree (its CHILDREN)
380
+ * @param {Document} [doc] owning document (defaults to target's)
381
+ */
382
+ static morph(
383
+ target,
384
+ newContent,
385
+ doc = target.ownerDocument ?? (typeof document === "undefined" ? null : document),
386
+ ) {
387
+ const ctx = new MorphContext(doc);
388
+ try {
389
+ ctx.computePersistentIds(target, newContent);
390
+ ctx.populateIdMap(target);
391
+ ctx.populateIdMap(newContent);
392
+ ctx.morphChildren(target, newContent);
393
+ MorphDom.executeNewScripts(target, doc);
394
+ } finally {
395
+ ctx.cleanup(); // G33 — pantry never leaks, even on throw
396
+ }
397
+ }
398
+
399
+ /** §7 — re-create injected <script>s so the browser executes them, once. */
400
+ static executeNewScripts(root, doc) {
401
+ if (!doc || typeof root.querySelectorAll !== "function") return; // browser-only
402
+ for (const script of root.querySelectorAll("script")) {
403
+ if (MorphDom.scripts.has(script)) continue;
404
+ const clone = doc.createElement("script");
405
+ for (const name of script.getAttributeNames()) {
406
+ clone.setAttribute(name, script.getAttribute(name));
407
+ }
408
+ clone.textContent = script.textContent;
409
+ script.parentNode?.replaceChild?.(clone, script);
410
+ MorphDom.scripts.add(clone);
411
+ }
412
+ }
413
+ }
414
+
415
+ // ─── EventDispatcher (primal:on* → WASM callbacks) ───────────────────────────────
416
+
417
+ const PRIMAL_ON = "primal:on";
418
+
419
+ /**
420
+ * Build the EventData object handed to a WASM callback (decision 018 / G4):
421
+ * type, the element's primal-id, current value/checked, key code, and modifier keys.
422
+ */
423
+ export function buildEventData(eventType, event, el) {
424
+ return {
425
+ type: eventType,
426
+ primalId: el.getAttribute ? el.getAttribute("primal-id") : null,
427
+ value: el.value ?? null,
428
+ checked: el.checked ?? null,
429
+ keyCode: event.keyCode ?? null,
430
+ modifiers: {
431
+ alt: !!event.altKey,
432
+ ctrl: !!event.ctrlKey,
433
+ shift: !!event.shiftKey,
434
+ meta: !!event.metaKey,
435
+ },
436
+ };
437
+ }
438
+
439
+ /**
440
+ * Parse a `primal:on*` attribute value into a WASM callback id.
441
+ * Accepts `"7"` or `"callback-7"`. Returns `null` for non-callback refs (e.g. a
442
+ * stimulus-style `"controller.delete"`), which a later increment will resolve as a
443
+ * JS function ref.
444
+ */
445
+ export function parseCallbackId(ref) {
446
+ if (ref == null) return null;
447
+ const s = String(ref).trim();
448
+ const body = s.startsWith("callback-") ? s.slice("callback-".length) : s;
449
+ return /^\d+$/.test(body) ? Number(body) : null;
450
+ }
451
+
452
+ /**
453
+ * WHY: DOM events have to reach BOTH worlds: WASM (signal setters via
454
+ * `primal:setter`, registry callbacks via `callback-N`) and plain JS handlers
455
+ * (dot-path refs like `"controller.delete"`). Decision 018: direct binding is
456
+ * the default (works for non-bubbling events); delegation is opt-in per
457
+ * attribute.
458
+ *
459
+ * WHAT: The feature-08 event runtime — scan/wire/unwire with idempotent
460
+ * rewiring (G2), dot-path resolution, opt-in delegation
461
+ * (`primal:onclick:delegate="#container"`), MutationObserver auto-wiring with
462
+ * the island boundary rule, microtask-batched removal cleanup, and the
463
+ * programmatic `on`/`off`/`on<event>` API.
464
+ *
465
+ * HOW: `deliver(callbackId, eventData)` ships registry-callback events;
466
+ * `deliverSignal(setterId, eventData)` ships signal-setter events (two id
467
+ * NAMESPACES — see {@link callbackDeliver} / {@link signalDeliver}).
468
+ * Handler resolution order per element/event:
469
+ * 1. `handlerRef` is `"N"`/`"callback-N"` → registry callback bridge
470
+ * 2. element carries `primal:setter="N"` → signal bridge (two-way binding)
471
+ * 3. `handlerRef` is a dot-path → JS function from `scope`
472
+ * 4. otherwise → console.warn, no listener
473
+ */
474
+ export class EventDispatcher {
475
+ static actionHook = null;
476
+ /**
477
+ * @param {(callbackId:number, eventData:object) => void} deliver
478
+ * @param {{ deliverSignal?:(setterId:number, eventData:object)=>void,
479
+ * scope?:object }} [options]
480
+ */
481
+ constructor(deliver, options = {}) {
482
+ this.deliver = deliver;
483
+ this.deliverSignal = options.deliverSignal ?? deliver;
484
+ this.scope = options.scope ?? globalThis;
485
+ // element -> Map<key, listenerFn>; keys are "click" (direct) or
486
+ // "click:delegate:<primal-id>" (delegated, stored on the TARGET element).
487
+ this.listeners = new WeakMap();
488
+ // trackRemoved microtask batching (feature 08 §9).
489
+ this.cleanupQueue = [];
490
+ this.cleanupScheduled = false;
491
+ this.observer = null;
492
+ }
493
+
494
+ /** Wire every `primal:on*` attribute on `root` and its descendants. */
495
+ scanAndWire(root) {
496
+ visit(root, (el) => {
497
+ for (const name of el.getAttributeNames()) {
498
+ if (!name.startsWith(PRIMAL_ON)) continue;
499
+ const rest = name.slice(PRIMAL_ON.length); // "click" | "click:delegate"
500
+ const [eventType, mode] = rest.split(":");
501
+ if (!eventType) continue;
502
+ if (mode === "delegate") {
503
+ this.wireDelegated(el, eventType, el.getAttribute(name));
504
+ } else if (mode === undefined) {
505
+ this.wire(el, eventType, el.getAttribute(name));
506
+ }
507
+ }
508
+ });
509
+ }
510
+
511
+ /**
512
+ * Wire one direct `eventType` on `el` to `handlerRef` (resolution order in
513
+ * the class docs). Idempotent (G2): the prior listener for that event is
514
+ * removed first, so re-scans never stack duplicates.
515
+ */
516
+ wire(el, eventType, handlerRef) {
517
+ const listener = this.#buildListener(el, eventType, handlerRef);
518
+ if (!listener) {
519
+ console.warn(`EventDispatcher: unresolvable handler "${handlerRef}" for ${eventType}`);
520
+ return;
521
+ }
522
+ this.off(el, eventType);
523
+ el.addEventListener(eventType, listener);
524
+ this.#listenerMap(el).set(eventType, listener);
525
+ }
526
+
527
+ #buildListener(el, eventType, handlerRef) {
528
+ if (/^(server|host):/.test(String(handlerRef))) {
529
+ return event => {
530
+ if (EventDispatcher.actionHook) return EventDispatcher.actionHook(String(handlerRef), el, event, eventType);
531
+ console.warn("No action runtime for", handlerRef);
532
+ };
533
+ }
534
+ const callbackId = parseCallbackId(handlerRef);
535
+ if (callbackId !== null) {
536
+ return (event) => this.deliver(callbackId, buildEventData(eventType, event, el));
537
+ }
538
+ const setterId = parseCallbackId(el.getAttribute?.("primal:setter"));
539
+ if (setterId !== null) {
540
+ return (event) => this.deliverSignal(setterId, buildEventData(eventType, event, el));
541
+ }
542
+ const fn = resolveFunctionRef(this.scope, handlerRef);
543
+ if (fn) return fn.bind(el); // clean `this` = the attributed element
544
+ return null;
545
+ }
546
+
547
+ /**
548
+ * Opt-in delegation (feature 08 §6): attach a listener on the element named
549
+ * by `selector` that stamps `event.delegateTarget = el` whenever the event
550
+ * originated inside `el`. Keys include `el`'s primal-id so many elements can
551
+ * delegate the same event type to one container without colliding.
552
+ */
553
+ wireDelegated(el, eventType, selector) {
554
+ const target = resolveDelegateTarget(el, selector, this.documentOf(el));
555
+ if (!target) {
556
+ console.warn(`EventDispatcher: delegate target "${selector}" not found`);
557
+ return;
558
+ }
559
+ const listener = (event) => {
560
+ if (el === event.target || (el.contains && el.contains(event.target))) {
561
+ event.delegateTarget = el;
562
+ }
563
+ };
564
+ const key = `${eventType}:delegate:${el.getAttribute?.("primal-id") || el.id || ""}`;
565
+ const map = this.#listenerMap(target);
566
+ const prior = map.get(key);
567
+ if (prior) target.removeEventListener(eventType, prior);
568
+ map.set(key, listener);
569
+ target.addEventListener(eventType, listener);
570
+ }
571
+
572
+ /** The document an element belongs to (overridable for tests/mocks). */
573
+ documentOf(el) {
574
+ return el.ownerDocument ?? (typeof document === "undefined" ? null : document);
575
+ }
576
+
577
+ #listenerMap(el) {
578
+ let map = this.listeners.get(el);
579
+ if (!map) {
580
+ map = new Map();
581
+ this.listeners.set(el, map);
582
+ }
583
+ return map;
584
+ }
585
+
586
+ /**
587
+ * Remove listeners on `el`: a specific event type (matching its direct key
588
+ * AND any delegated compound keys), or — with no `eventType` — everything.
589
+ */
590
+ off(el, eventType) {
591
+ const map = this.listeners.get(el);
592
+ if (!map) return;
593
+ if (eventType !== undefined) {
594
+ for (const [key, listener] of map) {
595
+ if (key === eventType || key.startsWith(`${eventType}:`)) {
596
+ el.removeEventListener(eventType, listener);
597
+ map.delete(key);
598
+ }
599
+ }
600
+ return;
601
+ }
602
+ for (const [key, listener] of map) {
603
+ el.removeEventListener(key.split(":")[0], listener);
604
+ }
605
+ map.clear();
606
+ this.listeners.delete(el);
607
+ }
608
+
609
+ /** Remove all listeners on `el` and its descendants (node-removal cleanup). */
610
+ removeListeners(root) {
611
+ visit(root, (el) => this.off(el));
612
+ }
613
+
614
+ /**
615
+ * Queue a removed node for cleanup; one microtask drains the whole batch
616
+ * (feature 08 §9 — removing 50 nodes costs one pass, before paint).
617
+ */
618
+ trackRemoved(node) {
619
+ this.cleanupQueue.push(node);
620
+ if (this.cleanupScheduled) return;
621
+ this.cleanupScheduled = true;
622
+ queueMicrotask(() => {
623
+ const batch = this.cleanupQueue.splice(0);
624
+ this.cleanupScheduled = false;
625
+ for (const item of batch) this.removeListeners(item);
626
+ });
627
+ }
628
+
629
+ /**
630
+ * Process MutationObserver-style records (feature 08 §7): wire added
631
+ * subtrees, clean removed ones — SKIPPING anything inside an `<island>`
632
+ * (the island custom element owns its own lifecycle, F06).
633
+ */
634
+ handleMutations(mutations) {
635
+ for (const mutation of mutations) {
636
+ if (mutation.type !== "childList") continue;
637
+ for (const node of mutation.addedNodes) {
638
+ if (!isElement(node) || insideIsland(node)) continue;
639
+ this.scanAndWire(node);
640
+ // Hydrate scoped styles/scripts on runtime-inserted subtrees (machinery
641
+ // delivery, spec-42 feature 05 §M-delivery). Idempotent: hydrate runs
642
+ // each scoped script once then removes it. Islands self-hydrate via
643
+ // connectedCallback, so they're skipped above.
644
+ Hydrator.hydrate(node);
645
+ }
646
+ for (const node of mutation.removedNodes) {
647
+ if (!isElement(node) || insideIsland(node)) continue;
648
+ this.removeListeners(node);
649
+ }
650
+ }
651
+ }
652
+
653
+ /** Start the document-level observer (browser only; no-op without one). */
654
+ observe(doc) {
655
+ if (typeof MutationObserver === "undefined" || this.observer) return;
656
+ this.observer = new MutationObserver((mutations) => this.handleMutations(mutations));
657
+ this.observer.observe(doc, { subtree: true, childList: true });
658
+ }
659
+
660
+ /**
661
+ * Programmatic wiring (feature 08 §11): `on(el, "click", "ctrl.fn")` or
662
+ * `on(el, "click", null, { delegate: "#box" })`.
663
+ */
664
+ on(el, eventType, handlerRef, options = {}) {
665
+ if (options.delegate) this.wireDelegated(el, eventType, options.delegate);
666
+ else this.wire(el, eventType, handlerRef);
667
+ }
668
+ }
669
+
670
+ /** Events that get `dispatcher.on<event>(el, ref, opts)` convenience methods. */
671
+ export const CONVENIENCE_EVENTS = [
672
+ "click", "change", "submit", "keydown", "keyup",
673
+ "focus", "blur", "scroll", "input", "mousedown", "mouseup",
674
+ ];
675
+ for (const evt of CONVENIENCE_EVENTS) {
676
+ EventDispatcher.prototype[`on${evt}`] = function (el, handlerRef, options) {
677
+ this.on(el, evt, handlerRef, options);
678
+ };
679
+ }
680
+
681
+ /** Depth-first walk over attribute-bearing nodes (root first). */
682
+ function visit(node, fn) {
683
+ if (typeof node.getAttributeNames === "function") fn(node);
684
+ for (const child of node.children || []) visit(child, fn);
685
+ }
686
+
687
+ function isElement(node) {
688
+ return !!node && typeof node.getAttributeNames === "function";
689
+ }
690
+
691
+ /** The island boundary rule: nearest `<island>` ancestor-or-self opts out. */
692
+ function insideIsland(node) {
693
+ if (typeof node.closest === "function") return node.closest("island") !== null;
694
+ // Mock fallback: walk parents by tag.
695
+ for (let cur = node; cur; cur = cur.parent ?? cur.parentElement ?? null) {
696
+ if ((cur.tag ?? cur.tagName ?? "").toLowerCase() === "island") return true;
697
+ }
698
+ return false;
699
+ }
700
+
701
+ /**
702
+ * Dot-path resolution against `scope` (feature 08 §4): `"controller.delete"`
703
+ * walks `scope.controller.delete`; missing segments or non-functions → null.
704
+ */
705
+ export function resolveFunctionRef(scope, handlerRef) {
706
+ if (typeof handlerRef !== "string" || handlerRef.length === 0) return null;
707
+ let current = scope;
708
+ for (const part of handlerRef.split(".")) {
709
+ if (current == null) return null;
710
+ current = current[part];
711
+ }
712
+ return typeof current === "function" ? current : null;
713
+ }
714
+
715
+ /** Delegate target resolution (feature 08 §5). */
716
+ export function resolveDelegateTarget(el, selector, doc) {
717
+ if (!selector) return null;
718
+ if (selector === "parent") return el.parentElement ?? el.parent ?? null;
719
+ if (selector === "body") return doc?.body ?? null;
720
+ return doc?.querySelector ? doc.querySelector(selector) : null;
721
+ }
722
+
723
+ /**
724
+ * Run the initial scan + observer once the document is ready (feature 08 §10).
725
+ * Both paths are idempotent — rewiring replaces listeners (G2).
726
+ */
727
+ export function initEventRuntime(dispatcher, doc = typeof document === "undefined" ? null : document) {
728
+ if (!doc) return;
729
+ const boot = () => {
730
+ dispatcher.scanAndWire(doc.body);
731
+ dispatcher.observe(doc);
732
+ };
733
+ doc.addEventListener?.("DOMContentLoaded", boot);
734
+ if (doc.readyState !== "loading") boot();
735
+ }
736
+
737
+ /**
738
+ * Default `deliver` for REGISTRY callbacks (`callback-N` refs): serialise
739
+ * EventData and ship via a `CallbackRegistry` (foundation-wasm.js), which
740
+ * writes an arena slot and calls the `invoke_callback` export.
741
+ *
742
+ * @param {{invoke:(id:number, bytes:Uint8Array)=>void}} callbackRegistry
743
+ * @param {(eventData:object)=>Uint8Array} [encode]
744
+ */
745
+ export function callbackDeliver(callbackRegistry, encode = jsonEncodeEventData) {
746
+ return (callbackId, eventData) => callbackRegistry.invoke(callbackId, encode(eventData));
747
+ }
748
+
749
+ /**
750
+ * `deliverSignal` for SIGNAL setters (`primal:setter` ids — the
751
+ * foundation_signals registry, a separate namespace): write the JSON
752
+ * EventData into a fresh global-arena slot and call the dedicated
753
+ * `invoke_signal_callback(setterId, memoryId)` export. Rust reads, dispatches
754
+ * to the setter, runs `stabilize()`, and frees the slot — no JS-side dispose.
755
+ *
756
+ * @param {{exports:object, memory:()=>WebAssembly.Memory}} bridge
757
+ * @param {(eventData:object)=>Uint8Array} [encode]
758
+ */
759
+ export function signalDeliver(bridge, encode = jsonEncodeEventData) {
760
+ return (setterId, eventData) => {
761
+ const bytes = encode(eventData);
762
+ const memId = bridge.exports.create_allocation(BigInt(bytes.length));
763
+ const ptr = Number(bridge.exports.allocation_start_pointer(memId));
764
+ const memory = typeof bridge.memory === "function" ? bridge.memory() : bridge.memory;
765
+ new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
766
+ bridge.exports.invoke_signal_callback(BigInt(setterId), memId);
767
+ };
768
+ }
769
+
770
+ function jsonEncodeEventData(eventData) {
771
+ return new TextEncoder().encode(JSON.stringify(eventData));
772
+ }
773
+
774
+ // ─── DomHeap (DOM external-pointer arena, = megatron DOMArena) ────────────────────
775
+
776
+ /**
777
+ * Generation-arena heap for DOM nodes referenced across the ABI by `ExternalPointer`
778
+ * ids (uid = `(index << 32) | generation`, bigint — same scheme as the core runtime's
779
+ * ExternalHeap; implemented here so this file stays import-free for the browser).
780
+ *
781
+ * Slots 0–4 are RESERVED at construction (megatron DOMArena parity):
782
+ * 0 = self (or this heap when no `self`), 1 = the heap itself, 2 = window,
783
+ * 3 = document, 4 = document.body. Reserved slots refuse `destroy`.
784
+ */
785
+ export class DomHeap {
786
+ static RESERVED_SLOTS = 5;
787
+
788
+ /** @param {{window?:object, document?:object}} [host] overrides for tests/SSR */
789
+ constructor(host = globalThis) {
790
+ this.items = []; // { item, generation, active }
791
+ this.free = [];
792
+ const doc = host.document ?? null;
793
+ this.create(typeof self !== "undefined" ? self : this);
794
+ this.create(this);
795
+ this.create(host.window ?? null);
796
+ this.create(doc);
797
+ this.create(doc && doc.body ? doc.body : null);
798
+ }
799
+
800
+ #unpack(uid) {
801
+ const v = BigInt(uid);
802
+ // The well-known DOM handles (Rust DOM_SELF..DOM_BODY) are the RAW values 0–4,
803
+ // not packed uids. Reserved slots are never destroyed, so their generation stays
804
+ // 0 and small raw values stay unambiguous (a packed index-n uid is n<<32).
805
+ if (v < BigInt(DomHeap.RESERVED_SLOTS)) return { index: Number(v), generation: 0n };
806
+ return { index: Number(v >> 32n), generation: v & 0xffffffffn };
807
+ }
808
+
809
+ /** Allocate a slot for `item` (may be null) → packed uid (bigint). */
810
+ create(item) {
811
+ let index;
812
+ if (this.free.length > 0) {
813
+ index = this.free.pop();
814
+ const slot = this.items[index];
815
+ slot.generation += 1n;
816
+ slot.active = true;
817
+ slot.item = item;
818
+ } else {
819
+ index = this.items.length;
820
+ this.items.push({ item, generation: 0n, active: true });
821
+ }
822
+ return (BigInt(index) << 32n) | this.items[index].generation;
823
+ }
824
+
825
+ /** Resolve a uid → node (undefined when stale/missing). */
826
+ get(uid) {
827
+ const { index, generation } = this.#unpack(uid);
828
+ const slot = this.items[index];
829
+ if (!slot || !slot.active || slot.generation !== generation) return undefined;
830
+ return slot.item;
831
+ }
832
+
833
+ /** Fill a pre-allocated uid. False when stale. */
834
+ update(uid, item) {
835
+ const { index, generation } = this.#unpack(uid);
836
+ const slot = this.items[index];
837
+ if (!slot || slot.generation !== generation) return false;
838
+ slot.item = item;
839
+ slot.active = true;
840
+ return true;
841
+ }
842
+
843
+ /** Retire a uid (reserved slots 0–4 refuse, megatron parity). */
844
+ destroy(uid) {
845
+ const { index, generation } = this.#unpack(uid);
846
+ if (index < DomHeap.RESERVED_SLOTS) return false;
847
+ const slot = this.items[index];
848
+ if (!slot || !slot.active || slot.generation !== generation) return false;
849
+ slot.item = null;
850
+ slot.active = false;
851
+ this.free.push(index);
852
+ return true;
853
+ }
854
+ }
855
+
856
+ // ─── DOM ABI extension ─────────────────────────────────────────────────────────────
857
+
858
+ /**
859
+ * Wire the DOM layer onto a core `FoundationWasm` runtime: creates the DomHeap,
860
+ * registers it as the ReplyEncoder's DOM heap (DOMObject returns intern here), and
861
+ * returns the DOM-specific import fragment to spread into the import object:
862
+ *
863
+ * const rt = new FoundationWasm();
864
+ * const dom = new DomHeap();
865
+ * const abi = { ...rt.web_abi, ...domAbi(rt, dom) };
866
+ * const instance = new WebAssembly.Instance(module, { abi });
867
+ *
868
+ * @param {{functions:{reply:{dom:object}}}} rt the core runtime
869
+ * @param {DomHeap} dom
870
+ * @returns {object} import fragment (`dom_allocate_external_pointer`, …)
871
+ */
872
+ export function domAbi(rt, dom) {
873
+ rt.functions.reply.dom = dom;
874
+ return {
875
+ // Pre-allocate an external-pointer slot earmarked for a DOM node
876
+ // (foundation_wasm_ui's allocate_dom_reference).
877
+ dom_allocate_external_pointer: () => dom.create(null),
878
+ // Retire a DOM handle (reserved slots 0–4 refuse; stale ids no-op).
879
+ host_dom_drop_external_pointer: (handle) => {
880
+ dom.destroy(BigInt(handle));
881
+ },
882
+ // DOM fast-path: the returned node interns into the DOM heap; its handle
883
+ // crosses naked (29 = ReturnTypeId.DOMObject, the shared contract value).
884
+ host_invoke_function_as_dom: (h, p, l) => {
885
+ const v = rt.functions.invokeNakedAs(h, p, l, 29);
886
+ return typeof v === "bigint" ? v : BigInt(v);
887
+ },
888
+ };
889
+ }
890
+
891
+ // ─── Global registration ──────────────────────────────────────────────────────────
892
+ //
893
+ // The ESM exports above are canonical (`<script type="module">` / import). This
894
+ // ─── Web Components (feature 06 — decisions 021/022/023/024) ─────────────────
895
+ //
896
+ // Three thin custom elements over four shared layers: Transport (how bytes
897
+ // move), ProtocolHandler (what the bytes are, by content type), Patcher (how
898
+ // parsed results land in the DOM), Hydrator (post-insertion styles/scripts —
899
+ // events stay with the F08 EventDispatcher). Browser-only APIs (EventSource,
900
+ // WebSocket, customElements, CSSStyleSheet) are guarded so the logic runs and
901
+ // tests under node.
902
+
903
+ /** Exponential reconnect backoff: 1s/2s/4s… capped at 30s (spec §12). */
904
+ export function reconnectDelay(attempt) {
905
+ return Math.min(1000 * 2 ** attempt, 30_000);
906
+ }
907
+
908
+ /** Probe `HEAD /primal/messages` (feature 11 §2): 200 = server batches. */
909
+ export async function probeBatching(fetchFn = globalThis.fetch) {
910
+ try {
911
+ const res = await fetchFn("/primal/messages", { method: "HEAD" });
912
+ return !!res && res.ok === true;
913
+ } catch {
914
+ return false;
915
+ }
916
+ }
917
+
918
+ /**
919
+ * HTTP request bundling (feature 11 / decision 026): when the server supports
920
+ * `/primal/messages`, queued requests flush as ONE id'd batch per microtask
921
+ * tick (`[{id, url, method, headers, body}]`); a lone request skips the
922
+ * wrapper and goes out as itself.
923
+ */
924
+ export class RequestQueue {
925
+ constructor(transport) {
926
+ this.queue = [];
927
+ this.scheduled = false;
928
+ this.transport = transport;
929
+ this.bundlingEnabled = false; // set after the probe
930
+ this.nextId = 1;
931
+ }
932
+
933
+ /** Probe once; enable bundling on 200 OK. */
934
+ async probe(fetchFn = globalThis.fetch) {
935
+ this.bundlingEnabled = await probeBatching(fetchFn);
936
+ return this.bundlingEnabled;
937
+ }
938
+
939
+ enqueue(request) {
940
+ if (!this.bundlingEnabled) {
941
+ return this.transport.send(request.url, request.method, request.data);
942
+ }
943
+ this.queue.push({
944
+ id: this.nextId++,
945
+ url: request.url,
946
+ method: request.method ?? "GET",
947
+ headers: request.headers,
948
+ body: request.data,
949
+ });
950
+ if (!this.scheduled) {
951
+ this.scheduled = true;
952
+ queueMicrotask(() => this.flush());
953
+ }
954
+ return null;
955
+ }
956
+
957
+ flush() {
958
+ this.scheduled = false;
959
+ if (this.queue.length === 0) return; // no network call (test 7)
960
+ const batch = this.queue.splice(0);
961
+ if (batch.length === 1) {
962
+ // Single request: as-is, no batch wrapper (test 5).
963
+ const only = batch[0];
964
+ this.transport.send(only.url, only.method, only.body);
965
+ return;
966
+ }
967
+ this.transport.send("/primal/messages", "POST", batch);
968
+ }
969
+ }
970
+
971
+ /**
972
+ * Parse one batched-response entry (`{id, status, headers, body}`) per its
973
+ * declared content type and produce the same result objects the protocol
974
+ * handlers emit — so `Patcher.route` works on batch members too (§5).
975
+ */
976
+ export function parseBatchEntry(entry) {
977
+ const ct = entry.headers?.["content-type"] ?? entry.headers?.["Content-Type"] ?? "";
978
+ if (ct.includes("primal-json")) return { id: entry.id, ...routeJson(entry.body) };
979
+ if (ct.includes("primal-html") || ct.includes("text/html")) {
980
+ return { id: entry.id, ...routeHtml(String(entry.body)) };
981
+ }
982
+ if (ct.includes("primal-arrow")) {
983
+ return {id:entry.id, ...removedArrow()};
984
+ }
985
+ return { id: entry.id, type: "raw", text: String(entry.body ?? "") };
986
+ }
987
+
988
+ /**
989
+ * WebSocket frame coalescing (feature 11 §6): one frame per microtask; a
990
+ * single message ships unwrapped, several wrap as `{ batch: [...] }`.
991
+ */
992
+ export class WSBatchQueue {
993
+ constructor(ws) {
994
+ this.ws = ws;
995
+ this.queue = [];
996
+ this.scheduled = false;
997
+ }
998
+
999
+ send(data) {
1000
+ this.queue.push(data);
1001
+ if (!this.scheduled) {
1002
+ this.scheduled = true;
1003
+ queueMicrotask(() => this.flush());
1004
+ }
1005
+ }
1006
+
1007
+ flush() {
1008
+ this.scheduled = false;
1009
+ if (this.queue.length === 1) {
1010
+ this.ws.send(JSON.stringify(this.queue.splice(0, 1)[0]));
1011
+ } else if (this.queue.length > 1) {
1012
+ this.ws.send(JSON.stringify({ batch: this.queue.splice(0) }));
1013
+ }
1014
+ }
1015
+ }
1016
+
1017
+ /**
1018
+ * Worker postMessage coalescing (feature 11 §7): one structured-clone
1019
+ * transfer per microtask, transferables forwarded rather than copied.
1020
+ */
1021
+ export class WorkerBatchQueue {
1022
+ constructor(worker) {
1023
+ this.worker = worker;
1024
+ this.queue = [];
1025
+ this.scheduled = false;
1026
+ }
1027
+
1028
+ postMessage(data) {
1029
+ this.queue.push(data);
1030
+ if (!this.scheduled) {
1031
+ this.scheduled = true;
1032
+ queueMicrotask(() => this.flush());
1033
+ }
1034
+ }
1035
+
1036
+ flush() {
1037
+ this.scheduled = false;
1038
+ if (this.queue.length === 0) return;
1039
+ const batch = this.queue.splice(0);
1040
+ const transfers = batch.map((d) => d?.transferable).filter(Boolean);
1041
+ this.worker.postMessage({ batch }, transfers);
1042
+ }
1043
+ }
1044
+
1045
+ // ─── Transport layer (G28: send for request-response, connect for streams) ────
1046
+
1047
+ export class FetchTransport {
1048
+ constructor(config = {}) {
1049
+ this.config = config;
1050
+ this.fetchFn = config.fetchFn ?? ((...args) => globalThis.fetch(...args));
1051
+ }
1052
+
1053
+ async send(url, method = "POST", data = undefined) {
1054
+ const init = { method, headers: this.config.headers };
1055
+ if (data !== undefined && method !== "GET" && method !== "HEAD") {
1056
+ init.body = typeof data === "string" ? data : JSON.stringify(data);
1057
+ }
1058
+ const response = await this.fetchFn(url, init);
1059
+ if (!response.ok) throw new Error(`FetchTransport: ${method} ${url} -> ${response.status}`);
1060
+ const handler =
1061
+ ProtocolHandler.named(this.config.protocol) ?? ProtocolHandler.fromContentType(response);
1062
+ return handler.process(response);
1063
+ }
1064
+
1065
+ disconnect() {}
1066
+ }
1067
+
1068
+ // ─── Owned SSE: parser + fetch-based EventSource (feature 21) ─────────────────
1069
+ //
1070
+ // The browser EventSource API is GET-only — no bodies, no custom verbs, no
1071
+ // headers. Datastar's answer (and ours): fetch() the stream with ANY method
1072
+ // and parse the SSE protocol from the response ReadableStream. The parser
1073
+ // MIRRORS foundation_netio's Rust SseParser semantics exactly (id rejects
1074
+ // NUL, one leading value space stripped, multi-line data joined with \n,
1075
+ // comments surfaced, empty line dispatches only with data, EOF flushes,
1076
+ // no-colon lines ignored), plus the byte-stream concerns the Rust reader
1077
+ // doesn't face here: UTF-8 sequences and CRLF pairs split across chunks, and
1078
+ // partial trailing lines buffered until their terminator arrives.
1079
+
1080
+ export class SseParser {
1081
+ constructor() {
1082
+ this.decoder = new TextDecoder("utf-8"); // {stream:true} handles split runes
1083
+ this.textBuffer = "";
1084
+ this.sawCarriageReturn = false; // CRLF split across chunks
1085
+ this.lastEventId = null;
1086
+ this.#resetBuilder();
1087
+ }
1088
+
1089
+ #resetBuilder() {
1090
+ this.id = null;
1091
+ this.eventType = null;
1092
+ this.data = [];
1093
+ this.retry = null;
1094
+ }
1095
+
1096
+ /** Feed one byte chunk; returns the COMPLETE events it finished. */
1097
+ push(chunk) {
1098
+ let text = this.decoder.decode(chunk, { stream: true });
1099
+ // A \r at a previous chunk's end: swallow a leading \n (split CRLF).
1100
+ if (this.sawCarriageReturn) {
1101
+ this.sawCarriageReturn = false;
1102
+ if (text.startsWith("\n")) text = text.slice(1);
1103
+ }
1104
+ if (text.endsWith("\r")) {
1105
+ this.sawCarriageReturn = true;
1106
+ }
1107
+ this.textBuffer += text;
1108
+
1109
+ const events = [];
1110
+ for (;;) {
1111
+ const cut = this.#nextLineEnd();
1112
+ if (cut === null) break;
1113
+ const [line, rest] = cut;
1114
+ this.textBuffer = rest;
1115
+ const event = this.#processLine(line);
1116
+ if (event) events.push(event);
1117
+ }
1118
+ return events;
1119
+ }
1120
+
1121
+ /** EOF: flush any accumulated data as a final event (Rust parity). */
1122
+ end() {
1123
+ const tail = this.decoder.decode(); // flush a dangling partial rune
1124
+ if (tail) this.textBuffer += tail;
1125
+ const events = [];
1126
+ if (this.textBuffer.length > 0) {
1127
+ const event = this.#processLine(this.textBuffer.replace(/\r$/, ""));
1128
+ this.textBuffer = "";
1129
+ if (event) events.push(event);
1130
+ }
1131
+ const flushed = this.#dispatch();
1132
+ if (flushed) events.push(flushed);
1133
+ return events;
1134
+ }
1135
+
1136
+ /** Find the next complete line, honoring \r\n, \n, and lone \r. */
1137
+ #nextLineEnd() {
1138
+ const buf = this.textBuffer;
1139
+ for (let i = 0; i < buf.length; i++) {
1140
+ const ch = buf[i];
1141
+ if (ch === "\n") return [buf.slice(0, i), buf.slice(i + 1)];
1142
+ if (ch === "\r") {
1143
+ if (i + 1 < buf.length) {
1144
+ const skip = buf[i + 1] === "\n" ? 2 : 1;
1145
+ return [buf.slice(0, i), buf.slice(i + skip)];
1146
+ }
1147
+ return null; // lone \r at buffer end — wait for the next chunk
1148
+ }
1149
+ }
1150
+ return null;
1151
+ }
1152
+
1153
+ #processLine(line) {
1154
+ if (line.length === 0) {
1155
+ return this.#dispatch(); // empty line — dispatch IF data accumulated
1156
+ }
1157
+ if (line.startsWith(":")) {
1158
+ // Comments surface immediately (Rust parity).
1159
+ return { type: "comment", comment: line.slice(1).replace(/^ /, "").trimStart(), lastEventId: this.lastEventId };
1160
+ }
1161
+ const colon = line.indexOf(":");
1162
+ if (colon === -1) return null; // no-colon lines ignored (Rust parity)
1163
+ const field = line.slice(0, colon);
1164
+ let value = line.slice(colon + 1);
1165
+ if (value.startsWith(" ")) value = value.slice(1); // exactly ONE space
1166
+
1167
+ switch (field) {
1168
+ case "id":
1169
+ if (!value.includes("\0")) this.id = value;
1170
+ break;
1171
+ case "event":
1172
+ this.eventType = value;
1173
+ break;
1174
+ case "data":
1175
+ this.data.push(value);
1176
+ break;
1177
+ case "retry": {
1178
+ const ms = Number(value);
1179
+ if (Number.isInteger(ms) && ms >= 0 && /^\d+$/.test(value)) this.retry = ms;
1180
+ break;
1181
+ }
1182
+ default: // unknown fields ignored
1183
+ }
1184
+ return null;
1185
+ }
1186
+
1187
+ #dispatch() {
1188
+ if (this.data.length === 0) {
1189
+ this.#resetBuilder(); // reset even without an event (Rust parity)
1190
+ return null;
1191
+ }
1192
+ if (this.id !== null) this.lastEventId = this.id;
1193
+ const event = {
1194
+ type: "message",
1195
+ event: this.eventType,
1196
+ data: this.data.join("\n"),
1197
+ id: this.id,
1198
+ lastEventId: this.lastEventId,
1199
+ retry: this.retry,
1200
+ };
1201
+ this.#resetBuilder();
1202
+ return event;
1203
+ }
1204
+ }
1205
+
1206
+ /**
1207
+ * EventSource over fetch (feature 21): ANY method, headers, body; streams the
1208
+ * response through {@link SseParser}; reconnects (F06 backoff, server
1209
+ * `retry:` override, `Last-Event-ID` carried) until {@link FetchEventSource#close}.
1210
+ */
1211
+ export class FetchEventSource {
1212
+ /**
1213
+ * @param {string} url
1214
+ * @param {{ method?:string, headers?:object, body?:any, fetchFn?:Function,
1215
+ * onOpen?:Function, onEvent?:Function, onComment?:Function,
1216
+ * onError?:Function }} [options]
1217
+ */
1218
+ constructor(url, options = {}) {
1219
+ this.url = url;
1220
+ this.options = options;
1221
+ this.fetchFn = options.fetchFn ?? ((...args) => globalThis.fetch(...args));
1222
+ this.closed = false;
1223
+ this.attempt = 0;
1224
+ this.retryOverride = null; // server `retry:` field
1225
+ this.lastEventId = null;
1226
+ this.abort = null;
1227
+ }
1228
+
1229
+ /** Open the stream (returns when the FIRST connection attempt settles). */
1230
+ async connect() {
1231
+ this.closed = false;
1232
+ await this.#attemptOnce();
1233
+ }
1234
+
1235
+ async #attemptOnce() {
1236
+ if (this.closed) return;
1237
+ this.abort = typeof AbortController === "undefined" ? null : new AbortController();
1238
+ const headers = {
1239
+ accept: "text/event-stream",
1240
+ ...(this.options.headers ?? {}),
1241
+ };
1242
+ if (this.lastEventId !== null) headers["last-event-id"] = this.lastEventId;
1243
+
1244
+ let response;
1245
+ try {
1246
+ response = await this.fetchFn(this.options.nextUrl?.(this.url) ?? this.url, {
1247
+ method: this.options.method ?? "GET",
1248
+ // Each open stream needs its own response, even when two URLs match.
1249
+ cache: "no-store",
1250
+ headers,
1251
+ body: this.options.body,
1252
+ signal: this.abort?.signal,
1253
+ });
1254
+ if (response.status === 410 && this.options.onExpired) {
1255
+ this.close();
1256
+ this.options.onExpired();
1257
+ return;
1258
+ }
1259
+ if (!response.ok) throw new Error(`FetchEventSource: ${response.status}`);
1260
+ } catch (error) {
1261
+ this.options.onError?.(error);
1262
+ this.#scheduleReconnect();
1263
+ return;
1264
+ }
1265
+
1266
+ this.options.onOpen?.(response);
1267
+ this.attempt = 0; // a successful open resets the backoff
1268
+ const parser = new SseParser();
1269
+ const reader = response.body.getReader();
1270
+ try {
1271
+ for (;;) {
1272
+ const { done, value } = await reader.read();
1273
+ if (done) break;
1274
+ for (const event of parser.push(value)) this.#deliver(event);
1275
+ }
1276
+ for (const event of parser.end()) this.#deliver(event);
1277
+ } catch (error) {
1278
+ if (!this.closed) this.options.onError?.(error);
1279
+ }
1280
+ this.lastEventId = parser.lastEventId ?? this.lastEventId;
1281
+ // Stream ended — SSE semantics: reconnect unless closed.
1282
+ this.#scheduleReconnect();
1283
+ }
1284
+
1285
+ #deliver(event) {
1286
+ if (event.type === "comment") {
1287
+ this.options.onComment?.(event);
1288
+ return;
1289
+ }
1290
+ if (event.retry !== null && event.retry !== undefined) {
1291
+ this.retryOverride = event.retry;
1292
+ }
1293
+ if (event.id !== null) this.lastEventId = event.id;
1294
+ this.options.onEvent?.(event);
1295
+ }
1296
+
1297
+ #scheduleReconnect() {
1298
+ if (this.closed) return;
1299
+ const delay = this.retryOverride ?? reconnectDelay(this.attempt);
1300
+ this.attempt += 1;
1301
+ this.reconnectTimer = setTimeout(() => {
1302
+ if (!this.closed) this.#attemptOnce();
1303
+ }, delay);
1304
+ }
1305
+
1306
+ /** Stop: abort the in-flight fetch and cancel reconnection. */
1307
+ close() {
1308
+ this.closed = true;
1309
+ clearTimeout(this.reconnectTimer);
1310
+ this.abort?.abort?.();
1311
+ }
1312
+ }
1313
+
1314
+ export class SSETransport {
1315
+ constructor(config = {}) {
1316
+ this.config = config;
1317
+ this.source = null;
1318
+ }
1319
+
1320
+ /**
1321
+ * Open an SSE stream with ANY method (feature 21 — the browser EventSource
1322
+ * is GET-only; this rides {@link FetchEventSource}). `config.method`
1323
+ * defaults to POST when `data` is given, GET otherwise.
1324
+ */
1325
+ connect(url, data, onResult) {
1326
+ const method = this.config.method ?? (data === undefined ? "GET" : "POST");
1327
+ this.source = new FetchEventSource(url, {
1328
+ method,
1329
+ headers: {
1330
+ ...(data === undefined ? {} : { "content-type": "application/json" }),
1331
+ ...(this.config.headers ?? {}),
1332
+ },
1333
+ body: data === undefined ? undefined : JSON.stringify(data),
1334
+ fetchFn: this.config.fetchFn,
1335
+ // G46: the `event:` field names the payload kind; unnamed = html.
1336
+ // The mount `protocol` attribute overrides per feature-04 precedence.
1337
+ onEvent: (event) => {
1338
+ if (this.config.listening?.() !== false) onResult(streamEventResult(this.config.protocol ?? event.event ?? "html", event.data));
1339
+ },
1340
+ onOpen: this.config.onOpen,
1341
+ onError: this.config.onError,
1342
+ nextUrl: this.config.nextUrl,
1343
+ onExpired: this.config.onExpired,
1344
+ });
1345
+ return this.source.connect();
1346
+ }
1347
+
1348
+ disconnect() {
1349
+ this.source?.close?.();
1350
+ this.source = null;
1351
+ }
1352
+ }
1353
+
1354
+ export class WebSocketTransport {
1355
+ constructor(config = {}) {
1356
+ this.config = config;
1357
+ this.ws = null;
1358
+ this.attempt = 0;
1359
+ this.closed = false;
1360
+ }
1361
+
1362
+ connect(url, _data, onResult) {
1363
+ const factory =
1364
+ this.config.wsFactory ??
1365
+ (typeof WebSocket === "undefined" ? null : (target) => new WebSocket(target));
1366
+ if (!factory) {
1367
+ throw new Error("WebSocketTransport: WebSocket unavailable in this environment");
1368
+ }
1369
+ this.closed = false;
1370
+ this.url = url;
1371
+ this.onResult = onResult;
1372
+ const socket = factory(this.config.nextUrl?.(url) ?? url);
1373
+ this.ws = socket;
1374
+ // Binary frames carry the ENVELOPE — its header tells the protocol
1375
+ // (feature 04); text frames fall back to the declared protocol, else
1376
+ // json (the pre-feature-04 behavior, preserved as the text default).
1377
+ if ("binaryType" in this.ws) this.ws.binaryType = "arraybuffer";
1378
+ this.ws.onopen = () => {
1379
+ if (this.ws !== socket || this.closed) return;
1380
+ this.attempt = 0;
1381
+ this.config.onOpen?.();
1382
+ };
1383
+ this.ws.onmessage = (event) => {
1384
+ if (this.ws !== socket || this.closed || this.config.listening?.() === false) return;
1385
+ const { data } = event;
1386
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
1387
+ const result = decodeEnvelopeFrame(
1388
+ data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
1389
+ );
1390
+ if (result) onResult(result);
1391
+ return; // malformed frames already surfaced a typed error
1392
+ }
1393
+ onResult(streamEventResult(this.config.protocol ?? "json", data));
1394
+ };
1395
+ this.ws.onclose = () => {
1396
+ if (this.closed || this.ws !== socket) return;
1397
+ this.config.onError?.(new Error("WebSocket disconnected"));
1398
+ const delay = reconnectDelay(this.attempt);
1399
+ this.attempt += 1;
1400
+ setTimeout(() => {
1401
+ if (!this.closed && this.ws === socket) this.connect(this.url, undefined, this.onResult);
1402
+ }, delay);
1403
+ };
1404
+ }
1405
+
1406
+ send(data) {
1407
+ if (!this.ws || (this.ws.readyState !== undefined && this.ws.readyState !== 1)) throw new Error("WebSocket is closed");
1408
+ this.ws.send(typeof data === "string" || ArrayBuffer.isView(data) || data instanceof ArrayBuffer ? data : JSON.stringify(data));
1409
+ }
1410
+
1411
+ disconnect() {
1412
+ this.closed = true;
1413
+ this.ws?.close?.();
1414
+ this.ws = null;
1415
+ }
1416
+ }
1417
+
1418
+ export class ChunkedTransport {
1419
+ constructor(config = {}) {
1420
+ this.config = config;
1421
+ this.abort = null;
1422
+ this.fetchFn = config.fetchFn ?? ((...args) => globalThis.fetch(...args));
1423
+ }
1424
+
1425
+ async connect(url, data, onChunk) {
1426
+ this.abort = new AbortController();
1427
+ const response = await this.fetchFn(url, {
1428
+ method: data === undefined ? "GET" : "POST",
1429
+ body: data === undefined ? undefined : JSON.stringify(data),
1430
+ signal: this.abort.signal,
1431
+ headers: this.config.headers,
1432
+ });
1433
+ if (response.status === 410 && this.config.onExpired) { this.config.onExpired(); return; }
1434
+ if (!response.ok) throw new Error("Stream request failed with HTTP " + response.status);
1435
+ this.config.onOpen?.();
1436
+ const handler = ProtocolHandler.named(this.config.protocol) ?? ProtocolHandler.fromContentType(response);
1437
+ if (handler instanceof FrameHandler && isViewResponse(response)) {
1438
+ onChunk(await handler.process(response));
1439
+ } else if (handler instanceof FrameHandler) {
1440
+ const hook = ProtocolHandler.frameHook;
1441
+ if (!hook) throw new Error("Install the frame runtime before opening a frame stream");
1442
+ for await (const frame of hook.readFrames(response.body,hook.maxFrameBytes)) {
1443
+ if (this.config.listening?.() !== false) onChunk({type:"frame",frames:[frame]});
1444
+ }
1445
+ } else {
1446
+ // A single document can span several network chunks.
1447
+ const limit = this.config.maxDocumentBytes ?? ProtocolHandler.frameHook?.maxFrameBytes ?? 4 * 1024 * 1024;
1448
+ let size = 0;
1449
+ const body = response.body.pipeThrough(new TransformStream({transform(bytes, controller) {
1450
+ size += bytes.byteLength;
1451
+ if (size > limit) throw new RangeError("Streamed document exceeds byte limit");
1452
+ controller.enqueue(bytes);
1453
+ }}));
1454
+ onChunk(await handler.process(new Response(body,{headers:response.headers})));
1455
+ }
1456
+ }
1457
+
1458
+ disconnect() {
1459
+ this.abort?.abort?.();
1460
+ this.abort = null;
1461
+ }
1462
+ }
1463
+
1464
+ export class WorkerTransport {
1465
+ constructor(config = {}) {
1466
+ this.worker = config.worker;
1467
+ }
1468
+
1469
+ send(_url, _method, data) {
1470
+ this.worker.postMessage(data);
1471
+ }
1472
+
1473
+ onMessage(callback) {
1474
+ this.worker.onmessage = (event) => callback(event.data);
1475
+ }
1476
+
1477
+ disconnect() {
1478
+ this.worker?.terminate?.();
1479
+ }
1480
+ }
1481
+
1482
+ export class Transport {
1483
+ /** Factory (spec §2): default is fetch. */
1484
+ static create(config = {}) {
1485
+ switch (config.transport) {
1486
+ case "sse":
1487
+ return new SSETransport(config);
1488
+ case "ws": case "websocket":
1489
+ return new WebSocketTransport(config);
1490
+ case "chunked":
1491
+ return new ChunkedTransport(config);
1492
+ case "worker":
1493
+ return new WorkerTransport(config);
1494
+ default:
1495
+ return new FetchTransport(config);
1496
+ }
1497
+ }
1498
+ }
1499
+
1500
+ /** Create a connection manager for one authentication context. */
1501
+ export function frameConnections(config = {}) {
1502
+ const manager = new ConnectionManager();
1503
+ for (const transport of ["sse", "websocket", "chunked"]) manager.register(transport, (options, events) => {
1504
+ const channel = options.channel ?? Transport.create({ ...config, headers: { ...config.headers, ...options.headers }, transport, protocol: "frame" });
1505
+ let waiting = [];
1506
+ const opened = () => {
1507
+ for (const pending of waiting.splice(0)) pending.resolve();
1508
+ events.opened();
1509
+ };
1510
+ const disconnected = cause => {
1511
+ for (const pending of waiting.splice(0)) pending.reject(cause);
1512
+ events.disconnected(cause);
1513
+ };
1514
+ if (channel.config) Object.assign(channel.config, { onOpen: opened, onError: disconnected, listening: events.listening });
1515
+ const result = channel.connect(options.endpoint, options.data, message => {
1516
+ if (message.type !== "frame") { disconnected(new Error("Expected a Foundation frame")); return; }
1517
+ for (const frame of message.frames) events.deliver(frame);
1518
+ });
1519
+ Promise.resolve(result).catch(disconnected);
1520
+ return {
1521
+ send: transport === "websocket" ? async bytes => {
1522
+ if (channel.ws?.readyState === 0) await new Promise((resolve, reject) => waiting.push({resolve, reject}));
1523
+ channel.send(bytes);
1524
+ } : undefined,
1525
+ close() {
1526
+ for (const pending of waiting.splice(0)) pending.reject(new Error("Connection closed"));
1527
+ channel.disconnect();
1528
+ },
1529
+ };
1530
+ });
1531
+ return manager;
1532
+ }
1533
+
1534
+ // ─── Protocol handlers (decision 022 content types) ───────────────────────────
1535
+
1536
+ // A binary message carries one EWF1 frame or a generic JSON envelope.
1537
+ export function decodeEnvelopeFrame(bytes) {
1538
+ if (ProtocolHandler.frameHook?.isFrame(bytes)) return { type: "frame", frames: [bytes] };
1539
+ if (!(bytes instanceof Uint8Array)) bytes = new Uint8Array(bytes);
1540
+ if (bytes.byteLength < 6) {
1541
+ console.error("decodeEnvelopeFrame: truncated header", bytes.byteLength);
1542
+ return null;
1543
+ }
1544
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1545
+ const protocol = view.getUint8(0);
1546
+ const version = view.getUint8(1);
1547
+ const length = view.getUint32(2, true);
1548
+ const payload = bytes.subarray(6);
1549
+ if (payload.byteLength !== length) {
1550
+ console.error(`decodeEnvelopeFrame: length mismatch (header ${length}, payload ${payload.byteLength})`);
1551
+ return null;
1552
+ }
1553
+ if (protocol === 2) {
1554
+ try {
1555
+ return routeJson(JSON.parse(new TextDecoder().decode(payload)));
1556
+ } catch (error) {
1557
+ console.error("decodeEnvelopeFrame: json payload did not parse", error);
1558
+ return null;
1559
+ }
1560
+ }
1561
+ console.error(`decodeEnvelopeFrame: unknown protocol ${protocol} v${version}`);
1562
+ return null;
1563
+ }
1564
+
1565
+ function base64ToBytes(text) {
1566
+ const bin = atob(String(text).trim());
1567
+ const bytes = new Uint8Array(bin.length);
1568
+ for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i);
1569
+ return bytes;
1570
+ }
1571
+
1572
+ function streamEventResult(kind, raw) {
1573
+ if (kind === "frame") return { type: "frame", frames: [base64ToBytes(raw)] };
1574
+ if (kind === "json") {
1575
+ try {
1576
+ return routeJson(JSON.parse(raw));
1577
+ } catch {
1578
+ return { type: "raw", text: String(raw) };
1579
+ }
1580
+ }
1581
+ if (kind === "arrow") return removedArrow();
1582
+ return routeHtml(String(raw));
1583
+ }
1584
+
1585
+ function routeJson(value) {
1586
+ if (value && typeof value === "object" && value.morph) {
1587
+ return { type: "json-morph", morph: value.morph };
1588
+ }
1589
+ return { type: "json", patches: value };
1590
+ }
1591
+
1592
+ /** HTML island-wrapper detection (spec §3). */
1593
+ function routeHtml(html) {
1594
+ const match = /^\s*<island\b[^>]*data-target="([^"]+)"[^>]*data-action="([^"]+)"[^>]*>([\s\S]*)<\/island>\s*$/.exec(html);
1595
+ if (match) {
1596
+ return { type: "html-morph", target: match[1], action: match[2], content: match[3] };
1597
+ }
1598
+ return { type: "html", html };
1599
+ }
1600
+
1601
+ function removedArrow() {
1602
+ console.error('mount: protocol "arrow" was removed; use "frame"');
1603
+ return {type:"raw", text:""};
1604
+ }
1605
+
1606
+ const emptyProtocolHandler = {
1607
+ process: async () => ({type:"raw", text:""}),
1608
+ };
1609
+
1610
+ export class JsonHandler {
1611
+ async process(response) {
1612
+ return routeJson(await response.json());
1613
+ }
1614
+ }
1615
+
1616
+ export class HtmlHandler {
1617
+ async process(response) {
1618
+ return routeHtml(await response.text());
1619
+ }
1620
+ }
1621
+
1622
+ export class RawHandler {
1623
+ async process(response) {
1624
+ return { type: "raw", text: await response.text() };
1625
+ }
1626
+ }
1627
+
1628
+ /**
1629
+ * NEGOTIATION TABLE (feature 04 — the contract, finally written down):
1630
+ *
1631
+ * | channel | decided by |
1632
+ * |--------------|--------------------------------------------------------------|
1633
+ * | HTTP fetch | response `content-type` (`fromContentType` below) |
1634
+ * | SSE | per-message `event:` name (html/json/frame; unnamed = html) |
1635
+ * | WS binary | the EWF1 identifier or the generic JSON envelope|
1636
+ * | WS text | declared `protocol` attr, else json |
1637
+ * | `protocol=` | mount attribute OVERRIDES headers/event names entirely |
1638
+ *
1639
+ * Precedence: attribute > headers/event name > channel default.
1640
+ */
1641
+ function isViewResponse(response) {
1642
+ return response.headers?.get?.("content-type")?.split(";")[0].trim().toLowerCase() === "application/vnd.ewe.frame";
1643
+ }
1644
+
1645
+ export class FrameHandler {
1646
+ async process(response) {
1647
+ if (!response.ok) throw new Error("Frame request failed with HTTP " + response.status);
1648
+ const hook = ProtocolHandler.frameHook;
1649
+ if (!hook) {
1650
+ console.error("frame received but the frame runtime is not installed");
1651
+ return { type: "raw", text: "" };
1652
+ }
1653
+ if (isViewResponse(response)) {
1654
+ return { type: "frame", frames: [await hook.readViewResponse(response, hook.maxFrameBytes)] };
1655
+ }
1656
+ const frames = [];
1657
+ let total = 0;
1658
+ for await (const frame of hook.readFrames(response.body, hook.maxFrameBytes)) {
1659
+ total += frame.length;
1660
+ if (total > hook.maxFrameBytes) throw new RangeError("Frame reply exceeds byte limit");
1661
+ frames.push(frame);
1662
+ }
1663
+ return { type: "frame", frames };
1664
+ }
1665
+ }
1666
+
1667
+ export class ProtocolHandler {
1668
+ static frameHook = null;
1669
+ /** Explicit handler by name — the mount `protocol` attribute override. */
1670
+ static named(name) {
1671
+ switch (name) {
1672
+ case "frame": return new FrameHandler();
1673
+ case "arrow":
1674
+ removedArrow();
1675
+ return emptyProtocolHandler;
1676
+ case "json":
1677
+ return new JsonHandler();
1678
+ case "html":
1679
+ return new HtmlHandler();
1680
+ default:
1681
+ return null;
1682
+ }
1683
+ }
1684
+
1685
+ /** Content-type table (spec §3, G46). */
1686
+ static fromContentType(response) {
1687
+ const ct = response.headers?.get?.("content-type") || "";
1688
+ if (isViewResponse(response) || ct.includes("primal-frame")) return new FrameHandler();
1689
+ if (ct.includes("primal-arrow") || ct.includes("event-stream-arrow")) return ProtocolHandler.named("arrow");
1690
+ if (ct.includes("primal-json") || ct.includes("event-stream-json")) return new JsonHandler();
1691
+ if (ct.includes("primal-html") || ct.includes("event-stream-html") || ct.includes("text/html")) {
1692
+ return new HtmlHandler();
1693
+ }
1694
+ return new RawHandler();
1695
+ }
1696
+ }
1697
+
1698
+ // ─── Hydrator (styles + scripts ONLY — events are F08's, G2) ──────────────────
1699
+
1700
+ /**
1701
+ * Prefix every rule selector with `prefix` — `.title{...}` inside `#island-1`
1702
+ * becomes `#island-1 .title{...}`; compound selectors each get the prefix.
1703
+ * Pure function (the CSSStyleSheet adoption around it is browser-only).
1704
+ */
1705
+ export function scopeCss(cssText, prefix) {
1706
+ return cssText.replace(/(^|\})\s*([^@{}][^{}]*)\{/g, (_, brace, selectors) => {
1707
+ const scoped = selectors
1708
+ .split(",")
1709
+ .map((sel) => `${prefix} ${sel.trim()}`)
1710
+ .join(", ");
1711
+ return `${brace}\n${scoped} {`;
1712
+ });
1713
+ }
1714
+
1715
+ export class Hydrator {
1716
+ static scopeExtensions = [];
1717
+ static behaviourMarkers = null;
1718
+ /** Scoped-script execution scope (spec §5). */
1719
+ static createScope(targetElement) {
1720
+ const eventCleanups = [];
1721
+ const scope = {
1722
+ targets: () => targetElement.querySelectorAll("[primal-id]"),
1723
+ parent: () => targetElement,
1724
+ querySelector: (sel) => targetElement.querySelector(sel),
1725
+ querySelectorAll: (sel) => targetElement.querySelectorAll(sel),
1726
+ addEvent(target, event, handler, options) {
1727
+ const el = typeof target === "string" ? targetElement.querySelector(target) : target;
1728
+ if (el) {
1729
+ el.addEventListener(event, handler, options);
1730
+ eventCleanups.push(() => el.removeEventListener(event, handler, options));
1731
+ }
1732
+ },
1733
+ onDispose(dispose) { eventCleanups.push(dispose); },
1734
+ cleanup() {
1735
+ for (const cleanup of eventCleanups.splice(0)) cleanup();
1736
+ },
1737
+ };
1738
+ for (const extend of Hydrator.scopeExtensions) extend(scope, targetElement);
1739
+ return scope;
1740
+ }
1741
+
1742
+ /** Styles + scripts. NOT events (F08 owns primal:on*). Browser-leaning. */
1743
+ static hydrate(root, doc = root.ownerDocument ?? globalThis.document) {
1744
+ if (typeof root.querySelectorAll !== "function") return;
1745
+ Hydrator.behaviourMarkers?.(root);
1746
+ // Styles: scope + adopt.
1747
+ for (const style of root.querySelectorAll("style[primal\\:style]")) {
1748
+ const prefix = root.id ? `#${root.id}` : `[primal-id="${root.getAttribute?.("primal-id") ?? ""}"]`;
1749
+ const scoped = scopeCss(style.textContent, prefix);
1750
+ if (typeof CSSStyleSheet === "function" && doc?.adoptedStyleSheets) {
1751
+ const sheet = new CSSStyleSheet();
1752
+ sheet.replaceSync(scoped);
1753
+ doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet];
1754
+ (root._sheets ??= []).push(sheet);
1755
+ }
1756
+ style.remove?.();
1757
+ }
1758
+ // Scripts: run with the scope object; per-script error isolation. Scope to
1759
+ // the script's OWN parent (spec §5.2), so hydrating a subtree containing
1760
+ // many components scopes each script to its component root, not the subtree.
1761
+ for (const script of root.querySelectorAll("script[primal\\:script]")) {
1762
+ const owner = script.parentElement ?? root;
1763
+ const scope = Hydrator.createScope(owner);
1764
+ try {
1765
+ const source = script.textContent.trim();
1766
+ const body = /^(?:async\s+)?function\s*\(/.test(source) ? `(${source})(scope)` : source;
1767
+ new Function("scope", body)(scope);
1768
+ Patcher.registerUnmount(owner, () => scope.cleanup());
1769
+ } catch (error) {
1770
+ scope.cleanup();
1771
+ console.error("Hydrator: scoped script failed", error);
1772
+ }
1773
+ script.remove?.();
1774
+ }
1775
+ }
1776
+ }
1777
+
1778
+ // ─── Patcher ───────────────────────────────────────────────────────────────────
1779
+
1780
+ export class Patcher {
1781
+ /** Document registry, event dispatcher, signal bridge and frame reader. */
1782
+ static runtime = { dispatcher: null, registry: null, signalBridge: null, frames: null };
1783
+ /** Monotonic count of applied results (the frame instrument; see `route`). */
1784
+ static frameSeq = 0;
1785
+ static localScopes = new WeakMap();
1786
+
1787
+ static registerUnmount(node, dispose) {
1788
+ let hooks = Patcher.localScopes.get(node);
1789
+ if (!hooks) Patcher.localScopes.set(node, hooks = new Set());
1790
+ hooks.add(dispose);
1791
+ }
1792
+
1793
+ static releaseScope(node) {
1794
+ const hooks = Patcher.localScopes.get(node);
1795
+ Patcher.localScopes.delete(node);
1796
+ if (hooks) for (const dispose of hooks) {
1797
+ try { dispose(); } catch (error) { console.error("Component cleanup failed", error); }
1798
+ }
1799
+ }
1800
+
1801
+ static releaseTree(node) {
1802
+ for (const child of Array.from(node.childNodes ?? [])) Patcher.releaseTree(child);
1803
+ Patcher.releaseScope(node);
1804
+ }
1805
+
1806
+ static materialize(html, target, doc = target.ownerDocument ?? globalThis.document) {
1807
+ if (typeof doc?.createRange === "function") {
1808
+ const fragment = doc.createRange().createContextualFragment(html);
1809
+ target.appendChild(fragment);
1810
+ } else {
1811
+ target.innerHTML = html;
1812
+ }
1813
+ Hydrator.hydrate(target, doc);
1814
+ Patcher.runtime.dispatcher?.scanAndWire?.(target); // F08 (idempotent)
1815
+ }
1816
+
1817
+ static ensureRegistry(doc) {
1818
+ if (Patcher.runtime.document !== doc) {
1819
+ Patcher.runtime.document = doc;
1820
+ Patcher.runtime.registry = new NodeRegistry().seedDocument(doc);
1821
+ }
1822
+ return Patcher.runtime.registry;
1823
+ }
1824
+
1825
+ static applySignalPatches(patches) {
1826
+ const bridge = Patcher.runtime.signalBridge;
1827
+ if (bridge?.applyPatches) bridge.applyPatches(patches);
1828
+ else console.warn("Patcher: no signalBridge installed; JSON patches dropped", patches);
1829
+ }
1830
+
1831
+ /** Route one ProtocolHandler result to the DOM (shared by both mounts). */
1832
+ static route(result, targetEl, doc) {
1833
+ Patcher.applyRoute(result, targetEl, doc);
1834
+ if (result.type !== "frame") Patcher.markApplied();
1835
+ }
1836
+
1837
+ static markApplied() {
1838
+ // Frame instrument: every applied result bumps a sequence + timestamp. Cheap,
1839
+ // always-on, broadly useful — a server-driven client (or a test driver) can
1840
+ // poll `globalThis.__primalFrames` to know the DOM has caught up.
1841
+ Patcher.frameSeq += 1;
1842
+ const stamp = (typeof performance !== "undefined" ? performance.now() : Date.now());
1843
+ if (typeof globalThis !== "undefined") {
1844
+ globalThis.__primalFrames = { seq: Patcher.frameSeq, at: stamp };
1845
+ }
1846
+ }
1847
+
1848
+ /** Apply one routed result (the actual DOM work; instrumented by `route`). */
1849
+ static applyRoute(result, targetEl, doc) {
1850
+ switch (result.type) {
1851
+ case "frame":
1852
+ if (!Patcher.runtime.frames) console.error("frame received but the frame runtime is not installed");
1853
+ else for (const frame of result.frames) Patcher.runtime.frames.receive(frame, { viewMount: targetEl });
1854
+ break;
1855
+ case "html":
1856
+ Patcher.materialize(result.html, targetEl, doc);
1857
+ break;
1858
+ case "html-morph": {
1859
+ const morphTarget = doc.querySelector(result.target);
1860
+ if (morphTarget && typeof doc.createRange === "function") {
1861
+ MorphDom.morph(morphTarget, doc.createRange().createContextualFragment(result.content), doc);
1862
+ }
1863
+ break;
1864
+ }
1865
+ case "json-morph": {
1866
+ const morphTarget = doc.querySelector(result.morph.target);
1867
+ if (morphTarget && typeof doc.createRange === "function") {
1868
+ MorphDom.morph(morphTarget, doc.createRange().createContextualFragment(result.morph.content), doc);
1869
+ }
1870
+ break;
1871
+ }
1872
+ case "json":
1873
+ Patcher.applySignalPatches(result.patches);
1874
+ break;
1875
+ default:
1876
+ targetEl.textContent = result.text ?? "";
1877
+ }
1878
+ }
1879
+ }
1880
+
1881
+ // ─── Response placement (spec §9, shared by both mounts) ──────────────────────
1882
+
1883
+ // A frame owns replacement and disposal. Keep the mount intact until the frame applies.
1884
+ export function frameMountTarget(element, target, doc) {
1885
+ if (!target) return element;
1886
+ return target === "parent" ? element.parentElement : doc.querySelector(target);
1887
+ }
1888
+
1889
+ export function resolveMountTarget(element, target, doc) {
1890
+ if (!target) {
1891
+ // Self-replacement: the mount is a placeholder that disappears (G29).
1892
+ const container = doc.createElement("div");
1893
+ element.parentNode?.replaceChild?.(container, element);
1894
+ return container;
1895
+ }
1896
+ if (target === "parent") {
1897
+ const parent = element.parentElement ?? element.parent ?? null;
1898
+ if (!parent) throw new Error("mount target not found: parent");
1899
+ clearChildren(parent);
1900
+ return parent;
1901
+ }
1902
+ const found = doc.querySelector(target);
1903
+ if (!found) throw new Error(`mount target not found: ${target}`);
1904
+ clearChildren(found);
1905
+ return found;
1906
+ }
1907
+
1908
+ function clearChildren(el) {
1909
+ while (el.firstChild) el.removeChild(el.firstChild);
1910
+ }
1911
+
1912
+ // ─── Custom elements (browser base class guarded for node) ─────────────────────
1913
+
1914
+ const BaseElement = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
1915
+
1916
+ /** `<primal-island>` — no network; styles + scripts + F08 event wiring. */
1917
+ export class IslandComponent extends BaseElement {
1918
+ connectedCallback() {
1919
+ Hydrator.hydrate(this);
1920
+ Patcher.runtime.dispatcher?.scanAndWire?.(this);
1921
+ }
1922
+
1923
+ disconnectedCallback() {
1924
+ const doc = this.ownerDocument ?? globalThis.document;
1925
+ if (this._sheets?.length && doc?.adoptedStyleSheets) {
1926
+ doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter((s) => !this._sheets.includes(s));
1927
+ }
1928
+ this._sheets = [];
1929
+ Patcher.runtime.dispatcher?.removeListeners?.(this);
1930
+ }
1931
+ }
1932
+
1933
+ /** Shared mount bootstrap: read attrs, build transport, resolve target. */
1934
+ function mountSetup(element, defaults = {}) {
1935
+ const api = element.getAttribute("api");
1936
+ if (!api) throw new Error(`${element.tagName?.toLowerCase() ?? "mount"}: missing api attribute`);
1937
+ let data = {};
1938
+ try {
1939
+ data = JSON.parse(element.getAttribute("data") || "{}");
1940
+ } catch (error) {
1941
+ console.error("mount: invalid JSON in data attribute", error);
1942
+ }
1943
+ const transport =
1944
+ element._transportOverride ??
1945
+ Transport.create({
1946
+ transport: element.getAttribute("transport") ?? defaults.transport,
1947
+ protocol: element.getAttribute("protocol") ?? undefined,
1948
+ url: api,
1949
+ });
1950
+ return { api, data, transport, target: element.getAttribute("target") };
1951
+ }
1952
+
1953
+ /** `<mount-data>` — one request, one response (spec §7). */
1954
+ export class MountDataComponent extends BaseElement {
1955
+ async connectedCallback() {
1956
+ const doc = this.ownerDocument ?? globalThis.document;
1957
+ try {
1958
+ const binding = Patcher.runtime.onMountConnect?.(this, false);
1959
+ this._frameMount = binding;
1960
+ if (binding?.local) return;
1961
+ const { api, data, transport, target } = mountSetup(this);
1962
+ this._transport = transport;
1963
+ const method = this.getAttribute("method") || "POST";
1964
+ const result = await transport.send(binding ? binding.url(api) : api, method, data);
1965
+ if (binding) binding.receive(result);
1966
+ else {
1967
+ const mount = result.type === "frame" ? frameMountTarget(this, target, doc) : resolveMountTarget(this, target, doc);
1968
+ Patcher.route(result, mount, doc);
1969
+ }
1970
+ } catch (error) {
1971
+ console.error("mount-data:", error);
1972
+ }
1973
+ }
1974
+
1975
+ disconnectedCallback() {
1976
+ this._frameMount?.close();
1977
+ this._transport?.disconnect?.();
1978
+ }
1979
+ }
1980
+
1981
+ /** Open a stream while its element is connected. */
1982
+ export class MountStreamComponent extends BaseElement {
1983
+ connectedCallback() {
1984
+ const doc = this.ownerDocument ?? globalThis.document;
1985
+ try {
1986
+ const binding = Patcher.runtime.onMountConnect?.(this, true);
1987
+ this._frameMount = binding;
1988
+ if (binding?.local) return;
1989
+ let generation = 0;
1990
+ const open = () => {
1991
+ const current = ++generation;
1992
+ const { api, data, transport, target } = mountSetup(this, { transport: "sse" });
1993
+ // Frame operations name their own targets. The mount owns the connection.
1994
+ const targetEl = binding ? null : resolveMountTarget(this, target, doc);
1995
+ if (binding?.managed) {
1996
+ const handle = binding.managed({ api, data, transport });
1997
+ if (handle) { this._transport = { disconnect: () => handle.close() }; return; }
1998
+ }
1999
+ this._transport = transport;
2000
+ if (!binding && this.isConnected === false && targetEl?.isConnected && !this._targetObserver) {
2001
+ // Legacy markup replaces its placeholder. Its replacement owns the connection.
2002
+ this._targetObserver = new MutationObserver(() => {
2003
+ if (!targetEl.isConnected) this.disconnectedCallback();
2004
+ });
2005
+ this._targetObserver.observe(doc, { childList: true, subtree: true });
2006
+ }
2007
+ if (binding && transport.config) {
2008
+ transport.config.nextUrl = url => binding.url(url);
2009
+ transport.config.onExpired = binding.expired;
2010
+ }
2011
+ const payload = binding && this.getAttribute("data") === null ? undefined : data;
2012
+ transport.connect(binding ? binding.url(api) : api, payload, result => {
2013
+ if (current !== generation || transport !== this._transport) return;
2014
+ if (binding) binding.receive(result);
2015
+ else Patcher.route(result, targetEl, doc);
2016
+ });
2017
+ };
2018
+ this._restartFrameStream = () => { this._transport?.disconnect?.(); open(); };
2019
+ open();
2020
+ } catch (error) {
2021
+ console.error("mount-stream:", error);
2022
+ }
2023
+ }
2024
+
2025
+ disconnectedCallback() {
2026
+ this._frameMount?.close();
2027
+ this._restartFrameStream = null;
2028
+ this._targetObserver?.disconnect();
2029
+ this._targetObserver = null;
2030
+ this._transport?.disconnect?.();
2031
+ this._transport = null;
2032
+ }
2033
+ }
2034
+
2035
+ /** Register the custom elements (browser only; idempotent). */
2036
+ export function registerWebComponents() {
2037
+ if (typeof customElements === "undefined") return;
2038
+ if (!customElements.get("primal-island")) customElements.define("primal-island", IslandComponent);
2039
+ if (!customElements.get("mount-data")) customElements.define("mount-data", MountDataComponent);
2040
+ if (!customElements.get("mount-stream")) customElements.define("mount-stream", MountStreamComponent);
2041
+ }
2042
+
2043
+ // Connect WebAssembly allocations, event delivery and local scope disposal.
2044
+ export function registerWasmApp(runtime, opts = {}) {
2045
+ const doc = opts.document ?? globalThis.document;
2046
+ if (!doc) {
2047
+ console.error("registerWasmApp: no document available (non-browser environment)");
2048
+ return;
2049
+ }
2050
+ const bridge = runtime.bridge ?? runtime;
2051
+ const frames = globalThis.EweFrames?.installFrameRuntime(globalThis.FoundationWasmUiRuntime, opts);
2052
+ if (!frames) throw new Error("registerWasmApp requires foundation-ui-frames.js");
2053
+ const dispatcher = Patcher.runtime.dispatcher ?? new EventDispatcher(callbackDeliver(runtime.callbacks));
2054
+ dispatcher.deliver = callbackDeliver(runtime.callbacks);
2055
+ dispatcher.deliverSignal = signalDeliver(bridge);
2056
+ Patcher.runtime.dispatcher = dispatcher;
2057
+ const owned = new WeakSet();
2058
+ const onMount = (id, node) => {
2059
+ if (!owned.has(node) && bridge.exports?.ewe_ui_dispose_mount) {
2060
+ owned.add(node);
2061
+ Patcher.registerUnmount(node, () => bridge.exports.ewe_ui_dispose_mount(id));
2062
+ }
2063
+ };
2064
+ const onEvent = (name, id, event, el) => {
2065
+ const setter = parseCallbackId(el.getAttribute?.("primal:setter"));
2066
+ if (setter !== null) dispatcher.deliverSignal(setter, buildEventData(name, event, el));
2067
+ };
2068
+ runtime.dispatcher.setRawHandler(ProtocolHandler.frameHook.isFrame, bytes => {
2069
+ if (bytes.byteLength > frames.maxFrameBytes) return frames.receive(bytes);
2070
+ return frames.receive(Uint8Array.from(bytes), {onMount, onEvent});
2071
+ });
2072
+ // Initial scan + observer: wires primal:on* attrs that exist on page load.
2073
+ initEventRuntime(dispatcher, doc);
2074
+ }
2075
+
2076
+ /**
2077
+ * The frame instrument: `{ seq, at }` — `seq` is the count of applied routed
2078
+ * results, `at` the timestamp of the last apply. A server-driven client (or a
2079
+ * test driver) polls this to know the DOM has caught up with the stream. Also
2080
+ * mirrored on `globalThis.__primalFrames`.
2081
+ */
2082
+ export function frameStats() {
2083
+ return globalThis.__primalFrames ?? { seq: Patcher.frameSeq, at: null };
2084
+ }
2085
+
2086
+ /** Build the `window.primal` namespace (G30) over injected runtime seams. */
2087
+ export function createPrimal({ dispatcher, doc = globalThis.document } = {}) {
2088
+ return {
2089
+ mountData(api, data, targetNode, opts = {}) {
2090
+ const transport = Transport.create({ transport: opts.transport, url: api });
2091
+ return transport
2092
+ .send(api, opts.method || "POST", data)
2093
+ .then((result) => Patcher.route(result, targetNode, doc));
2094
+ },
2095
+ mountStream(api, data, targetNode, opts = {}) {
2096
+ const transport = Transport.create({ transport: opts.transport ?? "sse", url: api });
2097
+ transport.connect(api, data, (result) => Patcher.route(result, targetNode, doc));
2098
+ return transport;
2099
+ },
2100
+ unmount(element) {
2101
+ element.disconnectedCallback?.();
2102
+ element.remove?.();
2103
+ },
2104
+ on: (selector, event, handler) => doc.querySelector(selector)?.addEventListener(event, handler),
2105
+ onclick(selector, handler) {
2106
+ this.on(selector, "click", handler);
2107
+ },
2108
+ onchange(selector, handler) {
2109
+ this.on(selector, "change", handler);
2110
+ },
2111
+ off: (selector, event, handler) => doc.querySelector(selector)?.removeEventListener(event, handler),
2112
+ scope: (element) => Hydrator.createScope(element),
2113
+ dispatcher,
2114
+ Transport,
2115
+ ProtocolHandler,
2116
+ Patcher,
2117
+ Hydrator,
2118
+ };
2119
+ }
2120
+
2121
+ if (typeof window !== "undefined") {
2122
+ queueMicrotask(registerWebComponents);
2123
+ window.primal ??= createPrimal({});
2124
+ }
2125
+
2126
+ // mirror lets classic (non-module) scripts on the same page reach the DOM runtime as
2127
+ // `globalThis.FoundationWasmUiRuntime` once the module has loaded.
2128
+ globalThis.FoundationWasmUiRuntime = Object.freeze({
2129
+ RESERVED,
2130
+ NodeRegistry,
2131
+ MorphDom,
2132
+ moveBefore,
2133
+ buildEventData,
2134
+ parseCallbackId,
2135
+ EventDispatcher,
2136
+ CONVENIENCE_EVENTS,
2137
+ callbackDeliver,
2138
+ signalDeliver,
2139
+ resolveFunctionRef,
2140
+ resolveDelegateTarget,
2141
+ initEventRuntime,
2142
+ Transport,
2143
+ ProtocolHandler,
2144
+ Patcher,
2145
+ Hydrator,
2146
+ scopeCss,
2147
+ RequestQueue,
2148
+ SseParser,
2149
+ FetchEventSource,
2150
+ WSBatchQueue,
2151
+ WorkerBatchQueue,
2152
+ probeBatching,
2153
+ parseBatchEntry,
2154
+ reconnectDelay,
2155
+ resolveMountTarget,
2156
+ IslandComponent,
2157
+ MountDataComponent,
2158
+ MountStreamComponent,
2159
+ registerWebComponents,
2160
+ registerWasmApp,
2161
+ createPrimal,
2162
+ DomHeap,
2163
+ domAbi,
2164
+ });