Architecture Overview
Relevant source files
The following files were used as context for generating this wiki page:
The @b2m9/keyfold library is a specialized utility designed to immutably fold partial deltas into plain state trees. It distinguishes itself from standard JSON Merge Patch implementations by providing identity-keyed list reconciliation, ensuring that arrays of objects are updated based on unique identifiers rather than simple index-based replacement.
The architecture is built on three core pillars: path-based policy compilation, recursive object merging, and identity-aware list reconciliation. It adheres to strict design principles including zero runtime dependencies, structural sharing for unchanged subtrees, and deterministic results.
Sources: README.md:3-15, AGENTS.md:12-25
Core System Components
The library's logic is distributed across several specialized modules that separate configuration validation, object traversal, and list operations.
| Component | Responsibility | Relevant Files |
|---|---|---|
| Merger Factory | Entry point that compiles options and returns a reusable merge function. | src/merge.ts, src/index.ts |
| Policy Compiler | Validates and transforms keyBy and replace paths into a searchable policy tree. | src/paths.ts |
| Recursive Folder | Handles the traversal of deltas and bases, applying field-level merges and deletions. | src/merge.ts |
| List Reconciler | Implements identity-keyed reconciliation for arrays, handling updates, inserts, and tombstones. | src/reconcile.ts |
| Object Utilities | Provides safe object manipulation, prototype protection, and enumerable key filtering. | src/objects.ts |
Sources: src/merge.ts:13-25, src/paths.ts:28-35, src/reconcile.ts:17-25, src/objects.ts:7-14
Data Flow and Execution Model
The system operates in two distinct phases: Configuration (Compile-time) and Execution (Merge-time).
Phase 1: Configuration Compilation
When createMerger is invoked, the library compiles the provided MergeOptions into a PolicyNode tree. This tree efficiently maps dot-separated path strings to specific behaviors (e.g., which field to use as an identity key or whether a path should be replaced wholesale).
The compiler ensures that policies do not overlap in contradictory ways, such as defining a keyBy policy inside a path already marked for replace.
Sources: src/paths.ts:28-85, AGENTS.md:27-29
Phase 2: Recursive Merging
The execution phase uses the compiled policy tree to guide the recursive folding of a delta into a base.
Sources: src/merge.ts:38-66, src/reconcile.ts:17-45
Keyed List Reconciliation
Reconciliation is the primary feature of Keyfold. Unlike standard merging which might overwrite arrays by index, the reconciler uses a unique identity field (e.g., id or sku) to match items.
- Indexing: The delta is indexed into a
Mapof patches by identity key. - Base Traversal: The base list is iterated. If a match is found in the patch map, the item is folded or deleted (if a tombstone is present).
- Order Preservation: Survivors from the base list retain their original relative order.
- Appending: Any patches in the delta that did not match an existing base item are appended as new inserts.
Sources: src/reconcile.ts:17-64, README.md:120-135
Reconciliation Logic Flow
The reconciler ensures that if no changes occur, the original base reference is returned to support efficient equality checks.
Sources: src/reconcile.ts:27-58, AGENTS.md:15-18
Safety and Invariants
The architecture enforces several runtime guards to maintain state integrity:
- Prototype Protection: The recursive fold ignores unsafe keys such as
__proto__,constructor, andprototypefrom deltas to prevent prototype pollution. - Atomic Boundaries: Certain types (e.g.,
Date,Map,Set,RegExp, and customAtomictypes) are treated as opaque and are replaced wholesale rather than merged. - Tombstone Strictness: A keyed-item tombstone (
$delete: true) must not contain any other patch fields; otherwise, the system throws aKeyfoldMergeError. - Immutability: The library never mutates the
baseordelta. Every operation creates shallow copies of only the affected branches.
Sources: src/objects.ts:7-14, src/reconcile.ts:114-125, AGENTS.md:12-25, src/types.ts:60-75
Error Handling
Keyfold uses specific error classes to distinguish between configuration and runtime data issues:
KeyfoldConfigError: Thrown duringcreateMergerif path strings are malformed or policies are unreachable.KeyfoldMergeError: Thrown during the merge process if data violates identity uniqueness, tombstone schemas, or type expectations (e.g., a keyed list landing on a non-array value).
Sources: src/errors.ts:1-10, src/paths.ts:30-40, src/reconcile.ts:33-35
Conclusion
The Keyfold architecture provides a predictable, performance-oriented approach to state management by treating deltas as authoritative updates. By combining a pre-compiled policy tree with a reference-preserving recursive merge strategy, it achieves high efficiency (O(delta)) while ensuring structural integrity and deep-merging capabilities for complex, keyed data structures.
Sources: README.md:150-165, AGENTS.md:30-33