# HomuraJS: The Directed Acyclic Graph (DAG) State & History Engine for JavaScript > Full Technical Specification, Architecture, Ecosystem Guides, WordPress & Zero-JS Integrations, and API Reference. > Engineered by Biagio Scaglia & the HomuraJS Core Team. > Version: 1.5.1 (production-hardened) > Documentation: https://biagio-scaglia.github.io/homura-js/ > Source Repository: https://github.com/biagio-scaglia/homura-js > Package Registry: https://www.npmjs.com/package/@biagioscaglia/homurajs --- ## 1. Executive Summary & Core Philosophy HomuraJS is an advanced, framework-agnostic state management and history engine designed to solve the fundamental flaw of traditional undo/redo implementations: **the destructive linear stack problem**. In conventional state libraries (e.g., Redux-Undo, simple undo arrays, browser history), history is modeled as a 1D linear array with a single active pointer. When a user steps back $N$ times and performs a new mutation, all future steps ahead of the pointer are permanently deleted. HomuraJS models application history as a **Directed Acyclic Graph (DAG)** of immutable state snapshots: - Every mutation creates a new node in the graph with parent and child links. - Rewinding to an earlier state and applying a change creates an **alternative timeline branch** without erasing any existing timeline. - Branches can be switched, compared, inspected, and merged via 3-way or fast-forward reconciliation. - Published snapshots are **deep-frozen**; accidental mutation of `getState()` throws instead of corrupting history. - `update(..., { silent: true })` applies in-place without a history node; `setStateAsync` awaits Promise middleware. - Memory usage is minimized using **Copy-On-Write structural sharing** via JavaScript Proxies. --- ## 2. Monorepo Package Anatomy HomuraJS is structured as a high-performance monorepo: ### `@homura-js/core` (< 5.2 kB gzipped) The zero-dependency core engine: - Graph node registry and DAG traversal algorithms (ancestors, descendants, branch heads). - Copy-On-Write draft proxy engine for intuitive mutable syntax (`update(draft => { draft.x = 1; })`). - Deep-frozen published snapshots (`deepFreeze`); draft creation is safe against frozen bases. - Silent updates (`silent: true`) and async middleware via `setStateAsync` / `MiddlewarePipeline.runAsync`. - Deep recursive structural diff engine (`diff(nodeA, nodeB)`); array removals apply high→low indexes. - Snapshot registry and milestone bookmarking. - Persistence adapters (LocalStorage, SessionStorage, IndexedDB, Custom); persistence errors rethrow (auto-save catches locally). - Event emitter (`state:change`, `node:add`, `branch:create`, `branch:switch`, `branch:merge`, `undo`, `redo`); cancelled transactions do not emit `transaction:commit`. - History compaction and topology-safe prune (`compact()`, `prune()`). - Step-by-step automated timeline playback (`replay()`). - Fast-forward and manual merge with required resolver when conflicts exist. ### `@homura-js/devtools` (< 9.4 kB gzipped) Standalone diagnostic UI and scrubber: - Interactive visual DAG timeline graph with zoom, pan, branch tags, and jump-to-node. - Real-time collapsible JSON state inspector. - Side-by-side recursive structural diff viewer with color-coded additions, deletions, and modifications. - Step-by-step timeline playback controls with speed multiplier (1x, 2x, 5x, 10x). - Floating and embedded mounting modes (`mountDevTools()`). ### `@homura-js/vanilla` (< 2.8 kB gzipped) Framework-free reactive DOM and form crash recovery: - `bindState(homura, targets)`: One-way reactive DOM binding without virtual DOM. - `bindForm(formElement, options)`: Form crash protection controller with undo/redo, smart recovery banner, and integrity verification. - `autoInitForms()`: Auto-discovers and initializes all declarative `[data-homura-form]` elements. - Utility functions: `extractFormData(form)`, `populateFormData(form, state)`, `isFieldSensitive(el)`, `maskPIIValue(key, val)`. - Smart Recovery: Visual state diff between DOM and saved drafts (`getDiffFromDom()`). - Sensitive Field Policy: Auto-filters passwords, CVVs, nonces, and `data-homura-sensitive="true"`. - AJAX Conflict Protection: `verifyIntegrityAndRestore()` detects and repairs fields wiped by asynchronous updates. - Handles multi-step form wizards (`data-homura-step`, `data-homura-next`, `data-homura-prev`). ### `@homura-js/react` (< 2.1 kB gzipped) React 18+ bindings: - `useHomura(store, selector?, equalityFn?)` hook powered by React 18's `useSyncExternalStore`. - Fine-grained selector optimization preventing unnecessary component re-renders. - Provides `state`, `update`, `undo`, `redo`, `canUndo`, `canRedo`, `createBranch`, `switchBranch`. ### `@homura-js/vue` (< 2.3 kB gzipped) Vue 3 Composition API bindings: - `useHomura(store)` hook returning shallow reactive state and time-travel controls. - Vue plugin wrapper for global store injection. ### `@biagioscaglia/homurajs` (Meta-Package & CDN) - Unified package exporting all modules. - CDN standalone browser bundle (`dist/index.global.js`) for static HTML, WordPress, Shopify, Squarespace, and Webflow. --- ## 3. WordPress & WooCommerce Integration (Deep Dive) HomuraJS provides an official WordPress plugin (`homura-time-travel-form-recovery`) designed for high-conversion sites, lead generation, and checkout crash protection. ### Key Capabilities in WordPress: 1. **Crash Recovery for Forms**: Automatically saves user input to browser LocalStorage as a local DAG state tree. If a customer accidentally closes a tab or experiences a page refresh, their data is instantly restored. 2. **Shortcodes for Page Builders & Themes**: - `[homura_form id="contact_quote" persist="localstorage"] ... [/homura_form]` - `[homura_undo form="contact_quote" label="Undo"]` - `[homura_redo form="contact_quote" label="Redo"]` - `[homura_status form="contact_quote"]` - `[homura_breadcrumbs form="contact_quote"]` 3. **Auto-Hooks for Popular WordPress Form & E-Commerce Plugins**: - **WooCommerce Checkout**: Auto-attaches to `.woocommerce-checkout` to protect customer shipping, billing, and order notes from accidental checkout abandonment. - **Contact Form 7**: Auto-attaches to `.wpcf7 form`. - **WPForms**: Auto-attaches to `.wpforms-form`. - **Gravity Forms**: Auto-attaches to `.gform_wrapper form`. - **Elementor Forms**: Auto-attaches to `.elementor-form`. 4. **Privacy & GDPR Compliance**: - 100% client-side operation. - Zero telemetry, zero external tracking, and zero remote script execution. - Data stored exclusively in the visitor's local browser sandbox. --- ## 4. Zero-JS Declarative HTML API (Static Sites & Headless CMS) Any static website (Webflow, Squarespace, Shopify, Astro, Hugo, 11ty, Plain HTML) can use HomuraJS without writing JavaScript: ### Single Form Crash Recovery & Time-Travel ```html
``` ### Multi-Step Questionnaire Wizard ```html

Step 1: Company Profile

Step 2: Technical Scope

``` --- ## 5. WordPress & WooCommerce Plugin Integration (v1.5.1) Official WordPress.org Plugin: `homura-time-travel-form-recovery` (https://wordpress.org/plugins/homura-time-travel-form-recovery/) ### Capabilities & Architecture: - **Zero-Data-Loss Form Protection**: Real-time client-side DAG state tracking in LocalStorage / SessionStorage. - **Real QR Mobile Handoff**: Scannable QR via `uqr`; oversized tokens fall back to copy-link UX (`[homura_handoff]`). - **Ghost Assist & AES-GCM Vault**: Sensory mass-delete recovery and optional WebCrypto encryption. - **WooCommerce AJAX Conflict Recovery**: Restores fields wiped by `update_order_review` / cart recalculation; destroy cleans MutationObservers and jQuery hooks. - **State Diff Engine (`[homura_diff]`)**: Visual modal comparison between current form DOM values and saved drafts. - **Smart Recovery Banner (`[homura_recovery_banner]`)**: Interactive prompt allowing visitors to restore drafts, inspect differences, or dismiss previous sessions. - **Sensitive Field Policy**: Strict exclusion of passwords, CVVs, credit card numbers, payment nonces, and inputs tagged with `data-homura-sensitive="true"` or `data-homura-persist="false"` (GDPR and PCI-DSS compliant). - **Form Schema Versioning**: Prevents corruption when forms are updated or fields are modified by site administrators. - **PII-Masked Debug Export (`[homura_debug_export]`)**: Sanitized JSON diagnostic payload for troubleshooting. ### Complete Shortcodes: - `[homura_form id="form_id" persist="localstorage" debounce="200" smart_recovery="true"]...[/homura_form]` - `[homura_undo form="form_id" label="↩ Undo"]` - `[homura_redo form="form_id" label="↪ Redo"]` - `[homura_status form="form_id"]` - `[homura_breadcrumbs form="form_id"]` - `[homura_recovery_banner form="form_id"]` - `[homura_diff form="form_id" label="🔍 View Changes"]` - `[homura_handoff form="form_id"]` - `[homura_ghost_assist form="form_id"]` - `[homura_visual_diff form="form_id"]` - `[homura_clear form="form_id" label="🗑️ Clear Draft"]` - `[homura_reset form="form_id" label="🗑️ Reset"]` - `[homura_debug_export form="form_id" label="🛠️ Export Debug JSON"]` - `[homura_wizard id="wizard_id" persist="localstorage"]` ### Auto-Hooked Form Engines: WooCommerce Checkout (`.woocommerce-checkout`), Contact Form 7 (`.wpcf7 form`), WPForms (`.wpforms-form`), Gravity Forms (`.gform_wrapper`), Elementor Forms (`.elementor-form`), Fluent Forms (`.fluentform`), Ninja Forms (`.nf-form-content form`), Formidable Forms (`.frm-show-form`), and WS Form (`.wsf-form`). --- ## 6. TypeScript / JavaScript API Reference ### Core Type Definitions ```ts export interface HistoryEntry { id: string; // UUIDv4 node identifier parentId: string | null; // Ancestor node ID childrenIds: string[]; // Divergent branch child node IDs branchId: string; // Active timeline branch name timestamp: number; // Unix epoch ms label: string; // Human-readable action description state: T; // Immutable frozen state snapshot metadata?: Record; } export interface Branch { id: string; name: string; headEntryId: string; createdAt: number; } export interface Snapshot { id: string; name: string; entryId: string; state: T; timestamp: number; } export interface DiffChange { type: 'added' | 'removed' | 'modified'; path: string; oldValue?: unknown; newValue?: unknown; } ``` ### Core Instance Methods - `getState(): T`: Returns current immutable frozen snapshot. - `update(updater: (draft: T) => void, options?: { label?: string; metadata?: Record }): HistoryEntry`: Applies mutation via draft proxy. - `undo(): HistoryEntry | null`: Rewinds active pointer to parent node. - `redo(): HistoryEntry | null`: Advances active pointer to child node. - `canUndo(): boolean`: Returns true if parent exists. - `canRedo(): boolean`: Returns true if child exists on active branch. - `createBranch(name: string, fromEntryId?: string): Branch`: Forks new timeline. - `switchBranch(branchName: string): boolean`: Switches active timeline to branch head. - `merge(sourceBranchId: string, options?: { strategy?: 'theirs' | 'ours' | 'manual' }): HistoryEntry`: 3-way branch reconciliation. - `diff(entryA: string | HistoryEntry, entryB?: string | HistoryEntry): DiffChange[]`: Recursive dot-path diffing. - `snapshot(name?: string, metadata?: Record): Snapshot`: Milestone bookmarking. - `transaction(fn: (draft: T) => void, options?: { label?: string }): HistoryEntry`: Collapses multiple writes into one node. - `replay(options?: { speed?: number; stepDelayMs?: number; onStep?: (entry: HistoryEntry, idx: number, total: number) => void }): Promise`: Automated playback. - `compact(options?: { keepSnapshots?: boolean; maxEntries?: number }): void`: Prunes linear nodes while preserving branch junctions. --- ## 6. Competitive Comparison Matrix | Feature | HomuraJS | Redux-Undo | Zustand History | XState | Immer (Standalone) | | :--- | :--- | :--- | :--- | :--- | :--- | | **History Topology** | **DAG (Non-destructive)** | 1D Linear Stack (Destructive) | 1D Linear Stack | Finite State Machine | None (Draft only) | | **Branch Divergence** | **Yes (Infinite branches)** | No (Discarded on mutation) | No | State transitions only | No | | **Zero-JS Form Recovery** | **Built-in (`bindForm`)** | None | None | None | None | | **WordPress Plugin** | **Official Plugin & Shortcodes** | None | None | None | None | | **Structural Diffing** | **Recursive dot-path diff** | None | None | None | None | | **Embedded DevTools GUI** | **Built-in visual DAG tree** | External extension | None | External visualizer | None | | **Bundle Size** | **< 5.2 kB gzip** | ~4 kB | ~3 kB | ~15 kB | ~6 kB | | **Dependencies** | **Zero** | Redux required | Zustand required | Zero | Zero | --- ## 7. Performance Benchmarks Tested on Chromium v130 (10,000 DAG Nodes, nested 500-key objects): - **Node Mutation (Proxy Commit)**: ~185,000 operations/second (`0.005 ms` average latency). - **Timeline Jump (Rewind/Fast-Forward)**: ~420,000 operations/second (`0.002 ms` average latency). - **Deep Structural Diffing**: ~95,000 operations/second (`0.010 ms` average latency). - **State Serialization**: ~45,000 operations/second (`0.022 ms` average latency). --- ## 8. Frequently Asked Questions (FAQ) ### Q1: How does HomuraJS prevent memory leaks when working with large DAG graphs? HomuraJS implements Copy-On-Write structural sharing. If only a single property of a 10,000-property object is updated, the new node references the unmodified subtrees in memory. Additionally, `compact()` and `pruneHistory()` allow pruning intermediate linear steps while preserving named snapshots and branch junction points. ### Q2: Can HomuraJS be used in non-React applications? Yes. `@homura-js/core` is 100% framework-agnostic. It works out-of-the-box in Vanilla JS, Node.js, Vue 3, Svelte, Solid, Angular, WordPress, Webflow, Shopify, and static HTML. ### Q3: How does HomuraJS integrate with WooCommerce and WordPress? The official WordPress plugin automatically hooks into `.woocommerce-checkout`, `.wpcf7 form`, `.wpforms-form`, `.gform_wrapper`, and `.elementor-form`. It stores form input in LocalStorage without any code or configuration required.