# ๐Ÿค– FX Framework - Complete AI Onboarding Guide ## ๐ŸŽฏ CRITICAL CONCEPT: Everything is a Node **STOP**: Before proceeding, understand this fundamental truth: > **In FX, EVERYTHING is a node in a reactive graph. Files, data, functions, DOM elements, database records, API responses - ALL nodes with paths like `$$("app.user.profile.name")`** This is not just a data structure - it's a **complete programming paradigm** where: - **Changing any node** automatically updates everything connected to it - **No manual synchronization** is ever needed - **Everything feels synchronous** even when crossing realms (client โ†” server) --- ## ๐Ÿง  Essential Mental Models (Memorize These) ### 1. **Node Paths = File System Paths** ```typescript $$("app.user.profile.name") // Like app/user/profile/name $$("session.auth.token") // Like session/auth/token $$("cache.api.users") // Like cache/api/users // Auto-creates nested structure: $$("deep.nested.path").set("value"); // Creates: deep โ†’ nested โ†’ path ``` ### 2. **Reactive vs Snapshot (CRITICAL DIFFERENCE)** ```typescript // โœ… REACTIVE - Updates automatically forever $$("output").val($$("source")); // Pass the node proxy // โŒ SNAPSHOT - One-time value copy $$("output").val($$("source").get()); // Pass current value only // When source changes: // Reactive: output updates automatically โœ… // Snapshot: output stays old value โŒ ``` ### 3. **The $ vs $$ Distinction** ```typescript // $$ = FX node operations (core framework) $$("app.user").set({name: "John"}); // FX node manipulation // $ = DOM operations (fx-dom-dollar plugin) $("#username").text($$("app.user.name")); // DOM manipulation + reactive binding // They work together: $("#output").text($$("data")); // DOM shows FX data reactively ``` ### 4. **Synchronous APIs for Async Operations** ```typescript // These LOOK synchronous but use async optimizations under the hood: const user = $db.users.find("#42"); // Database query (feels instant) const data = $$("@/api/users").get(); // API call (feels instant) $flow("process").start("validate", data); // Cross-realm execution (feels instant) // NO await needed - FX handles async complexity internally ``` --- ## ๐Ÿ›  Core API Patterns (Know These Cold) ### **Node Manipulation (The Foundation)** ```typescript // Create/access nodes (auto-creates hierarchy) $$("app.user.profile").set({name: "John", email: "john@example.com"}); // Get values (multiple ways) $$("app.user.name").get() // Simple value $$("app.user.name").val() // Raw value with metadata $$("app.user.name").str() // String representation // Watch for changes (reactive programming) $$("app.user.name").watch((newName, oldName) => { console.log(`User renamed: ${oldName} โ†’ ${newName}`); }); // Type-safe unwrapping (for class instances) class User { constructor(public name: string) {} } $$("app.currentUser").val(new User("John")); const user = $$("app.currentUser").as(User); // Returns User instance or null ``` ### **Module Loading (No Async/Await)** ```typescript // Synchronous module loading (uses Worker + SharedArrayBuffer) const UserClass = $$("@./models/User.ts"); // Loads immediately const utils = $$("@./utils/helpers.ts"); // All exports available // Attach modules to nodes $$("services.auth@./auth/AuthService.ts").options({ type: "auth", global: "$auth" }); // Now available as: $$("services.auth").login("user", "pass"); // Method from module $auth.login("user", "pass"); // Global reference ``` ### **CSS-Style Selectors (Query Anything)** ```typescript // Query nodes like CSS selectors const activeUsers = $$("app").select(".user[active=true]"); const functions = $$("modules").select(".function[exported=true]"); const errors = $$("logs").select(".error[level=critical]"); // Groups are reactive collections const userGroup = $$("collections.users").group([]) .include(".user[active=true]") // Auto-include active users .exclude(".user[banned=true]") // Exclude banned users .reactive(true); // Updates automatically // Group operations console.log(userGroup.length); // Count userGroup.forEach(user => user.notify()); // Iterate ``` --- ## ๐Ÿ”Œ Plugin Ecosystem - Choose Your Tools ### **๐ŸŽฏ DOM & UI Manipulation** #### **fx-dom-dollar (`$`) - jQuery-like DOM with Reactive Binding** **Use When:** Need DOM manipulation, form handling, UI updates **Best For:** Frontend development, user interfaces, reactive UIs ```typescript // Load plugin $$("plugins.dom@./plugins/fx-dom-dollar.ts"); // jQuery-like syntax with reactive binding $("#username").text($$("app.user.name")); // DOM updates when name changes $("#status").css("color", $$("app.theme.primary")); // Event handling with FX integration $("#saveBtn").on("click", () => { $$("user.data").set(getFormData()); // Save to FX node }); // Automatic form binding $("#userForm input").each((input) => { const fieldName = input.name; // Two-way binding: DOM โ†” FX input.val($$(`form.${fieldName}`)); // FX โ†’ DOM input.on("input", () => $$(`form.${fieldName}`).set(input.val())); // DOM โ†’ FX }); ``` ### **๐Ÿ—„๏ธ Database Operations** #### **fx-orm (`$db`) - "Mainnet-Zero Leak" Database** **Use When:** Any database operations, data persistence, queries **Best For:** Backend APIs, data-driven apps, real-time applications ```typescript // Load plugin $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); // CSS-like database queries (NO await needed!) const users = $db.users.where("[age>=21][status=active]"); const user = $db.users.find("#42"); const newId = $db.users.create({name: "John", email: "john@example.com"}); // Reactive models - direct mutation triggers auto-save! user.name = "Updated Name"; // Automatically saves to database user.email = "new@email.com"; // Batched with above (debounced) // Intent-first results - instant response, lazy data loading console.log(users.length); // Instant count console.log(users[0].name); // Triggers data load for first user ``` ### **๐Ÿ”„ Flow Control & Procedures** #### **fx-flow (`$flow`) - Cross-Realm Procedure Graphs** **Use When:** Complex workflows, multi-step processes, business logic **Best For:** APIs with multiple steps, data processing pipelines, orchestration ```typescript // Load plugin $$("plugins.flow@./plugins/fx-flow.ts").options({ global: "$flow" }); // Define dynamic procedure graphs $flow("userRegistration") .node("validate", { runsOn: "client", // Runs in browser effect: (ctx) => { const {email, password} = ctx.in; if (!email.includes("@")) throw new Error("Invalid email"); ctx.next("checkDuplicate", {email, password}); } }) .node("checkDuplicate", { runsOn: "server", // Runs on server effect: (ctx) => { const existing = $db.users.where(`[email="${ctx.in.email}"]`).first(); if (existing) throw new Error("Email already exists"); ctx.next("createUser", ctx.in); } }) .node("createUser", { runsOn: "both", // Runs on both client and server effect: (ctx) => { const userId = $db.users.create(ctx.in); ctx.set({userId, created: true}); // Flow automatically completes } }); // Execute flow (feels synchronous!) $flow("userRegistration").start("validate", {email: "test@example.com", password: "secret"}); ``` ### **๐Ÿ›ก๏ธ Safety & Reliability** #### **fx-safe (`$safe`) - Circuit Breakers & Resilience** **Use When:** External APIs, unreliable operations, production systems **Best For:** Robust applications, error handling, service integration ```typescript // Load plugin $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); // Circuit breaker protection const result = $safe.circuit("payment-api").execute(() => { return callPaymentAPI(orderData); }); if (result.success) { console.log("Payment processed:", result.value); } else { console.log("Payment failed:", result.error); // Circuit breaker handles retries and fallbacks } // Retry with exponential backoff const apiResult = await $safe.retry("external-api", () => { return fetch("/api/unreliable").then(r => r.json()); }, { maxAttempts: 3, backoffMs: 1000 }); ``` #### **fx-time-travel (`$time`) - State Snapshots & Debugging** **Use When:** Complex state changes, debugging, experimentation **Best For:** Development, testing, recovery scenarios ```typescript // Load plugin $$("plugins.timeTravel@./plugins/fx-time-travel.ts").options({ global: "$time" }); // Create checkpoint before risky operations const checkpoint = $time.snapshot("Before user data migration"); // Perform risky operations $$("app.users").set(migrateUserData()); $$("app.settings").set(updateSettings()); // Rollback if something goes wrong if (somethingWentWrong()) { $time.restore(checkpoint.id); // Complete state rollback console.log("State restored to checkpoint"); } // Timeline branching for experimentation $time.branch("experiment", () => { // Try different approaches in isolated timeline $$("app.algorithm").set("experimental-v2"); runTests(); }); ``` #### **fx-atomics (`$atomics`) - Coordinated State Updates** **Use When:** Multiple related state changes, consistency requirements **Best For:** Complex state management, coordinated updates ```typescript // Load plugin $$("plugins.atomics@./plugins/fx-atomics.ts").options({ global: "$atomics" }); // Entangle nodes for coordinated updates $atomics.entangle("user.profile", "ui.userDisplay", { bidirectional: true, mapAtoB: (profile) => ({displayName: profile.name, avatar: profile.avatar}) }); // When user.profile changes, ui.userDisplay updates automatically $$("user.profile").set({name: "John", avatar: "/avatars/john.jpg"}); // ui.userDisplay now shows: {displayName: "John", avatar: "/avatars/john.jpg"} ``` ### **๐Ÿ’พ Data Persistence & Caching** #### **fx-cache (`$cache`) - Multi-tier Caching** **Use When:** Expensive operations, API responses, computed data **Best For:** Performance optimization, offline capability ```typescript // Load plugin $$("plugins.cache@./plugins/fx-cache.ts").options({ global: "$cache" }); // Multi-tier caching (Memory โ†’ IndexedDB โ†’ ServiceWorker) const expensiveData = await $cache.getOrSet("complex-calculation", () => { return performExpensiveCalculation(); }, { ttl: 5 * 60 * 1000 }); // Cache for 5 minutes // Automatic cache promotion (persistent โ†’ memory when accessed) const userData = await $cache.get("user-42"); // Promotes to memory cache ``` #### **fx-serialize (`$serialize`) - Complete State Persistence** **Use When:** State snapshots, data export/import, session persistence **Best For:** Save/load functionality, debugging, data migration ```typescript // Load plugin $$("plugins.serialize@./plugins/fx-serialize.ts").options({ global: "$serialize" }); // Serialize complete application state const appSnapshot = $serialize.wrap($$("app").node(), { preserveClassInstances: true, includePrivateProps: false }); // Restore application state $serialize.expand(appSnapshot, $$("app").node()); ``` #### **fx-filesystem (`$filesystem`) - Server-Only File Mirroring** **Use When:** Server applications, inter-process sharing, file-based workflows **Best For:** Server development, shared state, file system integration ```typescript // Load plugin (server only) $$("plugins.filesystem@./plugins/fx-filesystem.ts").options({ global: "$filesystem" }); // Automatic node โ†’ file mirroring $$("project.config").set({theme: "dark", version: "1.0.0"}); // Creates: /tmp/fx-nodes/project/config/value.fxval // Bidirectional sync: edit files โ†’ updates FX nodes // Edit /tmp/fx-nodes/project/config/value.fxval โ†’ $$("project.config") updates ``` ### **๐ŸŽจ Development Experience** #### **fx-visualizer (`$visualizer`) - Live Node Graph** **Use When:** Debugging complex node structures, understanding data flow **Best For:** Development, debugging, learning FX ```typescript // Load plugin $$("plugins.visualizer@./plugins/fx-visualizer.ts").options({ global: "$visualizer" }); // Show live node graph (Ctrl+Shift+V hotkey) $visualizer.show(); // Interactive D3.js visualization $visualizer.toggle(); // Keyboard shortcut integration // Filter visualization $visualizer.filter("type", ["user", "session"]); $visualizer.filter("path", /^app\./); ``` #### **fx-devtools - Real-time Server Monitoring** **Use When:** Server development, performance optimization, debugging **Best For:** Production monitoring, development workflow ```typescript // Auto-loads when FX_DEVTOOLS=true // Provides real-time dashboard at /__fx-devtools // Monitors: // - Database query performance and results // - Flow execution with cross-realm tracking // - Node creation and value changes // - Error tracking with full context // - Performance metrics and bottlenecks ``` --- ## ๐Ÿš€ Quick Plugin Selection Guide ### **For Frontend Development:** ```typescript // Essential trio for UI applications $$("plugins.dom@./plugins/fx-dom-dollar.ts"); // DOM manipulation + reactive binding $$("plugins.router@./plugins/fx-router.ts"); // Page routing + lifecycle $$("plugins.components@./plugins/fx-components.ts"); // Component system ``` ### **For Backend APIs:** ```typescript // Essential trio for server applications $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); // Zero-latency database $$("plugins.flow@./plugins/fx-flow.ts").options({ global: "$flow" }); // Business logic flows $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); // Production reliability ``` ### **For Full-Stack Applications:** ```typescript // Complete development stack $$("plugins.dom@./plugins/fx-dom-dollar.ts"); $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); $$("plugins.flow@./plugins/fx-flow.ts").options({ global: "$flow" }); $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); $$("plugins.timeTravel@./plugins/fx-time-travel.ts").options({ global: "$time" }); $$("plugins.cache@./plugins/fx-cache.ts").options({ global: "$cache" }); ``` ### **For Data Processing:** ```typescript // Data-heavy applications $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); // Database operations $$("plugins.cache@./plugins/fx-cache.ts").options({ global: "$cache" }); // Performance caching $$("plugins.serialize@./plugins/fx-serialize.ts").options({ global: "$serialize" }); // Data persistence $$("plugins.flow@./plugins/fx-flow.ts").options({ global: "$flow" }); // Processing pipelines ``` ### **For Mission-Critical Systems:** ```typescript // Maximum reliability and safety $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); // Circuit breakers $$("plugins.timeTravel@./plugins/fx-time-travel.ts").options({ global: "$time" }); // State rollback $$("plugins.atomics@./plugins/fx-atomics.ts").options({ global: "$atomics" }); // Atomic operations // + fx-devtools for monitoring ``` --- ## โšก Revolutionary Capabilities (AI Efficiency Multipliers) ### **1. Zero Async/Await Contamination** ```typescript // Traditional frameworks force async everywhere: async function loadUser(id) { const user = await db.users.findById(id); // async const profile = await db.profiles.findByUserId(id); // async await updateUI(user, profile); // async return user; } // FX eliminates async contamination: function loadUser(id) { const user = $db.users.find(`#${id}`); // Feels synchronous! const profile = $db.profiles.find(`#${user.profileId}`); updateUI(user, profile); // No await needed return user; } ``` ### **2. Universal Reactivity Without Boilerplate** ```typescript // Traditional frameworks require complex state management: // Redux actions, reducers, selectors, useEffect, watchers, etc. // FX provides automatic reactivity: $$("app.user.name").set("John"); // Set data // Everything connected to app.user.name updates automatically: // - DOM elements displaying the name // - API calls using the name // - Other dependent computations // - UI components showing user info // NO manual updates needed! ``` ### **3. CSS-Like Everything** ```typescript // Database queries with CSS syntax $db.users.where("[age>=21][status=active]:limit(10)") // Node queries with CSS syntax $$("app").select(".user[online=true]") // Groups with CSS selectors $$("collections.items").group([]).include(".item[category=urgent]") ``` ### **4. Cross-Realm Execution** ```typescript // Flows can run on client, server, or both seamlessly $flow("dataProcessing") .node("validateInput", { runsOn: "client" }) // Browser validation .node("processData", { runsOn: "server" }) // Server processing .node("updateUI", { runsOn: "both" }) // Updates both sides .start("validateInput", userData); ``` --- ## ๐ŸŽฏ Critical Success Patterns for AIs ### **1. Always Think in Nodes** ```typescript // โŒ Don't think in variables let userName = "John"; let userEmail = "john@example.com"; // โœ… Think in node paths $$("app.user.name").set("John"); $$("app.user.email").set("john@example.com"); ``` ### **2. Leverage Reactive Binding** ```typescript // โŒ Don't manually sync UI function updateUserDisplay() { document.getElementById("name").textContent = $$("app.user.name").get(); document.getElementById("email").textContent = $$("app.user.email").get(); } // โœ… Set up reactive binding once $("#name").text($$("app.user.name")); // Auto-updates forever $("#email").text($$("app.user.email")); // Auto-updates forever ``` ### **3. Use Appropriate Plugins** ```typescript // โŒ Don't reinvent capabilities function saveToDatabase(data) { return fetch("/api/save", {method: "POST", body: JSON.stringify(data)}); } // โœ… Use fx-orm for database operations const id = $db.users.create(data); // Direct database access ``` ### **4. Think in Reactive Collections** ```typescript // โŒ Don't manually manage lists let activeUsers = []; function updateActiveUsers() { activeUsers = users.filter(u => u.active); refreshUI(activeUsers); } // โœ… Use reactive groups const activeUsers = $$("collections.activeUsers").group([]) .include(".user[active=true]") .reactive(true); // Auto-updates when any user's active status changes ``` --- ## ๐Ÿงช Validation Checklist for AI Understanding Before starting any FX project, confirm understanding: ### **โœ… Core Concepts Mastered:** - [ ] Everything is a node with a path: `$$("app.user.profile")` - [ ] Reactive binding: `$$("a").val($$("b"))` vs `$$("a").val($$("b").get())` - [ ] Synchronous APIs: No await needed for database/API/cross-realm operations - [ ] CSS selectors: Query nodes with `.user[active=true]` syntax - [ ] Plugin system: `$$("plugins.name@./path.ts").options({global: "$name"})` ### **โœ… Practical Patterns Understood:** - [ ] Node creation auto-creates hierarchy: `$$("deep.nested.path").set(value)` - [ ] Module loading with `@`: `const Utils = $$("@./utils.ts")` - [ ] Reactive groups: `$$("group").group([]).include(".selector")` - [ ] Type-safe unwrapping: `const user = $$("app.user").as(User)` - [ ] Watchers for side effects: `$$("data").watch((newVal) => sideEffect())` ### **โœ… Plugin Selection Clarity:** - [ ] DOM manipulation โ†’ fx-dom-dollar - [ ] Database operations โ†’ fx-orm - [ ] Complex workflows โ†’ fx-flow - [ ] Error resilience โ†’ fx-safe - [ ] State debugging โ†’ fx-time-travel - [ ] Performance โ†’ fx-cache - [ ] Server apps โ†’ fx-filesystem ### **โœ… Revolutionary Understanding:** - [ ] Why no async/await: SharedArrayBuffer + Atomics bridge - [ ] Why universal reactivity: Everything is connected in node graph - [ ] Why zero latency: Intent-first results + lazy hydration - [ ] Why CSS selectors: Familiar syntax for powerful queries --- ## ๐ŸŽŠ AI Efficiency Multipliers with FX ### **1. Pattern Recognition Speed** AIs quickly recognize FX patterns because: - **Consistent syntax**: Everything uses `$$("path")` - **Predictable behavior**: All plugins follow same reactive principles - **Clear mental model**: Node graph with paths like file system ### **2. Code Generation Quality** AIs generate better FX code because: - **No async complexity**: No need to track async boundaries - **Automatic reactivity**: No manual synchronization logic - **Clear plugin APIs**: Each plugin has well-defined capabilities ### **3. Problem Solving Efficiency** AIs solve problems faster with FX because: - **Everything connected**: Change one node, everything updates - **Built-in safety**: Circuit breakers and rollback built-in - **Visual debugging**: Node graph shows relationships clearly --- **๐ŸŽฏ Master these concepts and FX becomes an incredibly powerful AI development multiplier!** ๐Ÿš€