Files
modules/state-crdts/hyper-p2p-crdt-rga-text/docs/api.md
T
2026-05-20 23:36:32 -04:00

89 lines
2.5 KiB
Markdown

# API: hyper-p2p-crdt-rga-text
**Protocol:** `crdt-rga-text/v1`
**Export:** `{ HyperP2PCrdtRgaText, PROTOCOL }`
## Overview
`HyperP2PCrdtRgaText` stores characters in `_nodes` keyed by `charId` with tombstone `deleted`. Visible order is `_order` filtered to non-deleted nodes. `insert(index, charId, char)` places a character at a visible index; `delete(charId)` tombstones. `toString()` renders visible characters in order.
## Constructor
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `topic` | `string` \| `Buffer` \| `null` | `null` | Hyperswarm topic |
| `keyPair` | `KeyPair` | `hypercore-crypto.keyPair()` | Swarm identity |
## Methods
### `insert(index, charId, char)`
- **Parameters:**
- `index` — visible index (0-based); clamped to `visible.length`
- `charId` — stable string id per character
- `char` — single character string (required, non-empty)
- **Returns:** `string` — normalized `charId`
- **Throws:**
- `Error: index must be non-negative`
- `ValidationError: charId is required`
- `Error: char required`
- **Gossip:** `op: 'insert'` with resolved `index`
### `delete(charId)`
- **Returns:** `boolean``false` if already deleted or unknown
- **Throws:** `ValidationError: charId is required`
- **Gossip:** `op: 'delete'`
### `toString()`
- **Returns:** concatenation of visible chars in order
### `async ready()` / `async close()`
Standard gossip lifecycle.
### `getStats()`
| Field | Type | Description |
|-------|------|-------------|
| `ops` | `number` | insert/delete applied locally |
| `gossipIn` / `gossipOut` | `number` | Wire counters |
| `length` | `number` | `toString().length` |
| `protocol` | `string` | `crdt-rga-text/v1` |
## Events
None emitted.
## getStats()
Includes live `length`.
## Wire
| type | fields | direction | behavior |
|------|--------|-----------|----------|
| `crdt-rga-text-sync` | `op: 'insert'` | bidirectional | `_applyInsert(index, charId, char, false)` |
| `crdt-rga-text-sync` | `op: 'delete'`, `charId` | bidirectional | `_applyDelete(charId, false)` |
Insert payload: `charId`, `char`, `index` (sender's resolved index).
## Errors
| Message | Source |
|---------|--------|
| `index must be non-negative` | `insert` |
| `char required` | `insert` |
| `charId is required` | `insert` / `delete` |
## Testing
```bash
cd modules/state-crdts/hyper-p2p-crdt-rga-text
npm install && npm test
```
Concurrent inserts at same index rely on `charId` stability; tests should use unique ids per peer.