import type { ImmutableTree, } from "../immutable-tree.js"; import type { Node, } from "../node.js"; import type { ExportNode, } from "./types.js"; /** * Exporter exports nodes from an ImmutableTree in depth-first post-order (LRN). * This order must be preserved when importing to recreate the same tree structure. * * Based on Go IAVL export.go lines 28-99. * * Usage: * ```typescript * const exporter = tree.export(); * for await (const node of exporter) { * // Process exported node * } * ``` */ export class Exporter { private tree: ImmutableTree; constructor(tree: ImmutableTree) { if (!tree) { throw new Error("tree is nil: iavl/export newExporter failed to create"); } // Empty tree is allowed - it just exports no nodes this.tree = tree; } /** * Returns an async iterator that yields exported nodes in post-order (LRN). * Nodes are exported depth-first post-order, which means: * - Left child nodes are exported before right child nodes * - Child nodes are exported before parent nodes * * This order is required for import to work correctly. * * Based on Go export.go lines 62-80. */ async* [Symbol.asyncIterator](): AsyncIterableIterator { const root = this.tree.getRoot(); if (!root) { return; } // Collect nodes in post-order (LRN) during traversal const nodes: ExportNode[] = []; await root.traversePost(this.tree.ndb, true, (node: Node) => { // Export this node const exportNode: ExportNode = { key: node.key || new Uint8Array(0), value: node.value || new Uint8Array(0), version: node.nodeKey?.version || 0n, height: node.subtreeHeight, }; nodes.push(exportNode); return false; // continue traversal }); // Yield all collected nodes for (const node of nodes) { yield node; } } /** * Alternative API compatible with Go's Next() pattern. * Returns the next exported node, or null when done. * * Note: Prefer using `for await (const node of exporter)` instead. */ private iterator: AsyncIterator | null = null; async next(): Promise { if (!this.iterator) { this.iterator = this[Symbol.asyncIterator](); } const result = await this.iterator.next(); if (result.done) { return null; } return result.value; } }