1use core::fmt;
42
43pub const ADAPTER_SCHEMA_VERSION: &str = "1.0.0";
45
46pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum AdapterKind {
67 Vanilla,
69 React,
73}
74
75impl AdapterKind {
76 pub const ALL: [AdapterKind; 2] = [AdapterKind::Vanilla, AdapterKind::React];
78
79 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
101pub enum AdapterPhase {
102 Created,
104 Mounted,
106 Attached,
108 Detached,
110 Disposed,
112}
113
114impl AdapterPhase {
115 #[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#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum AdapterAction {
131 Mount,
133 Attach,
135 Resize {
137 cols: u16,
139 rows: u16,
141 },
142 Input {
144 bytes: u32,
146 },
147 Detach,
149 Dispose,
151}
152
153impl AdapterAction {
154 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum AdapterOutcome {
183 Applied,
185 StrictModeDeduped,
188}
189
190impl AdapterOutcome {
191 #[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#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct AdapterEvent {
204 pub seq: u64,
206 pub adapter_id: String,
208 pub kind: AdapterKind,
210 pub action: &'static str,
212 pub phase_before: AdapterPhase,
214 pub phase_after: AdapterPhase,
216 pub outcome: AdapterOutcome,
218 pub detail: String,
220}
221
222impl AdapterEvent {
223 #[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#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct AdapterMisuse {
248 pub seq: u64,
250 pub adapter_id: String,
252 pub kind: AdapterKind,
254 pub code: &'static str,
256 pub action: &'static str,
258 pub phase: AdapterPhase,
260 pub explanation: &'static str,
262}
263
264impl AdapterMisuse {
265 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 #[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#[derive(Debug, Clone)]
311pub struct AdapterLifecycle {
312 kind: AdapterKind,
313 adapter_id: String,
314 phase: AdapterPhase,
315 seq: u64,
316}
317
318impl AdapterLifecycle {
319 #[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 #[must_use]
332 pub const fn phase(&self) -> AdapterPhase {
333 self.phase
334 }
335
336 #[must_use]
338 pub const fn kind(&self) -> AdapterKind {
339 self.kind
340 }
341
342 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 (AdapterAction::Mount, AdapterPhase::Created) => {
359 Ok((AdapterPhase::Mounted, AdapterOutcome::Applied))
360 }
361 (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 (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 (
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 (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 (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 (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 (_, 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#[derive(Debug, Clone, PartialEq, Eq)]
484pub struct WiringStep {
485 pub step: u8,
487 pub method: &'static str,
489 pub note: &'static str,
491}
492
493#[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#[must_use]
562pub fn vanilla_example() -> String {
563 VANILLA_EXAMPLE.to_string()
564}
565
566#[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#[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 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 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 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 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 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 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 let mut a = lifecycle(kind);
842 a.apply(&AdapterAction::Dispose)
843 .expect("dispose from created");
844 let mut b = lifecycle(kind);
846 b.apply(&AdapterAction::Mount).expect("mount");
847 b.apply(&AdapterAction::Dispose)
848 .expect("dispose from mounted");
849 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 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 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 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 for (idx, step) in wiring.iter().enumerate() {
959 assert_eq!(usize::from(step.step), idx + 1);
960 }
961 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 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 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}