Skip to main content

ftui_web/
sdk_adapter.rs

1//! First-party integration adapters for the FrankenTermJS SDK
2//! (bd-2vr05.9.3).
3//!
4//! # Why this exists
5//!
6//! Replacing xterm.js in a real app is mostly a *lifecycle wiring* problem:
7//! when to call `init`, when it is safe to `attachConnect`, how resize
8//! observation feeds `resize`, and — the classic integration bug — what
9//! happens when React StrictMode runs your effect twice. The SDK contract
10//! (`docs/spec/frankenterm-web-api.md`) defines the method surface; this
11//! module defines the **recommended wiring** as an executable, deterministic
12//! model instead of prose:
13//!
14//! * [`AdapterLifecycle`] — a pure state machine encoding the legal call
15//!   order for a host adapter (mount → attach → resize/input → detach →
16//!   dispose), with per-host-kind semantics: the React adapter treats
17//!   StrictMode-style repeated mounts/cleanups as idempotent no-ops, the
18//!   vanilla adapter reports them as misuse.
19//! * [`recommended_wiring`] — the ordered wiring steps for each adapter
20//!   kind, each step naming the *real* stable contract method it calls.
21//! * [`vanilla_example`] / [`react_example`] — canonical example sources.
22//!   The committed files under `crates/ftui-web/sdk/examples/` must be
23//!   byte-identical to these generators (lockstep-tested, exactly like the
24//!   `.d.ts` in [`crate::sdk_event_model`]), so shipped examples can never
25//!   drift from the modeled lifecycle.
26//!
27//! Like the rest of the durable SDK surface, this lives in-tree in `ftui-web`
28//! while the `frankenterm-web` WASM packaging crate remains out-of-tree; the
29//! examples reference only the **Stable Method Surface (`1.0.0`)** from the
30//! canonical contract.
31//!
32//! # Determinism and logging
33//!
34//! Every applied action (and every rejected misuse) yields a JSONL line with
35//! a monotone `seq` and the host-chosen `adapter_id` as the correlation key.
36//! The model is timestamp-free so identical action sequences produce
37//! byte-identical logs; wall-clock timestamps are added by the E2E harness
38//! layer (`scripts/frankenterm_js_sdk_adapter_e2e.sh`) where determinism is
39//! not required.
40
41use core::fmt;
42
43/// Schema version for adapter lifecycle events and wiring tables.
44pub const ADAPTER_SCHEMA_VERSION: &str = "1.0.0";
45
46/// Stable contract methods referenced by the adapter wiring (a subset of the
47/// **Stable Method Surface (`1.0.0`)** in `docs/spec/frankenterm-web-api.md`).
48pub const WIRING_CONTRACT_METHODS: [&str; 9] = [
49    "apiContract",
50    "init",
51    "fitToContainer",
52    "resize",
53    "attachConnect",
54    "input",
55    "drainEventSubscriptionJsonl",
56    "attachClose",
57    "destroy",
58];
59
60// ============================================================================
61// Adapter kinds
62// ============================================================================
63
64/// First-party adapter flavors.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum AdapterKind {
67    /// Plain-DOM adapter: explicit create/dispose, misuse is an error.
68    Vanilla,
69    /// React adapter (also the Next.js wiring): effect-driven lifecycle where
70    /// StrictMode intentionally double-invokes mount/cleanup, so repeated
71    /// idempotent actions are deduplicated instead of rejected.
72    React,
73}
74
75impl AdapterKind {
76    /// Both adapter kinds, in stable order.
77    pub const ALL: [AdapterKind; 2] = [AdapterKind::Vanilla, AdapterKind::React];
78
79    /// Stable wire string.
80    #[must_use]
81    pub const fn as_str(self) -> &'static str {
82        match self {
83            AdapterKind::Vanilla => "vanilla",
84            AdapterKind::React => "react",
85        }
86    }
87}
88
89impl fmt::Display for AdapterKind {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str(self.as_str())
92    }
93}
94
95// ============================================================================
96// Lifecycle phases and actions
97// ============================================================================
98
99/// Adapter lifecycle phase.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
101pub enum AdapterPhase {
102    /// Constructed; no DOM or engine resources yet.
103    Created,
104    /// Engine initialized into a container (`init` called).
105    Mounted,
106    /// Transport attached (`attachConnect` succeeded).
107    Attached,
108    /// Transport detached (`attachClose`), engine still mounted.
109    Detached,
110    /// Fully torn down (`destroy`); terminal state.
111    Disposed,
112}
113
114impl AdapterPhase {
115    /// Stable wire string.
116    #[must_use]
117    pub const fn as_str(self) -> &'static str {
118        match self {
119            AdapterPhase::Created => "created",
120            AdapterPhase::Mounted => "mounted",
121            AdapterPhase::Attached => "attached",
122            AdapterPhase::Detached => "detached",
123            AdapterPhase::Disposed => "disposed",
124        }
125    }
126}
127
128/// Host action applied to the adapter (each maps to stable contract calls).
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum AdapterAction {
131    /// Initialize the engine into a container (`init`, then `fitToContainer`).
132    Mount,
133    /// Connect the transport (`attachConnect`).
134    Attach,
135    /// Propagate a size change (`resize(cols, rows)`).
136    Resize {
137        /// New column count.
138        cols: u16,
139        /// New row count.
140        rows: u16,
141    },
142    /// Forward host input (`input`).
143    Input {
144        /// Number of host-encoded input bytes forwarded.
145        bytes: u32,
146    },
147    /// Close the transport (`attachClose`).
148    Detach,
149    /// Tear everything down (`destroy`).
150    Dispose,
151}
152
153impl AdapterAction {
154    /// Stable wire label.
155    #[must_use]
156    pub const fn label(&self) -> &'static str {
157        match self {
158            AdapterAction::Mount => "mount",
159            AdapterAction::Attach => "attach",
160            AdapterAction::Resize { .. } => "resize",
161            AdapterAction::Input { .. } => "input",
162            AdapterAction::Detach => "detach",
163            AdapterAction::Dispose => "dispose",
164        }
165    }
166
167    fn detail(&self) -> String {
168        match self {
169            AdapterAction::Resize { cols, rows } => format!("cols={cols} rows={rows}"),
170            AdapterAction::Input { bytes } => format!("bytes={bytes}"),
171            _ => String::new(),
172        }
173    }
174}
175
176// ============================================================================
177// Outcomes, events, and misuse
178// ============================================================================
179
180/// How an accepted action was handled.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum AdapterOutcome {
183    /// The action performed its contract calls and advanced the phase.
184    Applied,
185    /// React-only: the action repeated an already-satisfied idempotent step
186    /// (StrictMode double mount / double cleanup) and was deduplicated.
187    StrictModeDeduped,
188}
189
190impl AdapterOutcome {
191    /// Stable wire string.
192    #[must_use]
193    pub const fn as_str(self) -> &'static str {
194        match self {
195            AdapterOutcome::Applied => "applied",
196            AdapterOutcome::StrictModeDeduped => "strict_mode_deduped",
197        }
198    }
199}
200
201/// One accepted lifecycle transition (JSONL-serializable).
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct AdapterEvent {
204    /// Monotone per-adapter sequence number (correlation within a run).
205    pub seq: u64,
206    /// Host-chosen correlation id.
207    pub adapter_id: String,
208    /// Adapter flavor.
209    pub kind: AdapterKind,
210    /// Action label.
211    pub action: &'static str,
212    /// Phase before the action.
213    pub phase_before: AdapterPhase,
214    /// Phase after the action.
215    pub phase_after: AdapterPhase,
216    /// Applied vs deduplicated.
217    pub outcome: AdapterOutcome,
218    /// Action-specific detail (`cols=..`, `bytes=..`), possibly empty.
219    pub detail: String,
220}
221
222impl AdapterEvent {
223    /// Deterministic single-line JSON (timestamp-free; see module docs).
224    #[must_use]
225    pub fn to_jsonl(&self) -> String {
226        format!(
227            "{{\"event\":\"adapter_transition\",\"schema\":\"{}\",\"seq\":{},\"adapter_id\":\"{}\",\"adapter\":\"{}\",\"action\":\"{}\",\"phase_before\":\"{}\",\"phase_after\":\"{}\",\"outcome\":\"{}\",\"detail\":\"{}\"}}",
228            ADAPTER_SCHEMA_VERSION,
229            self.seq,
230            escape_json(&self.adapter_id),
231            self.kind.as_str(),
232            self.action,
233            self.phase_before.as_str(),
234            self.phase_after.as_str(),
235            self.outcome.as_str(),
236            escape_json(&self.detail),
237        )
238    }
239}
240
241/// A rejected action: the host called the adapter out of order.
242///
243/// This is the *adapter-layer* misuse taxonomy (lifecycle ordering), distinct
244/// from the engine-level [`crate::sdk_event_model::SdkErrorKind`] taxonomy
245/// (protocol/capability/input errors).
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct AdapterMisuse {
248    /// Monotone per-adapter sequence number (shared with accepted events).
249    pub seq: u64,
250    /// Host-chosen correlation id.
251    pub adapter_id: String,
252    /// Adapter flavor.
253    pub kind: AdapterKind,
254    /// Stable dotted misuse code.
255    pub code: &'static str,
256    /// Action that was rejected.
257    pub action: &'static str,
258    /// Phase the adapter was in.
259    pub phase: AdapterPhase,
260    /// Human-readable explanation with the recommended fix.
261    pub explanation: &'static str,
262}
263
264impl AdapterMisuse {
265    /// All stable misuse codes (sorted), for contract tests.
266    pub const CODES: [&'static str; 5] = [
267        "adapter.already_attached",
268        "adapter.disposed",
269        "adapter.double_mount",
270        "adapter.not_attached",
271        "adapter.not_mounted",
272    ];
273
274    /// Deterministic single-line JSON for the error timeline.
275    #[must_use]
276    pub fn to_jsonl(&self) -> String {
277        format!(
278            "{{\"event\":\"adapter_misuse\",\"schema\":\"{}\",\"seq\":{},\"adapter_id\":\"{}\",\"adapter\":\"{}\",\"code\":\"{}\",\"action\":\"{}\",\"phase\":\"{}\",\"explanation\":\"{}\"}}",
279            ADAPTER_SCHEMA_VERSION,
280            self.seq,
281            escape_json(&self.adapter_id),
282            self.kind.as_str(),
283            self.code,
284            self.action,
285            self.phase.as_str(),
286            escape_json(self.explanation),
287        )
288    }
289}
290
291fn escape_json(text: &str) -> String {
292    let mut out = String::with_capacity(text.len());
293    for ch in text.chars() {
294        match ch {
295            '"' => out.push_str("\\\""),
296            '\\' => out.push_str("\\\\"),
297            '\n' => out.push_str("\\n"),
298            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
299            c => out.push(c),
300        }
301    }
302    out
303}
304
305// ============================================================================
306// The lifecycle state machine
307// ============================================================================
308
309/// Deterministic adapter lifecycle model.
310#[derive(Debug, Clone)]
311pub struct AdapterLifecycle {
312    kind: AdapterKind,
313    adapter_id: String,
314    phase: AdapterPhase,
315    seq: u64,
316}
317
318impl AdapterLifecycle {
319    /// Create a fresh adapter in [`AdapterPhase::Created`].
320    #[must_use]
321    pub fn new(kind: AdapterKind, adapter_id: impl Into<String>) -> Self {
322        Self {
323            kind,
324            adapter_id: adapter_id.into(),
325            phase: AdapterPhase::Created,
326            seq: 0,
327        }
328    }
329
330    /// Current phase.
331    #[must_use]
332    pub const fn phase(&self) -> AdapterPhase {
333        self.phase
334    }
335
336    /// Adapter flavor.
337    #[must_use]
338    pub const fn kind(&self) -> AdapterKind {
339        self.kind
340    }
341
342    /// Apply a host action, returning the transition event or the misuse.
343    ///
344    /// # Errors
345    ///
346    /// Returns [`AdapterMisuse`] when the action is illegal in the current
347    /// phase for this adapter kind. React deduplicates StrictMode-style
348    /// repeats of idempotent steps (mount when mounted, detach when detached,
349    /// dispose when disposed); vanilla reports them as misuse.
350    pub fn apply(&mut self, action: &AdapterAction) -> Result<AdapterEvent, AdapterMisuse> {
351        self.seq += 1;
352        let phase_before = self.phase;
353        let react = self.kind == AdapterKind::React;
354
355        let decided: Result<(AdapterPhase, AdapterOutcome), (&'static str, &'static str)> =
356            match (action, self.phase) {
357                // ── Mount ────────────────────────────────────────────
358                (AdapterAction::Mount, AdapterPhase::Created) => {
359                    Ok((AdapterPhase::Mounted, AdapterOutcome::Applied))
360                }
361                // Detached still has an INITIALIZED engine (attachClose only
362                // closed the transport), so a second `init` is a double
363                // mount, not a re-mount: React dedups it (mount already
364                // satisfied, phase unchanged), vanilla reports misuse.
365                (AdapterAction::Mount, AdapterPhase::Mounted | AdapterPhase::Detached) if react => {
366                    Ok((self.phase, AdapterOutcome::StrictModeDeduped))
367                }
368                (
369                    AdapterAction::Mount,
370                    AdapterPhase::Mounted | AdapterPhase::Attached | AdapterPhase::Detached,
371                ) => Err((
372                    "adapter.double_mount",
373                    "init was already called for this container; vanilla hosts must dispose \
374                     before re-mounting (React hosts get StrictMode dedup instead)",
375                )),
376                // ── Attach ───────────────────────────────────────────
377                (AdapterAction::Attach, AdapterPhase::Mounted | AdapterPhase::Detached) => {
378                    Ok((AdapterPhase::Attached, AdapterOutcome::Applied))
379                }
380                (AdapterAction::Attach, AdapterPhase::Attached) if react => {
381                    Ok((AdapterPhase::Attached, AdapterOutcome::StrictModeDeduped))
382                }
383                (AdapterAction::Attach, AdapterPhase::Attached) => Err((
384                    "adapter.already_attached",
385                    "attachConnect was already called; call attachClose before reconnecting",
386                )),
387                (AdapterAction::Attach, AdapterPhase::Created) => Err((
388                    "adapter.not_mounted",
389                    "call init (mount) before attachConnect: the engine must exist before \
390                     the transport",
391                )),
392                // ── Resize ───────────────────────────────────────────
393                // Legal from Mounted onward: fitToContainer/resize commonly
394                // run between init and attachConnect.
395                (
396                    AdapterAction::Resize { .. },
397                    AdapterPhase::Mounted | AdapterPhase::Attached | AdapterPhase::Detached,
398                ) => Ok((self.phase, AdapterOutcome::Applied)),
399                (AdapterAction::Resize { .. }, AdapterPhase::Created) => Err((
400                    "adapter.not_mounted",
401                    "resize requires an initialized engine; call init first",
402                )),
403                // ── Input ────────────────────────────────────────────
404                (AdapterAction::Input { .. }, AdapterPhase::Attached) => {
405                    Ok((AdapterPhase::Attached, AdapterOutcome::Applied))
406                }
407                (
408                    AdapterAction::Input { .. },
409                    AdapterPhase::Created | AdapterPhase::Mounted | AdapterPhase::Detached,
410                ) => Err((
411                    "adapter.not_attached",
412                    "input requires a connected transport; call attachConnect first",
413                )),
414                // ── Detach ───────────────────────────────────────────
415                (AdapterAction::Detach, AdapterPhase::Attached) => {
416                    Ok((AdapterPhase::Detached, AdapterOutcome::Applied))
417                }
418                (AdapterAction::Detach, AdapterPhase::Detached | AdapterPhase::Mounted)
419                    if react =>
420                {
421                    Ok((self.phase, AdapterOutcome::StrictModeDeduped))
422                }
423                (
424                    AdapterAction::Detach,
425                    AdapterPhase::Created | AdapterPhase::Mounted | AdapterPhase::Detached,
426                ) => Err((
427                    "adapter.not_attached",
428                    "attachClose requires a connected transport",
429                )),
430                // ── Dispose ──────────────────────────────────────────
431                // Teardown must be reachable from every live phase.
432                (AdapterAction::Dispose, AdapterPhase::Disposed) if react => {
433                    Ok((AdapterPhase::Disposed, AdapterOutcome::StrictModeDeduped))
434                }
435                (AdapterAction::Dispose, AdapterPhase::Disposed) => Err((
436                    "adapter.disposed",
437                    "destroy was already called; create a new adapter instead of reusing \
438                     a disposed one",
439                )),
440                (AdapterAction::Dispose, _) => {
441                    Ok((AdapterPhase::Disposed, AdapterOutcome::Applied))
442                }
443                // ── Anything on a disposed adapter ───────────────────
444                (_, AdapterPhase::Disposed) => Err((
445                    "adapter.disposed",
446                    "the adapter was destroyed; create a new adapter instead of reusing \
447                     a disposed one",
448                )),
449            };
450
451        match decided {
452            Ok((phase_after, outcome)) => {
453                self.phase = phase_after;
454                Ok(AdapterEvent {
455                    seq: self.seq,
456                    adapter_id: self.adapter_id.clone(),
457                    kind: self.kind,
458                    action: action.label(),
459                    phase_before,
460                    phase_after,
461                    outcome,
462                    detail: action.detail(),
463                })
464            }
465            Err((code, explanation)) => Err(AdapterMisuse {
466                seq: self.seq,
467                adapter_id: self.adapter_id.clone(),
468                kind: self.kind,
469                code,
470                action: action.label(),
471                phase: phase_before,
472                explanation,
473            }),
474        }
475    }
476}
477
478// ============================================================================
479// Recommended wiring
480// ============================================================================
481
482/// One ordered wiring step for an adapter integration.
483#[derive(Debug, Clone, PartialEq, Eq)]
484pub struct WiringStep {
485    /// 1-based order.
486    pub step: u8,
487    /// Stable contract method (or `"-"` for host-side-only steps).
488    pub method: &'static str,
489    /// What the step does and why it sits at this position.
490    pub note: &'static str,
491}
492
493/// The recommended, ordered wiring for each adapter kind, naming the real
494/// stable contract methods. This is the executable form of the "framework
495/// wiring" section in the migration guide.
496#[must_use]
497pub fn recommended_wiring(kind: AdapterKind) -> Vec<WiringStep> {
498    let mut steps = Vec::new();
499    let mut order = 0u8;
500    let mut push = |method: &'static str, note: &'static str| {
501        order += 1;
502        steps.push(WiringStep {
503            step: order,
504            method,
505            note,
506        });
507    };
508
509    if kind == AdapterKind::React {
510        push(
511            "-",
512            "mark the component `'use client'` and guard on `typeof window` so Next.js \
513             never runs engine code during SSR",
514        );
515    }
516    push(
517        "apiContract",
518        "pin the contract: verify apiLine and a `1.` apiVersion before any other call",
519    );
520    push(
521        "init",
522        "initialize the engine into the container element (the Mount action)",
523    );
524    push(
525        "fitToContainer",
526        "size the grid to the container before first paint; wire a ResizeObserver to \
527         keep it sized (fitToContainer again, or resize(cols, rows) when the host \
528         computes the grid itself)",
529    );
530    push(
531        "attachConnect",
532        "connect the transport only after init succeeded (the Attach action)",
533    );
534    push(
535        "input",
536        "forward host-encoded input; input is only legal while attached",
537    );
538    push(
539        "drainEventSubscriptionJsonl",
540        "drain typed events on the host's schedule (drain-driven, not push-driven)",
541    );
542    push(
543        "attachClose",
544        "teardown step 1: close the transport (the Detach action)",
545    );
546    push(
547        "destroy",
548        "teardown step 2: destroy the engine (the Dispose action); React cleanup runs \
549         this in the effect destructor and StrictMode may run it twice — the adapter \
550         dedups the repeat",
551    );
552    steps
553}
554
555// ============================================================================
556// Canonical examples (lockstep with crates/ftui-web/sdk/examples/)
557// ============================================================================
558
559/// Canonical vanilla-DOM adapter example. The committed
560/// `sdk/examples/frankenterm-adapter-vanilla.js` must equal this exactly.
561#[must_use]
562pub fn vanilla_example() -> String {
563    VANILLA_EXAMPLE.to_string()
564}
565
566/// Canonical React/Next adapter example. The committed
567/// `sdk/examples/frankenterm-adapter-react.tsx` must equal this exactly.
568#[must_use]
569pub fn react_example() -> String {
570    REACT_EXAMPLE.to_string()
571}
572
573const VANILLA_EXAMPLE: &str = r#"// FrankenTermJS first-party vanilla adapter (bd-2vr05.9.3).
574// Lifecycle contract: mount -> attach -> resize/input -> detach -> dispose.
575// Generated in lockstep with ftui-web's sdk_adapter model; do not hand-edit.
576
577export function createFrankenTermAdapter(FrankenTermWeb, container, transportUrl) {
578  // Step 1: pin the contract before any other call.
579  const contract = FrankenTermWeb.apiContract();
580  if (contract.apiLine !== "frankenterm-js" || !String(contract.apiVersion).startsWith("1.")) {
581    throw new Error(`unsupported FrankenTermWeb contract: ${contract.apiVersion}`);
582  }
583
584  // Step 2 (Mount): initialize the engine into the container.
585  const term = FrankenTermWeb.init(container);
586
587  // Step 3: size to the container now, then keep sizing on changes.
588  term.fitToContainer();
589  const resizeObserver = new ResizeObserver(() => term.fitToContainer());
590  resizeObserver.observe(container);
591
592  // Step 4 (Attach): connect the transport only after init succeeded.
593  term.attachConnect(transportUrl);
594
595  // Step 5: forward host input (legal only while attached).
596  const onKeyDown = (domEvent) => term.input(domEvent);
597  container.addEventListener("keydown", onKeyDown);
598
599  // Step 6: drain typed events on the host's schedule (drain-driven).
600  const drainTimer = setInterval(() => {
601    for (const line of term.drainEventSubscriptionJsonl()) {
602      handleTerminalEvent(JSON.parse(line));
603    }
604  }, 16);
605
606  // Teardown order matters: detach the transport, then destroy the engine.
607  // Vanilla hosts must call dispose() exactly once.
608  return {
609    term,
610    dispose() {
611      clearInterval(drainTimer);
612      container.removeEventListener("keydown", onKeyDown);
613      resizeObserver.disconnect();
614      term.attachClose(); // Detach
615      term.destroy(); // Dispose
616    },
617  };
618}
619
620function handleTerminalEvent(event) {
621  // Route by the typed taxonomy from sdk/frankenterm-js-events.d.ts.
622  console.debug("frankenterm event", event.type, event);
623}
624"#;
625
626const REACT_EXAMPLE: &str = r#"// FrankenTermJS first-party React adapter — also the Next.js wiring
627// (bd-2vr05.9.3). Lifecycle contract: mount -> attach -> resize/input ->
628// detach -> dispose, driven from a single effect. React StrictMode runs
629// setup -> cleanup -> setup in development; because the cleanup below fully
630// tears down the engine, the second setup starts from a clean container.
631// (The adapter model additionally dedups repeated idempotent steps for
632// hosts that keep one adapter instance across effect runs.)
633// Generated in lockstep with ftui-web's sdk_adapter model; do not hand-edit.
634"use client";
635
636import { useEffect, useRef } from "react";
637
638export function FrankenTerm({ FrankenTermWeb, transportUrl, onEvent }) {
639  const containerRef = useRef(null);
640
641  useEffect(() => {
642    // Next.js SSR guard: engine code is browser-only.
643    if (typeof window === "undefined" || !containerRef.current) {
644      return undefined;
645    }
646    const container = containerRef.current;
647
648    // Step 1: pin the contract before any other call.
649    const contract = FrankenTermWeb.apiContract();
650    if (contract.apiLine !== "frankenterm-js" || !String(contract.apiVersion).startsWith("1.")) {
651      throw new Error(`unsupported FrankenTermWeb contract: ${contract.apiVersion}`);
652    }
653
654    // Step 2 (Mount): initialize the engine into the container.
655    const term = FrankenTermWeb.init(container);
656
657    // Step 3: size to the container now, then keep sizing on changes.
658    term.fitToContainer();
659    const resizeObserver = new ResizeObserver(() => term.fitToContainer());
660    resizeObserver.observe(container);
661
662    // Step 4 (Attach): connect the transport only after init succeeded.
663    term.attachConnect(transportUrl);
664
665    // Step 5: forward host input (legal only while attached).
666    const onKeyDown = (domEvent) => term.input(domEvent);
667    container.addEventListener("keydown", onKeyDown);
668
669    // Step 6: drain typed events on the host's schedule (drain-driven).
670    const drainTimer = setInterval(() => {
671      for (const line of term.drainEventSubscriptionJsonl()) {
672        onEvent?.(JSON.parse(line));
673      }
674    }, 16);
675
676    // Effect cleanup IS the teardown: detach, then destroy. StrictMode runs
677    // cleanup between its two dev-mode setups, so each setup gets a fresh
678    // engine; the adapter model dedups repeats defensively.
679    return () => {
680      clearInterval(drainTimer);
681      container.removeEventListener("keydown", onKeyDown);
682      resizeObserver.disconnect();
683      term.attachClose(); // Detach
684      term.destroy(); // Dispose
685    };
686  }, [FrankenTermWeb, transportUrl, onEvent]);
687
688  return <div ref={containerRef} style={{ width: "100%", height: "100%" }} />;
689}
690"#;
691
692// ============================================================================
693// Tests
694// ============================================================================
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699
700    fn lifecycle(kind: AdapterKind) -> AdapterLifecycle {
701        AdapterLifecycle::new(kind, "term-1")
702    }
703
704    #[test]
705    fn happy_path_reaches_disposed_for_both_kinds() {
706        for kind in AdapterKind::ALL {
707            let mut adapter = lifecycle(kind);
708            for action in [
709                AdapterAction::Mount,
710                AdapterAction::Resize { cols: 80, rows: 24 },
711                AdapterAction::Attach,
712                AdapterAction::Input { bytes: 3 },
713                AdapterAction::Resize {
714                    cols: 100,
715                    rows: 30,
716                },
717                AdapterAction::Detach,
718                AdapterAction::Dispose,
719            ] {
720                let event = adapter
721                    .apply(&action)
722                    .unwrap_or_else(|m| panic!("{kind}: {} rejected: {}", action.label(), m.code));
723                assert_eq!(event.outcome, AdapterOutcome::Applied);
724            }
725            assert_eq!(adapter.phase(), AdapterPhase::Disposed);
726        }
727    }
728
729    #[test]
730    fn react_strict_mode_double_mount_and_double_cleanup_are_deduped() {
731        let mut adapter = lifecycle(AdapterKind::React);
732        assert_eq!(
733            adapter.apply(&AdapterAction::Mount).expect("mount").outcome,
734            AdapterOutcome::Applied
735        );
736        // StrictMode re-runs the effect body.
737        assert_eq!(
738            adapter
739                .apply(&AdapterAction::Mount)
740                .expect("strict remount")
741                .outcome,
742            AdapterOutcome::StrictModeDeduped
743        );
744        adapter.apply(&AdapterAction::Attach).expect("attach");
745        assert_eq!(
746            adapter
747                .apply(&AdapterAction::Attach)
748                .expect("strict reattach")
749                .outcome,
750            AdapterOutcome::StrictModeDeduped
751        );
752        adapter.apply(&AdapterAction::Detach).expect("detach");
753        // StrictMode re-runs the cleanup.
754        assert_eq!(
755            adapter
756                .apply(&AdapterAction::Detach)
757                .expect("strict re-detach")
758                .outcome,
759            AdapterOutcome::StrictModeDeduped
760        );
761        adapter.apply(&AdapterAction::Dispose).expect("dispose");
762        assert_eq!(
763            adapter
764                .apply(&AdapterAction::Dispose)
765                .expect("strict re-dispose")
766                .outcome,
767            AdapterOutcome::StrictModeDeduped
768        );
769        assert_eq!(adapter.phase(), AdapterPhase::Disposed);
770    }
771
772    #[test]
773    fn vanilla_rejects_the_same_repeats_react_dedups() {
774        let mut adapter = lifecycle(AdapterKind::Vanilla);
775        adapter.apply(&AdapterAction::Mount).expect("mount");
776        let misuse = adapter
777            .apply(&AdapterAction::Mount)
778            .expect_err("double mount");
779        assert_eq!(misuse.code, "adapter.double_mount");
780
781        adapter.apply(&AdapterAction::Attach).expect("attach");
782        let misuse = adapter
783            .apply(&AdapterAction::Attach)
784            .expect_err("double attach");
785        assert_eq!(misuse.code, "adapter.already_attached");
786
787        adapter.apply(&AdapterAction::Detach).expect("detach");
788        adapter.apply(&AdapterAction::Dispose).expect("dispose");
789        let misuse = adapter
790            .apply(&AdapterAction::Dispose)
791            .expect_err("double dispose");
792        assert_eq!(misuse.code, "adapter.disposed");
793    }
794
795    #[test]
796    fn ordering_violations_are_named_misuse() {
797        // Attach before mount.
798        let mut adapter = lifecycle(AdapterKind::Vanilla);
799        assert_eq!(
800            adapter
801                .apply(&AdapterAction::Attach)
802                .expect_err("no mount")
803                .code,
804            "adapter.not_mounted"
805        );
806        // Input before attach.
807        adapter.apply(&AdapterAction::Mount).expect("mount");
808        assert_eq!(
809            adapter
810                .apply(&AdapterAction::Input { bytes: 1 })
811                .expect_err("no attach")
812                .code,
813            "adapter.not_attached"
814        );
815        // Resize before mount.
816        let mut fresh = lifecycle(AdapterKind::React);
817        assert_eq!(
818            fresh
819                .apply(&AdapterAction::Resize { cols: 1, rows: 1 })
820                .expect_err("no mount")
821                .code,
822            "adapter.not_mounted"
823        );
824        // Anything after dispose (React dedups only dispose itself).
825        let mut disposed = lifecycle(AdapterKind::React);
826        disposed.apply(&AdapterAction::Mount).expect("mount");
827        disposed.apply(&AdapterAction::Dispose).expect("dispose");
828        assert_eq!(
829            disposed
830                .apply(&AdapterAction::Mount)
831                .expect_err("mount after dispose")
832                .code,
833            "adapter.disposed"
834        );
835    }
836
837    #[test]
838    fn dispose_is_reachable_from_every_live_phase() {
839        for kind in AdapterKind::ALL {
840            // From Created.
841            let mut a = lifecycle(kind);
842            a.apply(&AdapterAction::Dispose)
843                .expect("dispose from created");
844            // From Mounted.
845            let mut b = lifecycle(kind);
846            b.apply(&AdapterAction::Mount).expect("mount");
847            b.apply(&AdapterAction::Dispose)
848                .expect("dispose from mounted");
849            // From Attached.
850            let mut c = lifecycle(kind);
851            c.apply(&AdapterAction::Mount).expect("mount");
852            c.apply(&AdapterAction::Attach).expect("attach");
853            c.apply(&AdapterAction::Dispose)
854                .expect("dispose from attached");
855        }
856    }
857
858    #[test]
859    fn mount_while_detached_is_a_double_mount_not_a_remount() {
860        // Detached keeps the engine initialized; a second init must never be
861        // silently accepted as a fresh mount.
862        let mut vanilla = lifecycle(AdapterKind::Vanilla);
863        vanilla.apply(&AdapterAction::Mount).expect("mount");
864        vanilla.apply(&AdapterAction::Attach).expect("attach");
865        vanilla.apply(&AdapterAction::Detach).expect("detach");
866        let misuse = vanilla
867            .apply(&AdapterAction::Mount)
868            .expect_err("init on a detached-but-initialized engine");
869        assert_eq!(misuse.code, "adapter.double_mount");
870        assert_eq!(vanilla.phase(), AdapterPhase::Detached, "phase unchanged");
871
872        let mut react = lifecycle(AdapterKind::React);
873        react.apply(&AdapterAction::Mount).expect("mount");
874        react.apply(&AdapterAction::Attach).expect("attach");
875        react.apply(&AdapterAction::Detach).expect("detach");
876        let event = react
877            .apply(&AdapterAction::Mount)
878            .expect("react dedups the repeat");
879        assert_eq!(event.outcome, AdapterOutcome::StrictModeDeduped);
880        assert_eq!(react.phase(), AdapterPhase::Detached, "dedup keeps phase");
881    }
882
883    #[test]
884    fn remount_after_detach_supports_reconnect_flows() {
885        let mut adapter = lifecycle(AdapterKind::Vanilla);
886        adapter.apply(&AdapterAction::Mount).expect("mount");
887        adapter.apply(&AdapterAction::Attach).expect("attach");
888        adapter.apply(&AdapterAction::Detach).expect("detach");
889        // Reconnect without re-initializing the engine.
890        adapter.apply(&AdapterAction::Attach).expect("re-attach");
891        assert_eq!(adapter.phase(), AdapterPhase::Attached);
892    }
893
894    #[test]
895    fn jsonl_lines_are_deterministic_and_carry_correlation() {
896        let run = || -> Vec<String> {
897            let mut adapter = AdapterLifecycle::new(AdapterKind::React, "corr-7");
898            let mut lines = Vec::new();
899            for action in [
900                AdapterAction::Mount,
901                AdapterAction::Attach,
902                AdapterAction::Input { bytes: 5 },
903                AdapterAction::Dispose,
904            ] {
905                lines.push(adapter.apply(&action).expect("apply").to_jsonl());
906            }
907            lines.push(
908                adapter
909                    .apply(&AdapterAction::Attach)
910                    .expect_err("attach after dispose")
911                    .to_jsonl(),
912            );
913            lines
914        };
915        let a = run();
916        let b = run();
917        assert_eq!(a, b, "identical action sequences must log byte-identically");
918        for line in &a {
919            let parsed: serde_json::Value =
920                serde_json::from_str(line).expect("adapter JSONL parses");
921            assert_eq!(parsed["adapter_id"].as_str(), Some("corr-7"));
922            assert_eq!(parsed["schema"].as_str(), Some(ADAPTER_SCHEMA_VERSION));
923            assert!(parsed["seq"].as_u64().is_some());
924        }
925        // seq is monotone across accepted AND rejected actions.
926        let seqs: Vec<u64> = a
927            .iter()
928            .map(|l| {
929                serde_json::from_str::<serde_json::Value>(l).expect("parses")["seq"]
930                    .as_u64()
931                    .expect("seq")
932            })
933            .collect();
934        assert!(seqs.windows(2).all(|w| w[1] == w[0] + 1));
935    }
936
937    #[test]
938    fn misuse_codes_are_stable_sorted_and_exercised() {
939        let mut sorted = AdapterMisuse::CODES;
940        sorted.sort_unstable();
941        assert_eq!(sorted, AdapterMisuse::CODES, "codes must stay sorted");
942    }
943
944    #[test]
945    fn wiring_references_only_stable_contract_methods() {
946        for kind in AdapterKind::ALL {
947            let wiring = recommended_wiring(kind);
948            assert!(wiring.len() >= 8, "wiring must cover the full lifecycle");
949            for step in &wiring {
950                assert!(
951                    step.method == "-" || WIRING_CONTRACT_METHODS.contains(&step.method),
952                    "wiring step {} references non-contract method `{}`",
953                    step.step,
954                    step.method
955                );
956            }
957            // Order is 1..=n with no gaps.
958            for (idx, step) in wiring.iter().enumerate() {
959                assert_eq!(usize::from(step.step), idx + 1);
960            }
961            // Teardown order: attachClose strictly before destroy.
962            let pos = |m: &str| wiring.iter().position(|s| s.method == m).expect(m);
963            assert!(pos("init") < pos("attachConnect"));
964            assert!(pos("attachConnect") < pos("attachClose"));
965            assert!(pos("attachClose") < pos("destroy"));
966        }
967        // React wiring leads with the SSR guard.
968        assert_eq!(recommended_wiring(AdapterKind::React)[0].method, "-");
969    }
970
971    #[test]
972    fn examples_embed_every_wired_contract_method() {
973        for (example, kind) in [
974            (vanilla_example(), AdapterKind::Vanilla),
975            (react_example(), AdapterKind::React),
976        ] {
977            for step in recommended_wiring(kind) {
978                if step.method != "-" {
979                    assert!(
980                        example.contains(step.method),
981                        "{kind} example is missing wired method `{}`",
982                        step.method
983                    );
984                }
985            }
986        }
987        // The React example must carry the Next.js markers.
988        let react = react_example();
989        assert!(react.contains("\"use client\""));
990        assert!(react.contains("typeof window"));
991        assert!(react.contains("StrictMode"));
992    }
993
994    #[test]
995    fn committed_example_files_are_in_lockstep_with_the_generators() {
996        let vanilla_committed = include_str!("../sdk/examples/frankenterm-adapter-vanilla.js");
997        assert_eq!(
998            vanilla_committed,
999            vanilla_example(),
1000            "sdk/examples/frankenterm-adapter-vanilla.js drifted from sdk_adapter::vanilla_example()"
1001        );
1002        let react_committed = include_str!("../sdk/examples/frankenterm-adapter-react.tsx");
1003        assert_eq!(
1004            react_committed,
1005            react_example(),
1006            "sdk/examples/frankenterm-adapter-react.tsx drifted from sdk_adapter::react_example()"
1007        );
1008    }
1009}