# ๐Ÿงพ FX Framework - Enhanced AI Cheat Sheet ## ๐ŸŽฏ MEMORIZE FIRST: Core Concepts ### **Everything is a Node** ```typescript $$("path.to.anything") // Creates/accesses node at path // Paths auto-create hierarchy: app โ†’ user โ†’ profile โ†’ name ``` ### **Reactive vs Snapshot (CRITICAL)** ```typescript $$("a").val($$("b")) // โœ… REACTIVE - auto-updates when b changes $$("a").val($$("b").get()) // โŒ SNAPSHOT - one-time copy only ``` ### **Synchronous API Surface** ```typescript const user = $db.users.find("#42"); // Feels instant (uses SAB+Worker) const data = $$("@/api/users").get(); // Feels instant (uses Worker bridge) $flow("process").start("node", data); // Feels instant (cross-realm execution) ``` --- ## ๐Ÿ”ง Essential Syntax (Copy These Patterns) ### **Basic Node Operations** ```typescript $$("app.user.name").set("John"); // Create/set value $$("app.user.name").get() // Get value $$("app.user.name").watch((n,o) => {}) // Watch changes $$("app.user").as(User) // Type-safe class unwrap $$("app.user").node() // Get raw FX node ``` ### **Module Loading (No Await)** ```typescript const Utils = $$("@./utils.ts"); // Default export $$("@./math.ts").sum(1, 2); // Named exports $$("app.auth@./auth.ts").options({ // Attach to node type: "auth", global: "$auth" }); ``` ### **CSS-Style Queries** ```typescript $$("app").select(".user[active=true]") // Find active users $$("modules").select(".function[exported=true]") // Find exported functions $$("logs").select(".error:limit(10)") // Last 10 errors ``` ### **Reactive Groups** ```typescript const group = $$("collections.users").group([]) .include(".user[active=true]") // Auto-include criteria .exclude(".user[banned=true]") // Auto-exclude criteria .reactive(true); // Updates automatically group.length // Count group.sum() // Aggregate operations group.on("change", () => updateUI()) // React to changes ``` --- ## ๐Ÿ”Œ Plugin Quick Reference & Selection Guide ### **๐ŸŽฏ DOM & UI Layer** #### **fx-dom-dollar** - jQuery-like DOM with Reactive Binding **Choose When:** Frontend UI, DOM manipulation, form handling, user interaction **Provides:** `$()` function for DOM selection and manipulation ```typescript $$("plugins.dom@./plugins/fx-dom-dollar.ts"); $("#username").text($$("app.user.name")); // Reactive text binding $("#saveBtn").on("click", () => saveUserData()); // Event handling $(".cards").addClass("highlighted"); // Bulk operations $("#form input").val($$("form.data")); // Form data binding ``` **AI Use Case:** Perfect for any project involving user interfaces, forms, or DOM manipulation. #### **fx-router** - Page Routing & Navigation **Choose When:** Multi-page apps, SPAs, navigation flows **Provides:** `$router` for page routing and lifecycle management ```typescript $router.route("/users/:id", { component: "./UserProfile.ts", guards: ["authenticated"] }); ``` **AI Use Case:** Essential for applications with multiple pages or complex navigation. #### **fx-components** - Declarative Component System **Choose When:** Reusable UI components, complex interfaces **Provides:** `.fxc` component files with templates and reactive binding **AI Use Case:** Use for applications requiring modular, reusable UI components. --- ### **๐Ÿ—„๏ธ Data & Database Layer** #### **fx-orm** - "Mainnet-Zero Leak" Database Operations **Choose When:** ANY database operations, data persistence, real-time apps **Provides:** `$db` with CSS-like query syntax and zero-latency operations ```typescript $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); const users = $db.users.where("[age>=21][status=active]"); // CSS-like queries const user = $db.users.find("#42"); // ID lookup const newId = $db.users.create({name: "John"}); // Create record // Reactive models - direct mutation saves automatically! user.name = "Updated"; // Auto-saves to database (debounced) user.email = "new@example.com"; // Batched with above ``` **AI Use Case:** ESSENTIAL for any project involving data storage, user management, content systems, analytics, or persistence. #### **fx-cache** - Multi-tier Performance Caching **Choose When:** Performance optimization, expensive operations, API responses **Provides:** `$cache` with Memory โ†’ IndexedDB โ†’ ServiceWorker tiers ```typescript $$("plugins.cache@./plugins/fx-cache.ts").options({ global: "$cache" }); const result = await $cache.getOrSet("expensive-calc", () => { return performHeavyComputation(); }, { ttl: 5 * 60 * 1000 }); ``` **AI Use Case:** Use for apps with expensive computations, API calls, or performance requirements. --- ### **๐Ÿ”„ Flow Control & Logic** #### **fx-flow** - Cross-Realm Procedure Graphs **Choose When:** Complex workflows, multi-step processes, business logic, async coordination **Provides:** `$flow` for dynamic procedure graphs with client/server execution ```typescript $$("plugins.flow@./plugins/fx-flow.ts").options({ global: "$flow" }); $flow("userOnboarding") .node("validate", { runsOn: "client", effect: (ctx) => validate(ctx.in) }) .node("save", { runsOn: "server", effect: (ctx) => $db.users.create(ctx.in) }) .node("notify", { runsOn: "both", effect: (ctx) => sendWelcome(ctx.in) }) .connect("validate", "save", "notify") .start("validate", formData); ``` **AI Use Case:** CRITICAL for complex applications with business logic, API orchestration, data pipelines, or multi-step processes. --- ### **๐Ÿ›ก๏ธ Safety & Reliability System** #### **fx-safe** - Production Resilience Patterns **Choose When:** External APIs, unreliable services, production systems **Provides:** `$safe` with circuit breakers, retries, timeouts ```typescript $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); const apiResult = $safe.circuit("payment-api").execute(() => { return processPayment(orderData); // Protected by circuit breaker }); const retryResult = await $safe.retry("flaky-service", () => { return callExternalAPI(); }, { maxAttempts: 3, backoffMs: 1000 }); ``` **AI Use Case:** ESSENTIAL for production applications, external integrations, or systems requiring high reliability. #### **fx-time-travel** - State Debugging & Recovery **Choose When:** Complex state changes, debugging, experimentation **Provides:** `$time` for state snapshots and rollback capabilities ```typescript $$("plugins.timeTravel@./plugins/fx-time-travel.ts").options({ global: "$time" }); const checkpoint = $time.snapshot("Before risky operation"); // Perform risky state changes... if (operationFailed) { $time.restore(checkpoint.id); // Complete state rollback } ``` **AI Use Case:** Use for development tools, testing frameworks, or applications with complex state management. #### **fx-atomics** - Coordinated State Updates **Choose When:** Multiple related data changes, consistency requirements **Provides:** `$atomics` for node entanglement and atomic operations ```typescript $$("plugins.atomics@./plugins/fx-atomics.ts").options({ global: "$atomics" }); $atomics.entangle("user.data", "ui.display", { bidirectional: true, mapAtoB: (user) => ({name: user.name, avatar: user.avatar}) }); // When user.data changes, ui.display updates automatically with mapping ``` **AI Use Case:** Use for applications requiring coordinated state updates or complex data synchronization. --- ### **๐Ÿ’พ Data Persistence & Sharing** #### **fx-serialize** - Complete State Persistence **Choose When:** Save/load functionality, state export/import, session persistence **Provides:** `$serialize` for complete application state serialization ```typescript $$("plugins.serialize@./plugins/fx-serialize.ts").options({ global: "$serialize" }); const appState = $serialize.wrap($$("app").node()); // Serialize everything $serialize.expand(savedState, $$("app").node()); // Restore everything ``` **AI Use Case:** Use for applications requiring save/load, data migration, or session persistence. #### **fx-filesystem** - Server File System Integration **Choose When:** Server applications, file-based workflows, inter-process sharing **Provides:** Real-time FX node โ†’ file mirroring (server only) ```typescript $$("plugins.filesystem@./plugins/fx-filesystem.ts").options({ global: "$filesystem" }); $$("project.config").set({theme: "dark"}); // Auto-creates: /tmp/fx-nodes/project/config/value.fxval // Edit file โ†’ FX node updates automatically ``` **AI Use Case:** Use for server applications, development tools, or systems requiring file system integration. --- ### **๐Ÿ”ง Development & Debugging Tools** #### **fx-visualizer** - Live Node Graph Visualization **Choose When:** Debugging complex node structures, understanding data flow **Provides:** `$visualizer` with interactive D3.js node graph ```typescript $$("plugins.visualizer@./plugins/fx-visualizer.ts").options({ global: "$visualizer" }); $visualizer.toggle(); // Ctrl+Shift+V - Show/hide graph $visualizer.show(); // Interactive visualization ``` **AI Use Case:** Use during development for debugging, learning FX, or visualizing complex data relationships. #### **fx-devtools** - Real-time Development Monitoring **Choose When:** Server development, performance optimization, debugging **Provides:** Real-time dashboard for server-side operation monitoring ```typescript // Auto-loads when FX_DEVTOOLS=true // Dashboard: /__fx-devtools // Monitors: DB queries, flow execution, performance, errors ``` **AI Use Case:** ESSENTIAL for server applications, performance-critical systems, or complex debugging scenarios. --- ## ๐ŸŽฏ Plugin Combination Strategies ### **Minimal Frontend** (2 plugins) ```typescript $$("plugins.dom@./plugins/fx-dom-dollar.ts"); // DOM manipulation $$("plugins.cache@./plugins/fx-cache.ts"); // Performance caching ``` ### **Full Frontend** (4 plugins) ```typescript $$("plugins.dom@./plugins/fx-dom-dollar.ts"); // DOM manipulation $$("plugins.router@./plugins/fx-router.ts"); // Page routing $$("plugins.components@./plugins/fx-components.ts"); // UI components $$("plugins.cache@./plugins/fx-cache.ts"); // Performance ``` ### **Backend API** (3-4 plugins) ```typescript $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); // Database $$("plugins.flow@./plugins/fx-flow.ts").options({ global: "$flow" }); // Business logic $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); // Reliability // + fx-devtools for monitoring ``` ### **Full-Stack Application** (6+ plugins) ```typescript // Frontend $$("plugins.dom@./plugins/fx-dom-dollar.ts"); $$("plugins.router@./plugins/fx-router.ts"); // Backend $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); $$("plugins.flow@./plugins/fx-flow.ts").options({ global: "$flow" }); // Safety & Performance $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); $$("plugins.cache@./plugins/fx-cache.ts").options({ global: "$cache" }); // Development $$("plugins.timeTravel@./plugins/fx-time-travel.ts").options({ global: "$time" }); // + fx-devtools + fx-visualizer ``` ### **Mission-Critical System** (All safety plugins) ```typescript $$("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 $$("plugins.serialize@./plugins/fx-serialize.ts").options({ global: "$serialize" }); // State backup // + comprehensive monitoring and logging ``` --- ## โšก AI Development Acceleration Patterns ### **Rapid Prototyping Pattern** ```typescript // 1. Load minimal plugins $$("plugins.dom@./plugins/fx-dom-dollar.ts"); // 2. Create reactive data model $$("app.data").set(initialData); // 3. Bind to UI (automatic updates) $("#output").text($$("app.data.message")); // 4. Add interactivity $("#input").on("input", () => $$("app.data.input").set($("#input").val())); // Done! Fully reactive prototype in 4 lines ``` ### **Database-Driven Application Pattern** ```typescript // 1. Load database plugin $$("plugins.orm@./plugins/fx-orm.ts").options({ global: "$db" }); // 2. Query data (feels synchronous) const users = $db.users.where("[active=true]"); // 3. Bind to UI (reactive updates) $("#userCount").text($$("app.users.active.count")); $$("app.users.active.count").val(users.length); // 4. Handle user interactions $("#addUser").on("click", () => { const newUser = $db.users.create(getFormData()); $$("app.users.active.count").set($db.users.where("[active=true]").length); }); // UI updates automatically! ``` ### **Resilient Service Integration Pattern** ```typescript // 1. Load safety plugins $$("plugins.safe@./plugins/fx-safe.ts").options({ global: "$safe" }); $$("plugins.timeTravel@./plugins/fx-time-travel.ts").options({ global: "$time" }); // 2. Create checkpoint const checkpoint = $time.snapshot("Before API integration"); // 3. Protected external call const apiResult = $safe.circuit("external-api").execute(() => { return $safe.timeout("api-call", () => { return fetch("/external-api").then(r => r.json()); }, 30000); }); // 4. Handle results with rollback if (!apiResult.success) { $time.restore(checkpoint.id); // Rollback on failure } ``` --- ## ๐Ÿšจ Critical Anti-Patterns (Avoid These) ### **โŒ Async/Await Contamination** ```typescript // DON'T DO THIS: async function loadUser(id) { const user = await $db.users.find(`#${id}`); // Unnecessary await return user; } // DO THIS: function loadUser(id) { return $db.users.find(`#${id}`); // Direct synchronous access } ``` ### **โŒ Manual UI Updates** ```typescript // DON'T DO THIS: function updateUserName(newName) { $$("app.user.name").set(newName); document.getElementById("username").textContent = newName; // Manual document.getElementById("greeting").textContent = `Hi ${newName}!`; // Manual } // DO THIS: $("#username").text($$("app.user.name")); // Set up once $("#greeting").text(`Hi ${$$("app.user.name")}!`); // Set up once $$("app.user.name").set(newName); // Everything updates automatically ``` ### **โŒ Complex State Management** ```typescript // DON'T DO THIS: let state = {users: [], loading: false}; function updateUsers(newUsers) { state.users = newUsers; state.loading = false; notifyAllListeners(); // Manual notification updateAllUIComponents(); // Manual UI updates } // DO THIS: $$("app.users").set(newUsers); // Everything connected updates automatically ``` --- ## ๐ŸŽฏ Project Type โ†’ Plugin Selection Matrix | Project Type | Essential Plugins | Optional Plugins | Why These Plugins | |--------------|------------------|------------------|-------------------| | **Simple Frontend** | fx-dom-dollar | fx-cache, fx-router | DOM manipulation + optional performance/routing | | **Complex Frontend** | fx-dom-dollar, fx-router, fx-components | fx-cache, fx-safe | Complete UI framework with reliability | | **Backend API** | fx-orm, fx-flow, fx-safe | fx-cache, fx-filesystem | Database + business logic + reliability | | **Full-Stack App** | fx-dom-dollar, fx-orm, fx-flow | fx-safe, fx-cache, fx-router | Frontend + backend + business logic | | **Real-time App** | fx-orm, fx-dom-dollar, fx-atomics | fx-flow, fx-safe | Database + UI + coordinated state | | **Data Processing** | fx-orm, fx-flow, fx-cache | fx-serialize, fx-safe | Database + pipelines + performance | | **Enterprise System** | fx-orm, fx-flow, fx-safe, fx-atomics | fx-time-travel, fx-cache | Reliability + coordination + rollback | | **Development Tool** | fx-visualizer, fx-devtools, fx-serialize | fx-time-travel, fx-filesystem | Debugging + monitoring + persistence | | **AI Collaboration** | fx-flow, fx-safe, fx-serialize | fx-time-travel, fx-cache | Orchestration + safety + state management | --- ## ๐Ÿ“‹ AI Project Analysis Checklist ### **Before Starting Any Project, Determine:** #### **Data Requirements** - [ ] Does it store/retrieve data? โ†’ **fx-orm** (essential) - [ ] Complex queries needed? โ†’ **fx-orm** with CSS selectors - [ ] Performance critical? โ†’ **fx-cache** for optimization - [ ] Need persistence? โ†’ **fx-serialize** for state management #### **User Interface Requirements** - [ ] DOM manipulation needed? โ†’ **fx-dom-dollar** (essential for UI) - [ ] Multiple pages/routes? โ†’ **fx-router** for navigation - [ ] Complex UI components? โ†’ **fx-components** for modularity - [ ] Form handling? โ†’ **fx-dom-dollar** handles all form types #### **Business Logic Complexity** - [ ] Multi-step processes? โ†’ **fx-flow** for orchestration - [ ] Cross-system integration? โ†’ **fx-flow** + **fx-safe** for reliability - [ ] Complex decision trees? โ†’ **fx-flow** with branching logic - [ ] Background processing? โ†’ **fx-flow** with server-side execution #### **Reliability Requirements** - [ ] External API calls? โ†’ **fx-safe** circuit breakers (essential) - [ ] Critical data changes? โ†’ **fx-time-travel** for rollback - [ ] Coordinated updates? โ†’ **fx-atomics** for consistency - [ ] Production deployment? โ†’ Full safety stack required #### **Development Environment** - [ ] Complex debugging needed? โ†’ **fx-visualizer** for node exploration - [ ] Server monitoring? โ†’ **fx-devtools** for real-time insights - [ ] Team collaboration? โ†’ **fx-serialize** for state sharing - [ ] File-based workflows? โ†’ **fx-filesystem** (server only) --- ## ๐Ÿš€ Success Patterns for AI Code Generation ### **1. Start with Node Structure** ```typescript // Define your data model as FX nodes first $$("app.users").set([]); $$("app.currentUser").set(null); $$("app.ui.theme").set("dark"); $$("app.config").set(defaultConfig); ``` ### **2. Add Reactive Bindings** ```typescript // Connect data to UI reactively $("#userCount").text($$("app.users.length")); $("#currentUser").text($$("app.currentUser.name")); $("#themeToggle").attr("checked", $$("app.ui.theme").get() === "dark"); ``` ### **3. Handle User Interactions** ```typescript // Capture user input and update FX nodes $("#userForm").on("submit", (e) => { e.preventDefault(); const userData = getFormData(); const userId = $db.users.create(userData); $$("app.currentUser").set($db.users.find(`#${userId}`)); // UI updates automatically via reactive bindings! }); ``` ### **4. Add Business Logic** ```typescript // Use flows for complex processes $flow("userRegistration") .node("validate", { runsOn: "client", effect: validateInput }) .node("checkDuplicate", { runsOn: "server", effect: checkExistingUser }) .node("createUser", { runsOn: "server", effect: createUserRecord }) .node("sendWelcome", { runsOn: "both", effect: sendWelcomeMessage }) .connect("validate", "checkDuplicate", "createUser", "sendWelcome"); ``` --- ## ๐ŸŽŠ Why AIs Excel with FX ### **1. Consistent Mental Model** - Everything is a node with a path - All operations follow same patterns - Reactive updates are automatic - No context switching between async/sync ### **2. Predictable Behavior** - Nodes always behave the same way - Plugins follow consistent patterns - Error handling is built-in - Performance is optimized automatically ### **3. Composable Architecture** - Plugins work together seamlessly - Each plugin has clear responsibilities - Integration patterns are consistent - Scaling is straightforward ### **4. Immediate Feedback** - Changes are visible instantly - Debugging tools show node relationships - Performance monitoring is built-in - Error tracking provides clear context --- ## ๐ŸŽฏ **KEY TAKEAWAY FOR AIs:** **FX transforms complex application development into simple node manipulation with automatic reactivity. Choose plugins based on project requirements, think in terms of reactive node graphs, and let FX handle the complexity of synchronization, performance, and reliability.** **The result: Clean, maintainable code that feels magical to users and developers alike!** โœจ