@econ-v1/app-sdk 7.6.222 → 7.6.223

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,6 +11,7 @@ TypeScript / Bun SDK for building **Node-App** plugins for the [Node](https://gi
11
11
  - `invokeCapability()` — call any capability registered with the host's capability router.
12
12
  - `publishEvent()` — publish namespaced domain events to the host event bus.
13
13
  - `host.{trace,debug,info,warn,error}` — file-backed structured logging.
14
+ - `@econ-v1/app-sdk/replica` — replicated collections: versions, epochs, tombstones and the node's pull answer for data devices keep a copy of ([below](#replicated-collections-econ-v1app-sdkreplica)).
14
15
 
15
16
  ## Quick start
16
17
 
@@ -140,6 +141,94 @@ this.route(
140
141
 
141
142
  The host already enforces `endpoint_policies` from your manifest before the request reaches the app — `route()` re-checks `request.caller.granted_permissions` as a second line of defense.
142
143
 
144
+ ## Replicated collections (`@econ-v1/app-sdk/replica`)
145
+
146
+ Change-only replication of app data (Phase 3 of the one-stack design,
147
+ `docs/superpowers/specs/2026-11-19-one-stack-phase-3-replication.md`). Declare each
148
+ collection once and tell the helper what changed; it keeps a small ledger in the
149
+ app's own database (keys, digests, versions, tombstones — never the rows) and answers
150
+ the node's pull with **nothing new**, **the changes** since the caller's version, or
151
+ a **full copy**. The app writes no versioning code. It is the twin of the Rust crate
152
+ `node-app-replica` (`sdk/replica`): the same ledger rules, the same tables (layout 2)
153
+ and the same wire bytes (checked against that crate's golden fixtures and, step by
154
+ step, against its transcripts; numbers aside, see below).
155
+
156
+ ```typescript
157
+ import { host, invokeCapability, openDatabase } from "@econ-v1/app-sdk";
158
+ import { Replica, hostInvoke } from "@econ-v1/app-sdk/replica";
159
+
160
+ const db = openDatabase(path); // the app's own database
161
+ const replica = new Replica(db, hostInvoke(invokeCapability), { tablePrefix: "message_", warn: host.warn });
162
+ const conversations = replica.collection("message.conversations.pull", {
163
+ list: () => listConversations(db).map((c) => ({ key: c.id, value: c, ord: -c.updatedAt })),
164
+ });
165
+
166
+ // providedCapabilities(): [...own, ...replica.provides()] (and capabilities.provides in manifest.json)
167
+ // handleCapability(request):
168
+ // if (replica.handles(request.capability)) payload = await replica.handle(request.capability, request.payload);
169
+ // init(): await replica.start(); // once, before the app's first write
170
+ // at a write site: conversations.changed(); // or .touch(row) / .remove(key)
171
+ ```
172
+
173
+ - **Rows**: a key (1–256 bytes, no control characters), any JSON value (≤ 65,536
174
+ bytes encoded, at most 127 containers deep — the node's JSON parser stops at 128),
175
+ an `ord` (its place in the list, |ord| ≤ 2^53 − 1, default 0) and a `part` (a
176
+ group, ≤ 128 bytes, default `""`). A row outside these limits, or one without a
177
+ string key, is refused (`replica_row_invalid:`), and a reconcile with one bad row
178
+ records nothing. A `Date` or class instance is refused: hand over plain JSON.
179
+ - **What changed**: `changed()` marks the collection dirty at once (a pull before the
180
+ reconcile still reflects the write) and reconciles the whole `list()` 50 ms after
181
+ the last call of a burst, then announces once. `touch(row)` / `remove(key)` record
182
+ one row at a write site. `reset()` starts a new epoch (at most one a minute; a held
183
+ back one is owed and never dropped). `list()` and `get()` run inside the ledger's
184
+ transaction on the same database and must not call the replica.
185
+ - **The pull**: `handle()` answers `{"e","v","s","l","a"?}` and rejects with a
186
+ `ReplicaError` whose message starts with a stable prefix, the same as the Rust
187
+ crate's: `replica_schema_unsupported:`, `replica_request_invalid:`,
188
+ `replica_row_invalid:`, `replica_load_failed:`, `replica_store_failed:`,
189
+ `replica_config_invalid:`. A dirty ledger is reconciled first, and a row whose
190
+ loaded value no longer matches the ledger is recorded before the answer is built.
191
+ - **Announces** (`core.replica.announce`) never fail the app's work. The node answers
192
+ a device that holds the head it remembers with "nothing new" without calling the
193
+ app, so until an announce lands devices do not see the change. A failed announce,
194
+ and a failed background reconcile (one `changed()` scheduled), is therefore
195
+ retried after 2 s, then 4, 8, 16, 32 and every 60 s until it succeeds or
196
+ `stop()` is called (`retry: { firstMs, maxMs }` changes the schedule;
197
+ `retrying()` tells whether one is waiting). Each failure run is reported once
198
+ through `warn`. (`CollectionLedger.announce`, the ledger underneath, is one call
199
+ and does not retry, like the Rust crate's.) When the node answers
200
+ `{"rotate":true}` (the database went back in time) the helper rotates at once and
201
+ announces again. `start()` is how a database restored while the app was stopped is
202
+ found.
203
+ - **Storage**: `Replica` takes the `Database` the app holds (`bun:sqlite`, or
204
+ `burger:sqlite` in a Burger app; the same surface) and writes in `BEGIN IMMEDIATE`,
205
+ or in a savepoint inside the app's own transaction. Give the database a busy
206
+ timeout when another connection writes it. It also takes any `LedgerStore`;
207
+ `MemoryLedger` keeps the ledger in process memory (every device takes one full copy
208
+ after each start). `CollectionLedger` is the ledger underneath, for apps that drive
209
+ it directly.
210
+ - **Digest**: FNV-1a 64 plus the byte length of the canonical JSON of
211
+ `[value, ord, part]` (no crypto module, so it runs the same under Burger). The Rust
212
+ crate uses SHA-256; the digest never leaves the app's ledger, so the two never meet.
213
+ Keep one collection's ledger to one of the two helpers: to the other, every row
214
+ would look changed.
215
+
216
+ - **Numbers** are where the bytes can differ from the Rust crate's for the same JSON
217
+ value: JavaScript has only doubles, and a number is written as `JSON.stringify`
218
+ writes it. serde_json (1.0.149, the version the workspace locks) writes a
219
+ float-typed number in its own form: `1.0` for a whole float (`1` here), `-0.0`
220
+ (`0` here: `-0` becomes `0`) and `1e+16` for a float from 10^16 up to 10^21
221
+ (`10000000000000000` here); from 10^21 both write `1e+21` (serde_json before
222
+ 1.0.149 wrote `1e21`). An integer beyond 2^53 − 1 is exact in Rust and has lost
223
+ its precision before a JavaScript app holds it. `handle()` returns the reply as an
224
+ object, and whoever serialises it again writes object keys that look like array
225
+ indexes first, in numeric order (`{"9":…,"10":…}`, where the canonical text has
226
+ `"10"` first). Nothing hashes reserialised bytes (the digest is computed from the
227
+ app's value, inside one helper), so these change no reply and no device's data.
228
+
229
+ The epoch, tombstone and paging rules, and what the node and the device must do for
230
+ the guarantees to hold, are in `sdk/replica/README.md`.
231
+
143
232
  ## Calling host capabilities
144
233
 
145
234
  ```typescript
@@ -0,0 +1,131 @@
1
+ /**
2
+ * One replicated collection's ledger: the twin of the Rust helper's
3
+ * `node_app_replica::Collection`, bound to a {@link LedgerStore}.
4
+ *
5
+ * {@link Replica} (in `../replica.ts`) is what an app uses; this class is the
6
+ * ledger underneath it, for apps and tests that drive the ledger directly.
7
+ */
8
+ import type { Head, Horizon, ReplicaEnvironment } from "./ledger.js";
9
+ import { type LedgerStore } from "./store.js";
10
+ import { type PullReply, type PullRequest, type ReplicaRow } from "./wire.js";
11
+ /** The app's door to the node's capability bus: returns the reply payload, or throws. */
12
+ export type ReplicaInvoke = (capability: string, payload: unknown) => Promise<unknown>;
13
+ /** The result of an announce. An announce never fails the app's own work. */
14
+ export type AnnounceOutcome =
15
+ /** The node took the head. */
16
+ {
17
+ kind: "accepted";
18
+ head: Head;
19
+ }
20
+ /** The node remembered a higher version in this epoch; the helper rotated and announced the new head. */
21
+ | {
22
+ kind: "rotated";
23
+ head: Head;
24
+ }
25
+ /** The node answered `rotate` again to a fresh epoch; the head stays and the next announce asks again. */
26
+ | {
27
+ kind: "rotation-deferred";
28
+ head: Head;
29
+ }
30
+ /** The announce failed. `first` is true for the first failure since the last success (or start). */
31
+ | {
32
+ kind: "failed";
33
+ error: string;
34
+ first: boolean;
35
+ };
36
+ /** A pull's answer and whether it moved the head (then announce). */
37
+ export interface Answered {
38
+ reply: PullReply;
39
+ headMoved: boolean;
40
+ }
41
+ /** The system clock and an 8-character random epoch. */
42
+ export declare const systemEnvironment: ReplicaEnvironment;
43
+ /** Options of a {@link CollectionLedger}. */
44
+ export interface CollectionLedgerOptions {
45
+ /** Names the ledger's tables: `[A-Za-z_][A-Za-z0-9_]{0,47}` or empty (default). */
46
+ tablePrefix?: string;
47
+ /** The `N`s of the `.vN` names this app serves; default `[1]`. */
48
+ schemas?: readonly number[];
49
+ /** The clock and the epoch source; default the system's. */
50
+ env?: ReplicaEnvironment;
51
+ /** The tombstone horizon; default 30 days and 5,000 per collection. */
52
+ horizon?: Horizon;
53
+ }
54
+ /** One replicated collection's ledger in a store. */
55
+ export declare class CollectionLedger {
56
+ readonly store: LedgerStore;
57
+ readonly name: string;
58
+ readonly tablePrefix: string;
59
+ readonly schemas: readonly number[];
60
+ private readonly spec;
61
+ private announceFailing;
62
+ /**
63
+ * The highest version this process has handed out (in a pull reply, or in an
64
+ * announce the node took) or heard the node has (its `rotate`), per epoch,
65
+ * most recent epoch first. A ledger that reads lower in the same epoch went
66
+ * back in time.
67
+ */
68
+ private readonly handedOutMarks;
69
+ constructor(store: LedgerStore, pullCapability: string, options?: CollectionLedgerOptions);
70
+ private check;
71
+ /** The hand-out mark of `epoch` in this process. */
72
+ private handedOut;
73
+ private noteHandedOut;
74
+ /** The ledger reads below what this process handed out in its epoch. */
75
+ private wentBack;
76
+ /**
77
+ * Runs `work` on this collection's record in one write transaction and writes
78
+ * the record back. Before the work, a database that went back in time rotates
79
+ * the epoch, and so does an owed rotation whose minute has passed; `work` is
80
+ * told whether that happened.
81
+ */
82
+ private withRecord;
83
+ /** The committed record when a read can stand for a write; `null` sends the caller to the write path. */
84
+ private readSettled;
85
+ /** Creates the ledger's tables if they do not exist. Idempotent; call it on every start. */
86
+ ensure(): void;
87
+ /**
88
+ * Whole-list mode: hand over every current row; the helper finds what
89
+ * changed. Returns the new head version when the head moved, else `null`. One
90
+ * bad row refuses the whole list.
91
+ */
92
+ reconcile(rows: readonly ReplicaRow[]): number | null;
93
+ /** Records one row written at a write site. Returns the head version. */
94
+ touch(row: ReplicaRow): number;
95
+ /** Records one row deleted at a write site. Returns the head version. */
96
+ remove(key: string): number;
97
+ /** "Something may have changed": the next pull reconciles before answering. */
98
+ markDirty(): void;
99
+ /**
100
+ * Starts a new epoch (the app's data was replaced) and marks the collection
101
+ * dirty. Returns whether it rotated now; within a minute of the last rotation
102
+ * the rotation is owed instead.
103
+ */
104
+ reset(): boolean;
105
+ /** The ledger's head: what an announce reports. A plain read unless something is due. */
106
+ head(): Head;
107
+ /**
108
+ * Answers one pull. `load` returns the app's current rows: every row for
109
+ * `null`, else the rows of the given keys (keys with no row are left out). It
110
+ * runs inside the ledger's write transaction and must not call this
111
+ * collection again.
112
+ */
113
+ answer(request: PullRequest, load: (keys: readonly string[] | null) => readonly ReplicaRow[]): Answered;
114
+ /**
115
+ * The pull capability's handler: decodes the payload (ignoring the keys the
116
+ * router stamps in), answers, and returns the reply as a JSON object whose
117
+ * `JSON.stringify` is the contract's bytes (object keys that look like array
118
+ * indexes aside: JavaScript puts those first). Errors are {@link ReplicaError}s.
119
+ */
120
+ pull(payload: unknown, load: (keys: readonly string[] | null) => readonly ReplicaRow[]): unknown;
121
+ /**
122
+ * Tells the node this collection's head (`core.replica.announce`). Call it
123
+ * after a write that moved the head and once at app start. When the node
124
+ * answers `{"rotate":true}` the helper rotates the epoch and announces again.
125
+ * Never throws.
126
+ */
127
+ announce(invoke: ReplicaInvoke): Promise<AnnounceOutcome>;
128
+ private announceInner;
129
+ /** The description for this capability's `provided_capabilities` entry. */
130
+ description(): string;
131
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Canonical JSON, UTF-8 sizes and row digests (Phase 3 spec, section 5.1).
3
+ *
4
+ * Canonical JSON is compact and writes object keys sorted by their UTF-8 bytes;
5
+ * strings are escaped as `JSON.stringify` (and `serde_json`) escape them, so the
6
+ * canonical text of a value is byte for byte what the Rust helper writes for the
7
+ * same value (numbers aside: JavaScript has only doubles, see the README), and
8
+ * its UTF-8 length is the value's encoded size.
9
+ *
10
+ * The digest is FNV-1a 64 over the UTF-8 bytes of the canonical JSON of
11
+ * `[value, ord, part]`, plus that byte length: no crypto dependency, so it runs
12
+ * the same in Bun and in Burger. (The Rust helper uses SHA-256; the digest never
13
+ * leaves the app's own ledger, so the two never meet.)
14
+ *
15
+ * Nothing here imports a platform module.
16
+ */
17
+ /**
18
+ * Orders two strings by their UTF-8 bytes (SQLite's BINARY collation, Rust's
19
+ * `str` order). UTF-16 order differs only where a surrogate (a code point above
20
+ * U+FFFF) meets a unit in U+E000…U+FFFF; the units are shifted so that
21
+ * surrogates sort last, which is code point (= UTF-8 byte) order.
22
+ */
23
+ export declare function compareUtf8(a: string, b: string): number;
24
+ /** The UTF-8 length of a string (a lone surrogate counts as U+FFFD, 3 bytes). */
25
+ export declare function utf8Length(text: string): number;
26
+ /** A surrogate without its other half: not representable in UTF-8 (or in a Rust `String`). */
27
+ export declare function hasLoneSurrogate(text: string): boolean;
28
+ /**
29
+ * The deepest a row's value may nest, counted as the device's storage counts it
30
+ * (`isWithinReplicaValueDepth` in `client/ports/src/replica.js`): the value is
31
+ * level 1 and each container adds a level for what it holds, so 127 nested
32
+ * containers are accepted and 128 refused. That is exactly what serde_json's
33
+ * default recursion limit (128) parses, so the node can read every value the
34
+ * helper serves.
35
+ */
36
+ export declare const MAX_VALUE_DEPTH = 128;
37
+ /**
38
+ * Whether `value` nests no deeper than {@link MAX_VALUE_DEPTH} levels. Walks the
39
+ * value with an explicit stack and stops at the first level past the limit, so
40
+ * a deep or cyclic value is refused without using the call stack. The same
41
+ * rule, line for line, as the device's `isWithinReplicaValueDepth`.
42
+ */
43
+ export declare function isWithinValueDepth(value: unknown): boolean;
44
+ /** The refusal of a value past {@link MAX_VALUE_DEPTH}, the same text as the Rust helper's. */
45
+ export declare const VALUE_TOO_DEEP = "value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";
46
+ /** Why a value is not JSON; thrown by the canonical writer, mapped by the caller. */
47
+ export declare class NotJsonError extends Error {
48
+ }
49
+ /**
50
+ * The canonical JSON of a value. Throws {@link NotJsonError} for anything JSON
51
+ * cannot carry exactly: `undefined` (except as an object property, which is
52
+ * left out), functions, symbols, bigints, non-finite numbers, class instances
53
+ * (a `Date` too: convert it first), strings with a lone surrogate, and values
54
+ * nested past {@link MAX_VALUE_DEPTH}.
55
+ */
56
+ export declare function canonicalJson(value: unknown): string;
57
+ /** FNV-1a 64 of the UTF-8 bytes of `text`, as 16 hex characters. */
58
+ export declare function fnv1a64(text: string): string;
59
+ /** The parts of a row the digest covers. */
60
+ export interface DigestInput {
61
+ value: unknown;
62
+ ord: number;
63
+ part: string;
64
+ }
65
+ /**
66
+ * The ledger digest of a row — what changes when its value, order or group
67
+ * does — and its value's canonical (encoded) size in bytes, from one pass.
68
+ * Throws {@link NotJsonError} when the value is not JSON.
69
+ */
70
+ export declare function digestAndValueBytes(row: DigestInput): {
71
+ digest: string;
72
+ valueBytes: number;
73
+ };
74
+ /** The ledger digest of a row (see {@link digestAndValueBytes}). */
75
+ export declare function rowDigest(row: DigestInput): string;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Why a ledger operation or a pull failed. The message starts with a stable
3
+ * prefix, the same as the Rust helper's (`node-app-replica`), so the text can
4
+ * go straight into the capability error channel.
5
+ */
6
+ export type ReplicaErrorKind = "config" | "row" | "request" | "schema" | "load" | "store";
7
+ /** The stable prefix of each kind's message. */
8
+ export declare const REPLICA_ERROR_PREFIXES: Readonly<Record<ReplicaErrorKind, string>>;
9
+ /** The first 64 characters (code points) of a key, as an error names it. */
10
+ export declare function keyForError(key: string): string;
11
+ export declare class ReplicaError extends Error {
12
+ readonly kind: ReplicaErrorKind;
13
+ /** The reason, without the prefix (and, for a row, without the key). */
14
+ readonly reason: string;
15
+ /** For `row`: the row's key (its first 64 characters). */
16
+ readonly key: string | undefined;
17
+ private constructor();
18
+ /** The collection's declaration is unusable (its name or table prefix). */
19
+ static config(reason: string): ReplicaError;
20
+ /** A row outside the contract's limits, or a key listed twice. */
21
+ static row(key: string, reason: string): ReplicaError;
22
+ /** A pull request (or another wire shape) outside the contract. */
23
+ static request(reason: string): ReplicaError;
24
+ /** The pull asked for a schema this collection does not serve. */
25
+ static schema(capability: string, schema: number): ReplicaError;
26
+ /** The app's `load` (or `list`/`get`) callback failed. */
27
+ static load(reason: string): ReplicaError;
28
+ /** The ledger's store failed. */
29
+ static store(reason: string): ReplicaError;
30
+ }
31
+ /** The text of anything thrown. */
32
+ export declare function errorText(error: unknown): string;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The ledger's rules (Phase 3 spec, sections 4.2, 4.6, 4.7 and 5.1), written
3
+ * against {@link LedgerTx} and nothing else. A line-for-line port of the Rust
4
+ * helper's `ledger.rs`: the same plan, the same cut, the same rotation rules.
5
+ */
6
+ import type { CollectionRecord, LedgerTx } from "./store.js";
7
+ import { type PullReply, type PullRequest, type ReplicaRow, type Row } from "./wire.js";
8
+ /** How long, and how many, tombstones are kept (section 4.7). */
9
+ export interface Horizon {
10
+ /** A tombstone older than this (ms since its delete) is pruned. */
11
+ maxAgeMs: number;
12
+ /** At most this many tombstones are kept per collection; the oldest go first. */
13
+ maxCount: number;
14
+ }
15
+ /** 30 days. */
16
+ export declare const TOMBSTONE_MAX_AGE_MS: number;
17
+ /** Per collection. */
18
+ export declare const TOMBSTONE_MAX_COUNT = 5000;
19
+ /**
20
+ * A rotation the app asks for (`reset()`, or the pruning guard) within this long
21
+ * of the last one is owed, not done at once (section 4.6). An owed rotation is
22
+ * never dropped. A rotation for evidence that the database went back in time is
23
+ * never held back.
24
+ */
25
+ export declare const ROTATION_MIN_INTERVAL_MS = 60000;
26
+ /** 30 days and 5,000 tombstones per collection. */
27
+ export declare const DEFAULT_HORIZON: Horizon;
28
+ /** Where the helper reads the time and draws new epochs. */
29
+ export interface ReplicaEnvironment {
30
+ /** Unix time in milliseconds. */
31
+ nowMs(): number;
32
+ /** A fresh epoch: `[a-z0-9]{1,16}`, different from every earlier one with overwhelming probability. */
33
+ newEpoch(): string;
34
+ }
35
+ /** What the ledger logic needs to know about one collection. */
36
+ export interface Spec {
37
+ name: string;
38
+ schemas: readonly number[];
39
+ env: ReplicaEnvironment;
40
+ horizon: Horizon;
41
+ }
42
+ /** The head a pull or an announce reports. */
43
+ export interface Head {
44
+ epoch: string;
45
+ version: number;
46
+ }
47
+ export declare function headOf(record: CollectionRecord): Head;
48
+ export declare function sameHead(a: Head, b: Head): boolean;
49
+ /** Checks a row against the contract's limits and returns its digest. */
50
+ export declare function checkRow(row: Row): string;
51
+ /** The collection's record, created (new epoch, version 0, dirty) when the ledger has none. */
52
+ export declare function open(tx: LedgerTx, spec: Spec): CollectionRecord;
53
+ /**
54
+ * A rotation the app asks for (`reset()`, the pruning guard): done now when the
55
+ * rate limit allows, else owed. Returns whether it rotated now.
56
+ */
57
+ export declare function requestRotation(tx: LedgerTx, spec: Spec, record: CollectionRecord): boolean;
58
+ /**
59
+ * Run at the start of every ledger write. `wentBack`: this process handed out
60
+ * a higher version of the ledger's epoch than the ledger now holds; that
61
+ * rotates at once. Otherwise an owed rotation whose minute has passed happens
62
+ * now. Returns whether it rotated.
63
+ */
64
+ export declare function begin(tx: LedgerTx, spec: Spec, record: CollectionRecord, wentBack: boolean): boolean;
65
+ /** Whether a read of `record` can stand for the write `begin` would do: no owed rotation is due. */
66
+ export declare function nothingDue(spec: Spec, record: CollectionRecord): boolean;
67
+ /**
68
+ * Starts a new epoch: every live row is renumbered 1…n in key order, every
69
+ * tombstone is dropped, the floor returns to 0, and an owed rotation is settled.
70
+ * Evidence that the database went back in time rotates through here at once.
71
+ */
72
+ export declare function rotateNow(tx: LedgerTx, spec: Spec, record: CollectionRecord): void;
73
+ /**
74
+ * Whole-list mode: `rows` is every current row. A new key or a changed digest
75
+ * gets the next version; a ledger key missing from `rows` becomes a tombstone at
76
+ * the next version. All rows are checked before anything is written.
77
+ */
78
+ export declare function reconcile(tx: LedgerTx, spec: Spec, record: CollectionRecord, rows: readonly Row[]): void;
79
+ export declare function touch(tx: LedgerTx, spec: Spec, record: CollectionRecord, row: Row): void;
80
+ export declare function remove(tx: LedgerTx, spec: Spec, record: CollectionRecord, key: string): void;
81
+ /** Loads the app's current rows: all of them for `null`, else those of the given keys. */
82
+ export type Load = (keys: readonly string[] | null) => readonly ReplicaRow[];
83
+ /** Refuses a request for a schema this collection does not serve, or outside the contract. */
84
+ export declare function checkRequest(spec: Spec, request: PullRequest): void;
85
+ /** Answers one pull (section 4.2). `record` is the collection's current record; the caller writes it back. */
86
+ export declare function answer(tx: LedgerTx, spec: Spec, record: CollectionRecord, request: PullRequest, load: Load): PullReply;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The ledger on the app's own SQLite database: the `Database` the app already
3
+ * holds from `bun:sqlite`, or Burger's `burger:sqlite` (the same surface).
4
+ *
5
+ * The tables are those of the Phase 3 spec, section 5.1, named with the table
6
+ * prefix, at the same layout as the Rust helper's (layout 2, recorded in
7
+ * `<prefix>replica_meta`; `ensure` upgrades layout 1 and refuses a newer one).
8
+ * Every ledger write runs in `BEGIN IMMEDIATE`, so two connections to one file
9
+ * serialise on SQLite's write lock instead of both reading the same head; give
10
+ * the connection a busy timeout (`PRAGMA busy_timeout`) so the second writer
11
+ * waits rather than failing. Called inside a transaction the app already holds,
12
+ * the ledger uses a savepoint, and its writes commit or roll back with the
13
+ * app's. Reading the head is one `SELECT` and takes no write lock.
14
+ */
15
+ import type { CollectionRecord, LedgerStore, LedgerTx } from "./store.js";
16
+ /** A value SQLite binds or returns. */
17
+ export type ReplicaSqlValue = string | number | bigint | boolean | null | Uint8Array;
18
+ /** The statement surface the ledger uses: `bun:sqlite`'s and `burger:sqlite`'s. */
19
+ export interface ReplicaStatement {
20
+ all(...params: ReplicaSqlValue[]): unknown[];
21
+ get(...params: ReplicaSqlValue[]): unknown;
22
+ run(...params: ReplicaSqlValue[]): unknown;
23
+ }
24
+ /**
25
+ * The database surface the ledger uses: the subset of `bun:sqlite`'s `Database`
26
+ * that Burger's `burger:sqlite` provides too (`exec`, `query`). `inTransaction`
27
+ * is read when the database has it (`bun:sqlite` does); without it, a `BEGIN`
28
+ * refused inside the app's own transaction falls back to a savepoint.
29
+ */
30
+ export interface ReplicaDatabase {
31
+ exec(sql: string): unknown;
32
+ query(sql: string): ReplicaStatement;
33
+ readonly inTransaction?: boolean;
34
+ }
35
+ /** The layout this helper writes. Layout 1 (the first release) had no `replica_meta`. */
36
+ export declare const LEDGER_LAYOUT = 2;
37
+ /** The names of one prefix's ledger tables. */
38
+ export interface LedgerTables {
39
+ meta: string;
40
+ collections: string;
41
+ rows: string;
42
+ }
43
+ /** The ledger on a `bun:sqlite` (or `burger:sqlite`) database. */
44
+ export declare class SqliteLedgerStore implements LedgerStore {
45
+ readonly db: ReplicaDatabase;
46
+ private readonly statements;
47
+ constructor(db: ReplicaDatabase);
48
+ /** A prepared statement, cached per store. */
49
+ statement(sql: string): ReplicaStatement;
50
+ /**
51
+ * Runs `work` in `BEGIN IMMEDIATE`, or in a savepoint inside the app's own
52
+ * transaction. Any failure after the transaction opened (the work's, or a
53
+ * refused `COMMIT` — `database is locked` while another connection reads a
54
+ * rollback-journal database) rolls it back, so the connection is never left
55
+ * inside a transaction the app does not know about.
56
+ */
57
+ private inTransaction;
58
+ /** Opens the transaction; true when it is a savepoint inside the app's. */
59
+ private begin;
60
+ /**
61
+ * Whether the connection is inside a transaction, for a database that does
62
+ * not say (Burger's). Decided by the condition, not by the refusal's text: a
63
+ * deferred `BEGIN` takes no lock, so it can only be refused because a
64
+ * transaction is already open; when it is accepted it is rolled back at once.
65
+ */
66
+ private insideAppTransaction;
67
+ ensure(prefix: string): void;
68
+ /** Brings the tables to {@link LEDGER_LAYOUT}, inside the caller's transaction. */
69
+ private bringUp;
70
+ write(prefix: string, work: (tx: LedgerTx) => void): void;
71
+ /** @internal The header, read with one statement. */
72
+ readRecordIn(t: LedgerTables, collection: string): CollectionRecord | null;
73
+ readRecord(prefix: string, collection: string): CollectionRecord | null;
74
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The storage seam: where the ledger lives.
3
+ *
4
+ * The ledger is two small tables in the app's own database (Phase 3 spec,
5
+ * section 5.1). An app plugs its database in by implementing {@link LedgerStore},
6
+ * or uses one of the two stores this package ships:
7
+ *
8
+ * - {@link SqliteLedgerStore} (`./sqlite.ts`): the tables `<prefix>replica_collections`,
9
+ * `<prefix>replica_rows` and `<prefix>replica_meta` on the database object the
10
+ * app already holds (`bun:sqlite`, or Burger's `burger:sqlite`), written in
11
+ * `BEGIN IMMEDIATE` transactions.
12
+ * - {@link MemoryLedger}: a ledger that lives as long as the process. A new
13
+ * process starts a new epoch, so every device takes one full copy after each
14
+ * start. For an app with no database of its own.
15
+ *
16
+ * The ledger's logic sees only {@link LedgerTx}; it never writes SQL. Every
17
+ * method is synchronous, as `bun:sqlite` is.
18
+ */
19
+ /** One collection's ledger header (`replica_collections`). */
20
+ export interface CollectionRecord {
21
+ /** Which unbroken run of versions this is: `[a-z0-9]{1,16}`. */
22
+ epoch: string;
23
+ /** The head: the version of the latest change; 0 means nothing yet. */
24
+ version: number;
25
+ /** Deletes at or below this version are forgotten; a device below it gets a full copy. */
26
+ floor: number;
27
+ /** Reconcile before the next pull. */
28
+ dirty: boolean;
29
+ /** Unix ms of the last epoch rotation. */
30
+ rotatedAt: number;
31
+ /** Unix ms of the last reconcile. */
32
+ reconciledAt: number;
33
+ /**
34
+ * A rotation was asked for within a minute of the last one and is still to
35
+ * happen: before the next version is assigned, or at the first ledger
36
+ * operation once the minute has passed. It is never dropped.
37
+ */
38
+ rotateOwed: boolean;
39
+ }
40
+ /** One row of the ledger (`replica_rows`): a key and what is known about it, never its value. */
41
+ export interface LedgerEntry {
42
+ key: string;
43
+ /** See `rowDigest`. */
44
+ digest: string;
45
+ /** The version at which the row last changed. */
46
+ version: number;
47
+ /** The row was deleted at `version`: this entry is a tombstone. */
48
+ deleted: boolean;
49
+ /** Unix ms; used for the tombstone age only. */
50
+ changedAt: number;
51
+ }
52
+ /** What {@link LedgerTx.pruneTombstones} did. */
53
+ export interface Pruned {
54
+ /** The highest version among the tombstones removed; `null` when none was. */
55
+ highest: number | null;
56
+ /** More than `keep` tombstones are left (a store that could not prune): the ledger rotates. */
57
+ overKeep: boolean;
58
+ }
59
+ /** Ledger reads and writes inside one write transaction. Keys sort by their UTF-8 bytes. */
60
+ export interface LedgerTx {
61
+ /** The collection's header, or `null` before its first write. */
62
+ record(collection: string): CollectionRecord | null;
63
+ /** Creates or replaces the collection's header. */
64
+ putRecord(collection: string, record: CollectionRecord): void;
65
+ /** The entry of one key, tombstone or not. */
66
+ entry(collection: string, key: string): LedgerEntry | null;
67
+ /** Every entry, tombstones included, in key order. */
68
+ entries(collection: string): LedgerEntry[];
69
+ /** Creates or replaces the entry of `entry.key`. */
70
+ putEntry(collection: string, entry: LedgerEntry): void;
71
+ /** Removes the entry of one key (a tombstone dropped by a rotation). */
72
+ deleteEntry(collection: string, key: string): void;
73
+ /** Entries (tombstones included) whose version is above `version`, in version order, at most `limit`. */
74
+ changesAfter(collection: string, version: number, limit: number): LedgerEntry[];
75
+ /** Live entries whose key sorts after `after` (all when `null`), in key order, at most `limit`. */
76
+ liveAfter(collection: string, after: string | null, limit: number): LedgerEntry[];
77
+ /**
78
+ * Removes the tombstones that changed before `changedBefore` (unix ms), and
79
+ * all but the `keep` newest (by version) of the rest. Its cost should follow
80
+ * the tombstones, not the live rows: it runs on every write.
81
+ */
82
+ pruneTombstones(collection: string, changedBefore: number, keep: number): Pruned;
83
+ }
84
+ /**
85
+ * A database the ledger can live in. `prefix` names the tables (`friends_` →
86
+ * `friends_replica_collections`); it is `[A-Za-z_][A-Za-z0-9_]{0,47}` or empty,
87
+ * checked before any call.
88
+ */
89
+ export interface LedgerStore {
90
+ /** Creates the ledger's tables if they do not exist. Idempotent. */
91
+ ensure(prefix: string): void;
92
+ /**
93
+ * Runs `work` in one write transaction: everything it wrote is committed when
94
+ * it returns, and nothing is when it throws. Two writers on the same ledger
95
+ * never interleave. `work` is called exactly once.
96
+ */
97
+ write(prefix: string, work: (tx: LedgerTx) => void): void;
98
+ /**
99
+ * The collection's header as last committed, read without taking the write
100
+ * lock: `head()` and a pull answered "nothing new" need nothing else. A store
101
+ * without it is read through {@link LedgerStore.write}.
102
+ */
103
+ readRecord?(prefix: string, collection: string): CollectionRecord | null;
104
+ }
105
+ /** The header through `readRecord`, or through `write` when the store has no cheaper read. */
106
+ export declare function readRecordOf(store: LedgerStore, prefix: string, collection: string): CollectionRecord | null;
107
+ /** A ledger held in process memory. {@link MemoryLedger.clone} copies it as it is now. */
108
+ export declare class MemoryLedger implements LedgerStore {
109
+ private tables;
110
+ ensure(): void;
111
+ write(prefix: string, work: (tx: LedgerTx) => void): void;
112
+ readRecord(prefix: string, collection: string): CollectionRecord | null;
113
+ /** A copy of the ledger as it is now. */
114
+ clone(): MemoryLedger;
115
+ /** Replaces this ledger's contents with a copy of `other`'s (a restore from backup). */
116
+ restoreFrom(other: MemoryLedger): void;
117
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * The replication contract's wire shapes (Phase 3 spec, section 4), byte for byte.
3
+ *
4
+ * Every `encode*` writes the compact JSON the contract prints, with the keys in
5
+ * the contract's order and row values in canonical form (object keys sorted by
6
+ * their UTF-8 bytes): the same bytes as the Rust helper's encoders
7
+ * (`node_app_replica::wire`; numbers aside, see the README), checked against its golden fixtures. Every
8
+ * `decode*` takes a parsed JSON value and is as strict as the Rust decoder: it
9
+ * ignores keys it does not know (the capability router stamps `caller` and
10
+ * `caller_ingress` into every payload) and accepts the short forms of a row
11
+ * entry, and refuses wrong shapes with a `replica_request_invalid:` error.
12
+ */
13
+ /** A row key: 1–256 bytes of UTF-8 with no control characters. */
14
+ export declare const MAX_KEY_BYTES = 256;
15
+ /** A row value's encoded (compact JSON) size. */
16
+ export declare const MAX_VALUE_BYTES = 65536;
17
+ /** The largest `ord` magnitude and the largest version: 2^53 − 1. */
18
+ export declare const MAX_SAFE_INTEGER: number;
19
+ /** A row's `part`: 0–128 bytes of UTF-8. */
20
+ export declare const MAX_PART_BYTES = 128;
21
+ /** An epoch: 1–16 characters of `[a-z0-9]`. */
22
+ export declare const MAX_EPOCH_CHARS = 16;
23
+ /** The rows (upserts plus deletes) one reply carries for one collection. */
24
+ export declare const MAX_ROWS_PER_REPLY = 500;
25
+ /** The encoded bytes of the rows one reply carries for one collection. */
26
+ export declare const MAX_REPLY_ROW_BYTES = 262144;
27
+ /** Entries in one `core.replica.sync` request. */
28
+ export declare const MAX_SYNC_ENTRIES = 64;
29
+ /** A whole `core.replica.sync` reply (under node-wire's 1 MiB frame). */
30
+ export declare const MAX_SYNC_REPLY_BYTES = 786432;
31
+ /** The device's batched check (node core). */
32
+ export declare const SYNC_CAPABILITY = "core.replica.sync";
33
+ /** The app's "my head moved" notice (node core). */
34
+ export declare const ANNOUNCE_CAPABILITY = "core.replica.announce";
35
+ /** The capability error prefix for a schema the app does not serve. */
36
+ export declare const SCHEMA_UNSUPPORTED_PREFIX = "replica_schema_unsupported:";
37
+ /** A row as an app hands it over: `ord` defaults to 0 and `part` to `""`. */
38
+ export interface ReplicaRow {
39
+ /** The row's identity in its collection: 1–256 bytes, no control characters. */
40
+ key: string;
41
+ /** Any JSON value, at most 65,536 bytes encoded. */
42
+ value: unknown;
43
+ /** The row's position in its list (|ord| ≤ 2^53 − 1); default 0. */
44
+ ord?: number;
45
+ /** A group the row belongs to (a conversation id for a message), ≤ 128 bytes; default `""`. */
46
+ part?: string;
47
+ }
48
+ /** A row with its defaults filled in. */
49
+ export interface Row {
50
+ key: string;
51
+ value: unknown;
52
+ ord: number;
53
+ part: string;
54
+ }
55
+ /**
56
+ * Fills in a row's defaults. Something that is not a row with a string key is
57
+ * a `replica_row_invalid:` error (an app's untyped data reaches here too).
58
+ */
59
+ export declare function toRow(row: ReplicaRow): Row;
60
+ /** The request the node sends an app's pull capability. */
61
+ export interface PullRequest {
62
+ /** The epoch the caller holds; `""` when it holds nothing. */
63
+ epoch: string;
64
+ /** The version the caller holds. */
65
+ version: number;
66
+ /** The schema number: the `N` of the consumer's `.vN`. */
67
+ schema: number;
68
+ /** The most rows to return (the helper serves at most 500). */
69
+ limit: number;
70
+ /** The last key of the previous page of a paged full copy. */
71
+ resume?: string;
72
+ }
73
+ /** "I hold nothing": the first request for a collection. */
74
+ export declare function initialPullRequest(schema: number): PullRequest;
75
+ /** The row limit the helper serves: `l`, capped at 500. */
76
+ export declare function effectiveLimit(request: PullRequest): number;
77
+ /**
78
+ * Checks a request against the contract's limits; returns the reason it is
79
+ * outside them, or `null`. A limit above 500 is not an error; the helper serves 500.
80
+ */
81
+ export declare function pullRequestProblem(request: PullRequest): string | null;
82
+ /** An app's answer to one pull (section 4.2). */
83
+ export type PullReply =
84
+ /** `{"e":"k3f9a2c1","v":41}` */
85
+ {
86
+ kind: "nothing-new";
87
+ epoch: string;
88
+ version: number;
89
+ }
90
+ /** `{"e":…,"v":43,"u":[…],"x":[…]}` plus `"m":1` when more remain. */
91
+ | {
92
+ kind: "changes";
93
+ epoch: string;
94
+ version: number;
95
+ upserts: Row[];
96
+ deletes: string[];
97
+ more: boolean;
98
+ }
99
+ /**
100
+ * `{"e":…,"v":7,"f":1,"u":[…]}` plus `"n":"<last key>"` when more pages
101
+ * remain, and `"h"` (for the node only) on a later page read after the head
102
+ * moved. Rows are in key order.
103
+ */
104
+ | {
105
+ kind: "full-copy";
106
+ epoch: string;
107
+ version: number;
108
+ rows: Row[];
109
+ next?: string;
110
+ head?: number;
111
+ };
112
+ /**
113
+ * The highest version whose data the reply can carry: its version, or `"h"` on
114
+ * a later page of a full copy. The node keeps, per epoch, the highest of these
115
+ * it has passed on.
116
+ */
117
+ export declare function handedOut(reply: PullReply): number;
118
+ /** True when the caller must ask again to get the rest (`"m":1` or `"n"`). */
119
+ export declare function isTruncated(reply: PullReply): boolean;
120
+ /** One entry of a device check: `[pullCapability, schema, epoch, version, resume?]`. */
121
+ export interface SyncEntry {
122
+ capability: string;
123
+ schema: number;
124
+ epoch: string;
125
+ version: number;
126
+ resume?: string;
127
+ }
128
+ /** The pull request the node sends the app for one entry of a check. */
129
+ export declare function pullRequestOf(entry: SyncEntry, limit: number): PullRequest;
130
+ /** The payload of `core.replica.sync`, plus `"origin":"background"` on checks no person waits for. */
131
+ export interface SyncRequest {
132
+ entries: SyncEntry[];
133
+ origin?: string;
134
+ }
135
+ /** Why the node could not answer one entry of a check. */
136
+ export type SyncErrorCode = "unknown" | "schema" | "unavailable" | "busy";
137
+ /** The node's answer for one entry of a check (section 4.3). */
138
+ export type SyncAnswer = {
139
+ kind: "nothing-new";
140
+ } | {
141
+ kind: "changes";
142
+ version: number;
143
+ upserts: Row[];
144
+ deletes: string[];
145
+ more: boolean;
146
+ } | {
147
+ kind: "full-copy";
148
+ epoch: string;
149
+ version: number;
150
+ rows: Row[];
151
+ next?: string;
152
+ } | {
153
+ kind: "error";
154
+ code: SyncErrorCode;
155
+ };
156
+ /** What the node passes on to the device for an app's reply (`"h"` and the changes' `e` stay behind). */
157
+ export declare function syncAnswerOf(reply: PullReply): SyncAnswer;
158
+ /** The `result` of `core.replica.sync`, aligned with the request's entries by index. */
159
+ export interface SyncReply {
160
+ answers: SyncAnswer[];
161
+ }
162
+ /** The payload of `core.replica.announce`. */
163
+ export interface Announce {
164
+ capability: string;
165
+ epoch: string;
166
+ version: number;
167
+ }
168
+ /** The node's answer to an announce: `{"ok":true}` or `{"rotate":true}`. */
169
+ export type AnnounceReply = "ok" | "rotate";
170
+ /** One head in a `replica.heads` push. */
171
+ export interface PushedHead {
172
+ capability: string;
173
+ epoch: string;
174
+ version: number;
175
+ }
176
+ /** The `data` of a `replica.heads` frame. */
177
+ export interface HeadsData {
178
+ heads: PushedHead[];
179
+ }
180
+ /** `[a-z0-9]{1,16}`. */
181
+ export declare function isEpoch(value: string): boolean;
182
+ /** Why a row key is outside the contract, or `null`: 1–256 bytes, no control characters. */
183
+ export declare function keyProblem(key: string): string | null;
184
+ /** The canonical JSON of a row's value; a value that is not JSON is a row error. */
185
+ export declare function canonicalValue(row: Row): string;
186
+ /** `["<key>",<value>,<ord>,"<part>"]`, dropping a trailing `""` part and then a trailing 0 ord. */
187
+ export declare function encodeRow(row: Row): string;
188
+ /** The bytes one row adds inside `u` (its entry plus a separating comma). */
189
+ export declare function encodedRowBytes(row: Row): number;
190
+ /** The bytes one delete adds inside `x`. */
191
+ export declare function encodedDeleteBytes(key: string): number;
192
+ /** `{"e":"k3f9a2c1","v":41,"s":1,"l":500}` plus `"a"` when resuming. */
193
+ export declare function encodePullRequest(request: PullRequest): string;
194
+ /** The exact bytes of an app's pull reply. */
195
+ export declare function encodePullReply(reply: PullReply): string;
196
+ /** `["friends.people.pull",1,"k3f9a2c1",41]` plus the resume key. */
197
+ export declare function encodeSyncEntry(entry: SyncEntry): string;
198
+ /** `{"c":[…]}` plus `"origin"`. */
199
+ export declare function encodeSyncRequest(request: SyncRequest): string;
200
+ /** `0`, the changes, a full copy, or `{"err":"<code>"}`. */
201
+ export declare function encodeSyncAnswer(answer: SyncAnswer): string;
202
+ /** `{"r":[…]}`. */
203
+ export declare function encodeSyncReply(reply: SyncReply): string;
204
+ /** `{"c":"friends.people.pull","e":"k3f9a2c1","v":42}`. */
205
+ export declare function encodeAnnounce(announce: Announce): string;
206
+ /** `{"ok":true}` or `{"rotate":true}`. */
207
+ export declare function encodeAnnounceReply(reply: AnnounceReply): string;
208
+ /** `{"h":[["friends.people.pull","k3f9a2c1",42]]}`. */
209
+ export declare function encodeHeadsData(data: HeadsData): string;
210
+ /** A row entry `[key, value, ord?, part?]`. */
211
+ export declare function decodeRow(value: unknown): Row;
212
+ /** A pull request payload (unknown keys ignored, `l` defaults to 500). Not yet checked against the limits. */
213
+ export declare function decodePullRequest(value: unknown): PullRequest;
214
+ /** An app's pull reply. */
215
+ export declare function decodePullReply(value: unknown): PullReply;
216
+ /** One entry of a check: `[capability, schema, epoch, version, resume?]`. */
217
+ export declare function decodeSyncEntry(value: unknown): SyncEntry;
218
+ /** The payload of `core.replica.sync`. */
219
+ export declare function decodeSyncRequest(value: unknown): SyncRequest;
220
+ /** One answer of a check. */
221
+ export declare function decodeSyncAnswer(value: unknown): SyncAnswer;
222
+ /** The `result` of `core.replica.sync`. */
223
+ export declare function decodeSyncReply(value: unknown): SyncReply;
224
+ /** The payload of `core.replica.announce`. */
225
+ export declare function decodeAnnounce(value: unknown): Announce;
226
+ /** The node's answer to an announce. */
227
+ export declare function decodeAnnounceReply(value: unknown): AnnounceReply;
228
+ /** The `data` of a `replica.heads` frame. */
229
+ export declare function decodeHeadsData(value: unknown): HeadsData;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * `@econ-v1/app-sdk/replica` — change-only replication of app data for Bun and
3
+ * Burger app backends (Phase 3 of the one-stack design,
4
+ * `docs/superpowers/specs/2026-11-19-one-stack-phase-3-replication.md`,
5
+ * sections 4 and 5). The twin of the Rust helper `node-app-replica`: the same
6
+ * ledger rules and the same wire bytes.
7
+ *
8
+ * An app declares each collection once and tells the helper what changed. The
9
+ * helper keeps a small ledger in the app's own database (keys, digests,
10
+ * versions, tombstones — never the rows) and answers the node's pull with one of
11
+ * three replies: nothing new, the changes since the caller's version, or a full
12
+ * copy. The app writes no versioning code.
13
+ *
14
+ * ```ts
15
+ * import { Database } from "bun:sqlite";
16
+ * import { invokeCapability } from "@econ-v1/app-sdk";
17
+ * import { Replica, hostInvoke } from "@econ-v1/app-sdk/replica";
18
+ *
19
+ * const replica = new Replica(db, hostInvoke(invokeCapability), { tablePrefix: "message_", warn: host.warn });
20
+ * const conversations = replica.collection("message.conversations.pull", {
21
+ * list: () => listConversations(db).map((c) => ({ key: c.id, value: c, ord: -c.updatedAt })),
22
+ * });
23
+ * // providedCapabilities(): [...own, ...replica.provides()]
24
+ * // handleCapability(request): if (replica.handles(request.capability)) payload = await replica.handle(request.capability, request.payload)
25
+ * // init(): await replica.start();
26
+ * // at a write site: conversations.changed();
27
+ * ```
28
+ *
29
+ * The module imports no platform module: it runs on the database object the app
30
+ * already holds, `bun:sqlite`'s or Burger's `burger:sqlite`.
31
+ */
32
+ import { CollectionLedger, type ReplicaInvoke } from "./replica/collection.js";
33
+ import { type Head, type Horizon, type ReplicaEnvironment } from "./replica/ledger.js";
34
+ import { type ReplicaDatabase } from "./replica/sqlite.js";
35
+ import type { LedgerStore } from "./replica/store.js";
36
+ import { type ReplicaRow } from "./replica/wire.js";
37
+ export { CollectionLedger, systemEnvironment } from "./replica/collection.js";
38
+ export type { AnnounceOutcome, Answered, CollectionLedgerOptions, ReplicaInvoke } from "./replica/collection.js";
39
+ export { canonicalJson, compareUtf8, fnv1a64, isWithinValueDepth, MAX_VALUE_DEPTH, rowDigest, utf8Length } from "./replica/digest.js";
40
+ export { REPLICA_ERROR_PREFIXES, ReplicaError } from "./replica/errors.js";
41
+ export type { ReplicaErrorKind } from "./replica/errors.js";
42
+ export { DEFAULT_HORIZON, ROTATION_MIN_INTERVAL_MS, TOMBSTONE_MAX_AGE_MS, TOMBSTONE_MAX_COUNT, } from "./replica/ledger.js";
43
+ export type { Head, Horizon, ReplicaEnvironment } from "./replica/ledger.js";
44
+ export { LEDGER_LAYOUT, SqliteLedgerStore } from "./replica/sqlite.js";
45
+ export type { ReplicaDatabase, ReplicaSqlValue, ReplicaStatement } from "./replica/sqlite.js";
46
+ export { MemoryLedger } from "./replica/store.js";
47
+ export type { CollectionRecord, LedgerEntry, LedgerStore, LedgerTx, Pruned } from "./replica/store.js";
48
+ export * from "./replica/wire.js";
49
+ /** A `provided_capabilities` entry (the SDK's `ProvidedCapability` shape). */
50
+ export interface ReplicaProvidedCapability {
51
+ name: string;
52
+ description: string;
53
+ }
54
+ /** One collection as the app declares it. */
55
+ export interface CollectionOptions {
56
+ /** The `N`s of the `.vN` names this app serves; default `[1]`. */
57
+ schemas?: readonly number[];
58
+ /** Every current row. Called inside the ledger's transaction; it must not call the replica. */
59
+ list: () => readonly ReplicaRow[];
60
+ /**
61
+ * The rows of the given keys (a key with no row is left out), for large lists;
62
+ * by default `list()` filtered.
63
+ */
64
+ get?: (keys: readonly string[]) => readonly ReplicaRow[];
65
+ }
66
+ /** Options of a {@link Replica}. */
67
+ export interface ReplicaOptions {
68
+ /** Names the ledger's tables (`message_` → `message_replica_rows`); default empty. */
69
+ tablePrefix?: string;
70
+ /** Where a failed announce or a failed background reconcile is reported (once per failure run). */
71
+ warn?: (message: string) => void;
72
+ /**
73
+ * How a failed background reconcile or announce is retried: after `firstMs`,
74
+ * then twice as long each time up to `maxMs`, until it succeeds or the
75
+ * replica is stopped. Default 2 s doubling to 60 s (2, 4, 8, 16, 32, 60, 60 … s).
76
+ */
77
+ retry?: {
78
+ firstMs?: number;
79
+ maxMs?: number;
80
+ };
81
+ /** The clock and epoch source; default the system's. */
82
+ env?: ReplicaEnvironment;
83
+ /** The tombstone horizon; default 30 days and 5,000 per collection. */
84
+ horizon?: Horizon;
85
+ /** The trailing window in which `changed()` calls coalesce into one reconcile; default 50 ms. */
86
+ coalesceMs?: number;
87
+ }
88
+ /** What an app does with one declared collection. */
89
+ export interface ReplicaCollection {
90
+ /** The pull capability. */
91
+ readonly name: string;
92
+ /** The ledger underneath. */
93
+ readonly ledger: CollectionLedger;
94
+ /** "Something may have changed": reconcile soon (one reconcile per burst), then announce. */
95
+ changed(): void;
96
+ /** One row written at a write site. Throws a `replica_row_invalid:` error for a row outside the limits. */
97
+ touch(row: ReplicaRow): void;
98
+ /** One row deleted at a write site. */
99
+ remove(key: string): void;
100
+ /** The app replaced its data: a new epoch (at most one a minute; a held-back one is owed), then reconcile. */
101
+ reset(): void;
102
+ /** The ledger's head. */
103
+ head(): Head;
104
+ }
105
+ /** The SDK's `invokeCapability` surface, as {@link hostInvoke} needs it. */
106
+ export type InvokeCapability = (request: {
107
+ id: string;
108
+ capability: string;
109
+ payload: unknown;
110
+ }, timeoutMs?: number) => Promise<{
111
+ success: boolean;
112
+ payload: unknown;
113
+ }>;
114
+ /**
115
+ * Adapts the SDK's `invokeCapability` to the replica's door to the node: the
116
+ * reply payload on success, an error carrying the payload's text otherwise.
117
+ */
118
+ export declare function hostInvoke(invokeCapability: InvokeCapability, timeoutMs?: number): ReplicaInvoke;
119
+ /**
120
+ * The app's replicated collections: declares them, serves their pull
121
+ * capabilities and announces their heads to the node.
122
+ */
123
+ export declare class Replica {
124
+ private readonly invoke;
125
+ private readonly options;
126
+ private readonly store;
127
+ private readonly collections;
128
+ private readonly tablePrefix;
129
+ private readonly warn;
130
+ /**
131
+ * `db` is the app's own database (`bun:sqlite`'s `Database`, or Burger's), or
132
+ * any {@link LedgerStore}. `invoke` reaches the node's capability bus (see
133
+ * {@link hostInvoke}).
134
+ */
135
+ constructor(db: ReplicaDatabase | LedgerStore, invoke: ReplicaInvoke, options?: ReplicaOptions);
136
+ /**
137
+ * Declares a collection served by `pullCapability` (`<app>.<collection>.pull`)
138
+ * and creates the ledger's tables if they do not exist.
139
+ */
140
+ collection(pullCapability: string, options: CollectionOptions): ReplicaCollection;
141
+ /** The `provided_capabilities` entries of the pull capabilities; merge them into the app's own. */
142
+ provides(): ReplicaProvidedCapability[];
143
+ /** Whether `capability` is one of this replica's pull capabilities. */
144
+ handles(capability: string): boolean;
145
+ /**
146
+ * Answers a pull capability: the reply object (the contract's bytes once
147
+ * JSON-encoded). Rejects with a {@link ReplicaError} whose message starts
148
+ * with a stable prefix (`replica_schema_unsupported:`, `replica_request_invalid:`, …).
149
+ */
150
+ handle(capability: string, payload: unknown): Promise<unknown>;
151
+ /**
152
+ * Announces every collection's head once. Call it at app start, before the
153
+ * app's first write: it is how a database restored while the app was stopped
154
+ * is found. Never rejects.
155
+ */
156
+ start(): Promise<void>;
157
+ /** Runs every pending reconcile now and waits for the announces in flight. */
158
+ flush(): Promise<void>;
159
+ /** Whether any collection has a failed reconcile or announce waiting for its retry. */
160
+ retrying(): boolean;
161
+ /**
162
+ * Cancels pending reconciles and retries (at shutdown). The ledgers stay
163
+ * dirty, so the next pull reconciles.
164
+ */
165
+ stop(): void;
166
+ }
@@ -0,0 +1,31 @@
1
+ // @bun
2
+ var O={config:"replica_config_invalid:",row:"replica_row_invalid:",request:"replica_request_invalid:",schema:"replica_schema_unsupported:",load:"replica_load_failed:",store:"replica_store_failed:"};function yn(e){return typeof e==="string"?Array.from(e).slice(0,64).join(""):""}class s extends Error{kind;reason;key;constructor(e,n,t,r){super(n);this.name="ReplicaError",this.kind=e,this.reason=t,this.key=r}static config(e){return new s("config",`${O.config} ${e}`,e)}static row(e,n){let t=yn(e);return new s("row",`${O.row} row '${t}': ${n}`,n,t)}static request(e){return new s("request",`${O.request} ${e}`,e)}static schema(e,n){let t=`schema ${n} is not served by ${e}`;return new s("schema",`${O.schema} ${t}`,t)}static load(e){return new s("load",`${O.load} ${e}`,e)}static store(e){return new s("store",`${O.store} ${e}`,e)}}function w(e){if(e instanceof Error)return e.message;if(typeof e==="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function T(e,n){if(e===n)return 0;let t=Math.min(e.length,n.length);for(let r=0;r<t;r+=1){let o=e.charCodeAt(r),i=n.charCodeAt(r);if(o===i)continue;if(o>=55296)o+=o>=57344?-2048:8192;if(i>=55296)i+=i>=57344?-2048:8192;return o<i?-1:1}return e.length<n.length?-1:e.length>n.length?1:0}function _(e){let n=0;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<128)n+=1;else if(r<2048)n+=2;else if(r>=55296&&r<=56319&&re(e.charCodeAt(t+1)))n+=4,t+=1;else n+=3}return n}function re(e){return e>=56320&&e<=57343}function U(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t<55296||t>57343)continue;if(t<=56319&&re(e.charCodeAt(n+1))){n+=1;continue}return!0}return!1}var oe=128;function ie(e){let n=[{level:1,value:e}];for(let t=n.pop();t!==void 0;t=n.pop()){if(typeof t.value!=="object"||t.value===null)continue;if(t.level>=oe)return!1;for(let r of Array.isArray(t.value)?t.value:Object.values(t.value))n.push({level:t.level+1,value:r})}return!0}var se="value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";class k extends Error{}function mn(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function _e(e,n){if(U(e))throw new k(`${n} holds a lone surrogate`);return JSON.stringify(e)}function te(e,n,t){switch(typeof e){case"string":return _e(e,n);case"number":if(!Number.isFinite(e))throw new k(`${n} is ${String(e)}, not a JSON number`);return JSON.stringify(e);case"boolean":return e?"true":"false";case"object":{if(e===null)return"null";if(t+1>=oe)throw new k(se);if(Array.isArray(e)){let i=[];for(let a=0;a<e.length;a+=1){let u=e[a];if(u===void 0)throw new k(`${n}[${a}] is undefined`);i.push(te(u,`${n}[${a}]`,t+1))}return`[${i.join(",")}]`}if(!mn(e))throw new k(`${n} is not a plain object`);let r=Object.keys(e).filter((i)=>e[i]!==void 0).sort(T),o=[];for(let i of r)o.push(`${_e(i,`${n} key`)}:${te(e[i],`${n}.${i}`,t+1)}`);return`{${o.join(",")}}`}default:throw new k(`${n} is ${e===void 0?"undefined":`a ${typeof e}`}, not JSON`)}}function Y(e){return te(e,"value",0)}class ae{h0=8997;h1=33826;h2=40164;h3=52210;bytes=0;byte(e){this.h0^=e;let n=this.h0*435,t=this.h1*435,r=this.h2*435+(this.h0<<8),o=this.h3*435+(this.h1<<8);t+=n>>>16,this.h0=n&65535,r+=t>>>16,this.h1=t&65535,this.h3=o+(r>>>16)&65535,this.h2=r&65535}update(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t>=55296&&t<=56319&&re(e.charCodeAt(n+1)))t=65536+(t-55296<<10)+(e.charCodeAt(n+1)-56320),n+=1;else if(t>=55296&&t<=57343)t=65533;if(t<128)this.byte(t),this.bytes+=1;else if(t<2048)this.byte(192|t>>6),this.byte(128|t&63),this.bytes+=2;else if(t<65536)this.byte(224|t>>12),this.byte(128|t>>6&63),this.byte(128|t&63),this.bytes+=3;else this.byte(240|t>>18),this.byte(128|t>>12&63),this.byte(128|t>>6&63),this.byte(128|t&63),this.bytes+=4}return this}hex(){return[this.h3,this.h2,this.h1,this.h0].map((e)=>e.toString(16).padStart(4,"0")).join("")}}function wn(e){return new ae().update(e).hex()}function ce(e){let n=Y(e.value),t=new ae().update("[").update(n),r=t.bytes-1;return t.update(`,${e.ord},`).update(JSON.stringify(e.part)).update("]"),{digest:`${t.hex()}.${t.bytes}`,valueBytes:r}}function Rn(e){return ce(e).digest}var Me=256,ue=65536,C=Number.MAX_SAFE_INTEGER,de=128,Jn=16,he=500,fe=262144,Zn=64,Qn=786432,et="core.replica.sync",Ne="core.replica.announce",nt="replica_schema_unsupported:";function F(e){if(typeof e!=="object"||e===null)throw s.row("",`a row must be an object {key, value, ord?, part?}, not ${e===null?"null":typeof e}`);let n=e.key;if(typeof n!=="string")throw s.row("",`key must be a string, not ${n===null?"null":typeof n}`);return{key:n,value:e.value,ord:e.ord??0,part:e.part??""}}function tt(e){return{epoch:"",version:0,schema:e,limit:he}}function pe(e){return Math.min(e.limit,he)}function Ce(e){if(e.epoch!==""&&!ge(e.epoch))return'e must be "" or 1-16 characters of [a-z0-9]';if(e.version>C)return"v must be at most 2^53 - 1";if(e.limit===0)return"l must be at least 1";if(e.resume!==void 0){let n=G(e.resume);if(n!==null)return`a ${n}`;if(e.epoch==="")return"a resumes a full copy and needs that copy's e"}return null}function rt(e){if(e.kind==="full-copy"&&e.head!==void 0)return Math.max(e.version,e.head);return e.version}function ot(e){if(e.kind==="changes")return e.more;if(e.kind==="full-copy")return e.next!==void 0;return!1}function it(e,n){let t={epoch:e.epoch,version:e.version,schema:e.schema,limit:n};if(e.resume!==void 0)t.resume=e.resume;return t}var vn=["unknown","schema","unavailable","busy"];function st(e){switch(e.kind){case"nothing-new":return{kind:"nothing-new"};case"changes":return{kind:"changes",version:e.version,upserts:e.upserts,deletes:e.deletes,more:e.more};case"full-copy":{let n={kind:"full-copy",epoch:e.epoch,version:e.version,rows:e.rows};if(e.next!==void 0)n.next=e.next;return n}}}function ge(e){return/^[a-z0-9]{1,16}$/.test(e)}var bn=/[\u0000-\u001f\u007f-\u009f]/;function G(e){if(typeof e!=="string")return"key must be a string";if(e.length===0)return"key must not be empty";let n=_(e);if(n>Me)return`key is ${n} bytes; at most ${Me} are allowed`;if(bn.test(e))return"key must not contain control characters";if(U(e))return"key must not contain a lone surrogate";return null}function p(e){return JSON.stringify(e)}function b(e){if(!Number.isSafeInteger(e))throw s.store(`${e} is not an integer within 2^53 - 1`);return String(e)}function En(e){try{return Y(e.value)}catch(n){if(n instanceof k)throw s.row(e.key,n.message);throw n}}function Pe(e){let n=`[${p(e.key)},${En(e)}`;if(e.part!=="")return`${n},${b(e.ord)},${p(e.part)}]`;if(e.ord!==0)return`${n},${b(e.ord)}]`;return`${n}]`}function ye(e){return _(Pe(e))+1}function Ie(e){return _(p(e))+1}function De(e){return`[${e.map(Pe).join(",")}]`}function xn(e){return`[${e.map(p).join(",")}]`}function at(e){let n=e.resume===void 0?"":`,"a":${p(e.resume)}`;return`{"e":${p(e.epoch)},"v":${b(e.version)},"s":${b(e.schema)},"l":${b(e.limit)}${n}}`}function He(e,n,t,r){return`"v":${b(e)},"u":${De(n)},"x":${xn(t)}${r?',"m":1':""}`}function Ue(e,n,t,r){return`"e":${p(e)},"v":${b(n)},"f":1,"u":${De(t)}${r===void 0?"":`,"n":${p(r)}`}`}function K(e){switch(e.kind){case"nothing-new":return`{"e":${p(e.epoch)},"v":${b(e.version)}}`;case"changes":return`{"e":${p(e.epoch)},${He(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":{let n=e.head===void 0?"":`,"h":${b(e.head)}`;return`{${Ue(e.epoch,e.version,e.rows,e.next)}${n}}`}}}function kn(e){let n=e.resume===void 0?"":`,${p(e.resume)}`;return`[${p(e.capability)},${b(e.schema)},${p(e.epoch)},${b(e.version)}${n}]`}function ct(e){let n=e.origin===void 0?"":`,"origin":${p(e.origin)}`;return`{"c":[${e.entries.map(kn).join(",")}]${n}}`}function An(e){switch(e.kind){case"nothing-new":return"0";case"changes":return`{${He(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":return`{${Ue(e.epoch,e.version,e.rows,e.next)}}`;case"error":return`{"err":${p(e.code)}}`}}function lt(e){return`{"r":[${e.answers.map(An).join(",")}]}`}function Fe(e){return`{"c":${p(e.capability)},"e":${p(e.epoch)},"v":${b(e.version)}}`}function ut(e){return e==="ok"?'{"ok":true}':'{"rotate":true}'}function dt(e){return`{"h":[${e.heads.map((t)=>`[${p(t.capability)},${p(t.epoch)},${b(t.version)}]`).join(",")}]}`}function g(e){return s.request(e)}function qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function M(e,n){if(!qe(e))throw g(`${n} must be an object`);return e}function R(e,n){let t=e[n];return t===null?void 0:t}function x(e,n,t){let r=R(e,n);if(r===void 0)throw g(`${t}: missing field \`${n}\``);return r}function y(e,n){if(typeof e!=="string")throw g(`${n} must be a string`);return e}function A(e,n,t=C){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>t){let r=t===C?"from 0 to 2^53 - 1":t===Number.MAX_VALUE?"of at least 0":`from 0 to ${t}`;throw g(`${n} must be an integer ${r}`)}return e}var le=4294967295;function z(e,n){let t=R(e,n);if(t===void 0)return!1;if(A(t,n,255)!==1)throw g(`${n} must be 1 when present, got ${JSON.stringify(t)}`);return!0}function Tn(e){if(!Array.isArray(e)||e.length<2||e.length>4)throw g("a row entry is [key, value, ord?, part?]");let n=e,t=y(n[0],"a row's key"),r=n[2];if(r!==void 0&&(typeof r!=="number"||!Number.isInteger(r)))throw g("a row's ord must be an integer");let o=n[3]===void 0?"":y(n[3],"a row's part");return{key:t,value:n[1],ord:typeof r==="number"?r:0,part:o}}function W(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw g(`${n} must be an array of row entries`);return e.map(Tn)}function Be(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw g(`${n} must be an array of keys`);return e.map((t)=>y(t,`an entry of ${n}`))}function J(e){let n=M(e,"a pull request"),t=R(n,"l"),r={epoch:y(x(n,"e","a pull request"),"e"),version:A(x(n,"v","a pull request"),"v",Number.MAX_VALUE),schema:A(x(n,"s","a pull request"),"s",le),limit:t===void 0?he:A(t,"l",le)},o=R(n,"a");if(o!==void 0)r.resume=y(o,"a");return r}function ht(e){let n=M(e,"a pull reply"),t=A(x(n,"v","a pull reply"),"v"),r=R(n,"e");if(r===void 0)throw g("a pull reply: missing field `e`");let o=y(r,"e"),i=R(n,"u"),a=R(n,"x");if(z(n,"f")){let u={kind:"full-copy",epoch:o,version:t,rows:W(i,"u")},d=R(n,"n");if(d!==void 0)u.next=y(d,"n");let l=R(n,"h");if(l!==void 0)u.head=A(l,"h");return u}if(i!==void 0||a!==void 0)return{kind:"changes",epoch:o,version:t,upserts:W(i,"u"),deletes:Be(a,"x"),more:z(n,"m")};return{kind:"nothing-new",epoch:o,version:t}}function Ln(e){if(!Array.isArray(e)||e.length<4||e.length>5)throw g("a sync entry is [capability, schema, epoch, version, resume?]");let n=e,t={capability:y(n[0],"a sync entry's capability"),schema:A(n[1],"a sync entry's schema",le),epoch:y(n[2],"a sync entry's epoch"),version:A(n[3],"a sync entry's version")};if(n.length===5)t.resume=y(n[4],"a sync entry's resume key");return t}function ft(e){let n=M(e,"a sync request"),t=x(n,"c","a sync request");if(!Array.isArray(t))throw g("c must be an array of sync entries");let r={entries:t.map(Ln)},o=R(n,"origin");if(o!==void 0)r.origin=y(o,"origin");return r}function Sn(e){if(e===0)return{kind:"nothing-new"};if(!qe(e))throw g("a sync answer is 0, a changes object, a full copy or an error");if("err"in e){let t=vn.find((r)=>r===e.err);if(t===void 0)throw g("err must be a known error code");return{kind:"error",code:t}}let n=A(x(e,"v","a sync answer"),"v");if(z(e,"f")){let t={kind:"full-copy",epoch:y(x(e,"e","a sync answer"),"e"),version:n,rows:W(R(e,"u"),"u")},r=R(e,"n");if(r!==void 0)t.next=y(r,"n");return t}return{kind:"changes",version:n,upserts:W(R(e,"u"),"u"),deletes:Be(R(e,"x"),"x"),more:z(e,"m")}}function pt(e){let n=x(M(e,"a sync reply"),"r","a sync reply");if(!Array.isArray(n))throw g("r must be an array of answers");return{answers:n.map(Sn)}}function gt(e){let n=M(e,"an announce");return{capability:y(x(n,"c","an announce"),"c"),epoch:y(x(n,"e","an announce"),"e"),version:A(x(n,"v","an announce"),"v")}}function Xe(e){let n=M(e,"an announce reply"),t=(i)=>{let a=R(n,i);if(a===void 0)return!1;if(typeof a!=="boolean")throw g(`${i} must be a boolean`);return a},r=t("rotate"),o=t("ok");if(r)return"rotate";if(o)return"ok";throw g('an announce reply is {"ok":true} or {"rotate":true}')}function yt(e){let n=x(M(e,"replica.heads data"),"h","replica.heads data");if(!Array.isArray(n))throw g("h must be an array of heads");return{heads:n.map((t)=>{if(!Array.isArray(t)||t.length!==3)throw g("a pushed head is [capability, epoch, version]");let r=t;return{capability:y(r[0],"a head's capability"),epoch:y(r[1],"a head's epoch"),version:A(r[2],"a head's version")}})}}var Ve=2592000000,Ye=5000,ze=60000,me={maxAgeMs:Ve,maxCount:Ye};function L(e){return{epoch:e.epoch,version:e.version}}function q(e,n){return e.epoch===n.epoch&&e.version===n.version}function we(e){let n=G(e.key);if(n!==null)throw s.row(e.key,n);if(!ie(e.value))throw s.row(e.key,se);let t,r;try{({digest:t,valueBytes:r}=ce(e))}catch(i){if(i instanceof k)throw s.row(e.key,i.message);throw i}if(r>ue)throw s.row(e.key,`value is ${r} bytes encoded; at most ${ue} are allowed`);if(!Number.isInteger(e.ord)||Math.abs(e.ord)>C)throw s.row(e.key,"ord must be within \xB1(2^53 - 1)");if(typeof e.part!=="string")throw s.row(e.key,"part must be a string");let o=_(e.part);if(o>de)throw s.row(e.key,`part is ${o} bytes; at most ${de} are allowed`);if(U(e.part))throw s.row(e.key,"part must not contain a lone surrogate");return t}function We(e,n){for(let t=0;t<4;t+=1){let r=e.env.newEpoch();if(!ge(r))throw s.store("the environment produced an epoch outside [a-z0-9]{1,16}");if(r!==n)return r}throw s.store("the environment keeps producing the current epoch")}function Z(e,n,t){if(t.rotateOwed)D(e,n,t);if(t.version>=C)throw s.store(`version of ${t.epoch} would pass 2^53 - 1`);return t.version+=1,t.version}function Ge(e,n){let t=e.record(n.name);if(t!==null)return t;let r={epoch:We(n,null),version:0,floor:0,dirty:!0,rotatedAt:n.env.nowMs(),reconciledAt:0,rotateOwed:!1};return e.putRecord(n.name,r),r}function Re(e,n){let t=e.env.nowMs();return n.rotatedAt===0||t<n.rotatedAt||t-n.rotatedAt>=ze}function ve(e,n,t){if(Re(n,t))return D(e,n,t),!0;return t.rotateOwed=!0,!1}function Ke(e,n,t,r){if(r||t.rotateOwed&&Re(n,t))return D(e,n,t),!0;return!1}function Je(e,n){return!(n.rotateOwed&&Re(e,n))}function D(e,n,t){let r=n.env.nowMs(),o=0;for(let i of e.entries(n.name)){if(i.deleted){e.deleteEntry(n.name,i.key);continue}o+=1,e.putEntry(n.name,{...i,version:o,changedAt:r})}t.epoch=We(n,t.epoch),t.version=o,t.floor=0,t.rotatedAt=r,t.rotateOwed=!1}function Ze(e,n,t,r,o,i){let a=e.entry(n.name,r.key);if(a!==null&&!a.deleted&&a.digest===o)return!1;let u=Z(e,n,t);return e.putEntry(n.name,{key:r.key,digest:o,version:u,deleted:!1,changedAt:i}),!0}function Qe(e,n,t,r,o){let i=e.entry(n.name,r);if(i===null||i.deleted)return!1;let a=Z(e,n,t);return e.putEntry(n.name,{key:r,digest:i.digest,version:a,deleted:!0,changedAt:o}),!0}function be(e,n,t,r){let o=e.pruneTombstones(n.name,Math.max(0,r-n.horizon.maxAgeMs),n.horizon.maxCount);if(o.highest!==null)t.floor=Math.max(t.floor,o.highest);if(o.overKeep)ve(e,n,t)}function Ee(e,n,t,r){let o=n.env.nowMs(),i=r.map((c)=>({row:c,digest:we(c)}));i.sort((c,h)=>T(c.row.key,h.row.key));for(let c=1;c<i.length;c+=1){let h=i[c-1],f=i[c];if(h!==void 0&&f!==void 0&&h.row.key===f.row.key)throw s.row(h.row.key,"the key appears twice in the list")}let a=e.entries(n.name),u=[],d=[],l=0;for(let c of i){while(l<a.length&&T(P(a,l).key,c.row.key)<0){let f=P(a,l);if(!f.deleted)d.push(f);l+=1}let h=!1;if(l<a.length&&P(a,l).key===c.row.key){let f=P(a,l);h=!f.deleted&&f.digest===c.digest,l+=1}if(!h)u.push(c)}for(;l<a.length;l+=1){let c=P(a,l);if(!c.deleted)d.push(c)}for(let{row:c,digest:h}of u){let f=Z(e,n,t);e.putEntry(n.name,{key:c.key,digest:h,version:f,deleted:!1,changedAt:o})}for(let c of d){let h=Z(e,n,t);e.putEntry(n.name,{key:c.key,digest:c.digest,version:h,deleted:!0,changedAt:o})}be(e,n,t,o),t.dirty=!1,t.reconciledAt=o}function P(e,n){let t=e[n];if(t===void 0)throw s.store("ledger index out of range");return t}function en(e,n,t,r){let o=we(r),i=n.env.nowMs();Ze(e,n,t,r,o,i),be(e,n,t,i)}function nn(e,n,t,r){let o=G(r);if(o!==null)throw s.row(r,o);let i=n.env.nowMs();Qe(e,n,t,r,i),be(e,n,t,i)}function I(e,n,t,r,o){return{kind:"full-copy",version:r,entries:e.liveAfter(n.name,t,o)}}function $n(e,n,t,r){let o=pe(r)+1;if(r.epoch!==t.epoch)return I(e,n,null,t.version,o);if(r.version>t.version)return D(e,n,t),I(e,n,null,t.version,o);if(r.resume!==void 0){if(r.version>=t.floor)return I(e,n,r.resume,r.version,o);return I(e,n,null,t.version,o)}if(r.version<t.floor)return I(e,n,null,t.version,o);if(r.version===t.version)return{kind:"nothing-new"};return{kind:"changes",entries:e.changesAfter(n.name,r.version,o)}}function On(e,n,t,r,o){let i=n.env.nowMs(),a=!1;for(let u of r){if(u.deleted)continue;let d=o.get(u.key);if(d===void 0)a=Qe(e,n,t,u.key,i)||a;else{let l=we(d);if(l!==u.digest)a=Ze(e,n,t,d,l,i)||a}}return a}function xe(e,n){if(!e.schemas.includes(n.schema))throw s.schema(e.name,n.schema);let t=Ce(n);if(t!==null)throw s.request(t)}function je(e,n){let t;try{t=e(n)}catch(r){throw s.load(w(r))}return t.map(F)}function tn(e,n,t,r,o){if(xe(n,r),t.dirty)Ee(e,n,t,je(o,null));let i=pe(r),a=!1,u=0;for(;;){let d=a?I(e,n,null,t.version,i+1):$n(e,n,t,r);if(d.kind==="nothing-new")return{kind:"nothing-new",epoch:t.epoch,version:t.version};let l=d.entries.slice(0,i),c=l.filter((E)=>!E.deleted).map((E)=>E.key),h=new Map;if(c.length>0){let E=new Set(c);for(let N of je(o,c))if(E.has(N.key))h.set(N.key,N)}if(u<2&&On(e,n,t,l,h)){u+=1;continue}let f=_n(t,r,d,i,h);if(f!==null)return f;if(a)throw s.store("a full copy could not be built");a=!0}}function _n(e,n,t,r,o){if(t.kind==="changes"){let c=[],h=0,f=!1;for(let m of t.entries){if(c.length===r){f=!0;break}let H=o.get(m.key),Oe=m.deleted?Ie(m.key):H!==void 0?ye(H):0;if(c.length>0&&h+Oe>fe){f=!0;break}h+=Oe,c.push(m)}let E;if(f){let m=0;while(m<c.length&&c[m]?.version===n.version+m+1)m+=1;if(m===0)return null;c.length=m,E=n.version+m}else E=e.version;let N=[],$e=[];for(let m of c){if(m.deleted){$e.push(m.key);continue}let H=o.get(m.key);if(H!==void 0)N.push(H)}return{kind:"changes",epoch:e.epoch,version:E,upserts:N,deletes:$e,more:f}}let i=[],a=0,u=null,d=!1;for(let c=0;c<t.entries.length;c+=1){let h=P(t.entries,c);if(c===r){d=!0;break}let f=o.get(h.key);if(f===void 0){u=h.key;continue}let E=ye(f);if(c>0&&a+E>fe){d=!0;break}i.push(f),a+=E,u=h.key}let l={kind:"full-copy",epoch:e.epoch,version:t.version,rows:i};if(d&&u!==null)l.next=u;if(e.version>t.version)l.head=e.version;return l}function sn(e,n,t){if(e.readRecord!==void 0)return e.readRecord(n,t);let r=null;return e.write(n,(o)=>{r=o.record(t)}),r}function Nn(e){let n=new Map;for(let[t,r]of e.entries)n.set(t,{...r});return{record:e.record===null?null:{...e.record},entries:n}}function rn(e){let n=new Map;for(let[t,r]of e)n.set(t,Nn(r));return n}function on(e){if(e===void 0)return[];return[...e.entries.values()].sort((n,t)=>T(n.key,t.key))}class an{prefix;tables;undo=[];saved=new Set;constructor(e,n){this.prefix=e;this.tables=n}rollback(){for(let e=this.undo.length-1;e>=0;e-=1)this.undo[e]?.()}name(e){return`${this.prefix}\x00${e}`}get(e){return this.tables.get(this.name(e))}getMut(e){let n=this.name(e),t=this.tables.get(n);if(t===void 0)t={record:null,entries:new Map},this.tables.set(n,t),this.undo.push(()=>this.tables.delete(n));return t}saveRecord(e){let n=this.getMut(e),t=`r\x00${this.name(e)}`;if(!this.saved.has(t)){this.saved.add(t);let r=n.record;this.undo.push(()=>{n.record=r})}return n}saveEntry(e,n,t){let r=`e\x00${this.name(n)}\x00${t}`;if(this.saved.has(r))return;this.saved.add(r);let o=e.entries.get(t);this.undo.push(()=>{if(o===void 0)e.entries.delete(t);else e.entries.set(t,o)})}record(e){let n=this.get(e)?.record;return n?{...n}:null}putRecord(e,n){this.saveRecord(e).record={...n}}entry(e,n){let t=this.get(e)?.entries.get(n);return t?{...t}:null}entries(e){return on(this.get(e)).map((n)=>({...n}))}putEntry(e,n){let t=this.getMut(e);this.saveEntry(t,e,n.key),t.entries.set(n.key,{...n})}deleteEntry(e,n){let t=this.getMut(e);this.saveEntry(t,e,n),t.entries.delete(n)}changesAfter(e,n,t){let r=this.get(e);if(r===void 0)return[];return[...r.entries.values()].filter((o)=>o.version>n).sort((o,i)=>o.version-i.version).slice(0,t).map((o)=>({...o}))}liveAfter(e,n,t){return on(this.get(e)).filter((r)=>!r.deleted&&(n===null||T(r.key,n)>0)).slice(0,t).map((r)=>({...r}))}pruneTombstones(e,n,t){let r=this.getMut(e),o=r.entries,i=[...o.values()].filter((l)=>l.deleted).sort((l,c)=>l.version-c.version||l.changedAt-c.changedAt||T(l.key,c.key)),a=Math.max(0,i.length-t),u=null,d=0;return i.forEach((l,c)=>{if(c<a||l.changedAt<n)this.saveEntry(r,e,l.key),o.delete(l.key),u=u===null?l.version:Math.max(u,l.version);else d+=1}),{highest:u,overKeep:d>t}}}class ke{tables=new Map;ensure(){}write(e,n){let t=new an(e,this.tables);try{n(t)}catch(r){throw t.rollback(),r}}readRecord(e,n){let t=this.tables.get(`${e}\x00${n}`)?.record;return t?{...t}:null}clone(){let e=new ke;return e.tables=rn(this.tables),e}restoreFrom(e){this.tables=rn(e.tables)}}var dn={nowMs:()=>Date.now(),newEpoch:Cn},cn="abcdefghijklmnopqrstuvwxyz0123456789",ln=0;function Cn(){let e=new Uint8Array(8),n=globalThis.crypto;if(n?.getRandomValues!==void 0)n.getRandomValues(e);else{ln+=1;let r=Date.now()+ln;for(let o=0;o<e.length;o+=1)e[o]=Math.floor(Math.random()*256)^r>>>o%4*8&255}let t="";for(let r of e)t+=cn.charAt(r%cn.length);return t}var Pn=16,In=/^[a-z][a-z0-9_-]*$/,Dn=/^(?:[A-Za-z_][A-Za-z0-9_]{0,47})?$/;class Q{store;name;tablePrefix;schemas;spec;announceFailing=!1;handedOutMarks=[];constructor(e,n,t={}){this.store=e;this.name=n,this.tablePrefix=t.tablePrefix??"",this.schemas=[...t.schemas??[1]],this.spec={name:n,schemas:this.schemas,env:t.env??dn,horizon:t.horizon??me}}check(){let e=this.name.split(".");if(e.length<3||e[e.length-1]!=="pull"||!e.every((n)=>In.test(n)))throw s.config(`'${this.name}' is not a pull capability '<app>.<collection>.pull'`);if(this.name.startsWith("core."))throw s.config(`'${this.name}' is in the reserved 'core.' namespace`);if(!Dn.test(this.tablePrefix))throw s.config(`table prefix '${this.tablePrefix}' must be [A-Za-z_][A-Za-z0-9_]{0,47} or empty`);if(!(this.spec.horizon.maxCount>=1))throw s.config("the tombstone horizon must keep at least one tombstone");if(!this.schemas.every((n)=>Number.isInteger(n)&&n>=0&&n<=4294967295))throw s.config("schemas must be integers from 0 to 4294967295")}handedOut(e){return this.handedOutMarks.find(([n])=>n===e)?.[1]}noteHandedOut(e,n){let t=this.handedOutMarks.findIndex(([o])=>o===e),r=n;if(t>=0){let[o]=this.handedOutMarks.splice(t,1);if(o!==void 0)r=Math.max(o[1],n)}this.handedOutMarks.unshift([e,r]),this.handedOutMarks.length=Math.min(this.handedOutMarks.length,Pn)}wentBack(e){let n=this.handedOut(e.epoch);return n!==void 0&&n>e.version}withRecord(e){this.check();let n=null;if(this.store.write(this.tablePrefix,(t)=>{let r=Ge(t,this.spec),o={...r},i=Ke(t,this.spec,r,this.wentBack(r)),a=e(t,r,i);if(!Hn(r,o))t.putRecord(this.spec.name,r);n={value:a}}),n===null)throw s.store("the store did not run the ledger work");return n.value}readSettled(){this.check();let e=sn(this.store,this.tablePrefix,this.name);if(e===null||this.wentBack(e)||!Je(this.spec,e))return null;return e}ensure(){this.check(),this.store.ensure(this.tablePrefix)}reconcile(e){let n=e.map(F);return this.withRecord((t,r)=>{let o=L(r);return Ee(t,this.spec,r,n),q(L(r),o)?null:r.version})}touch(e){let n=F(e);return this.withRecord((t,r)=>(en(t,this.spec,r,n),r.version))}remove(e){return this.withRecord((n,t)=>(nn(n,this.spec,t,e),t.version))}markDirty(){this.withRecord((e,n)=>{n.dirty=!0})}reset(){return this.withRecord((e,n,t)=>{let r=t||ve(e,this.spec,n);return n.dirty=!0,r})}head(){let e=this.readSettled();if(e!==null)return L(e);return this.withRecord((n,t)=>L(t))}answer(e,n){if(xe(this.spec,e),e.resume===void 0){let o=this.readSettled();if(o!==null&&!o.dirty&&o.epoch===e.epoch&&o.version===e.version)return this.noteHandedOut(o.epoch,o.version),{reply:{kind:"nothing-new",epoch:o.epoch,version:o.version},headMoved:!1}}let{answered:t,head:r}=this.withRecord((o,i,a)=>{let u=L(i),d=tn(o,this.spec,i,e,n),l=L(i);return{answered:{reply:d,headMoved:a||!q(l,u)},head:l}});return this.noteHandedOut(r.epoch,r.version),t}pull(e,n){return JSON.parse(K(this.answer(J(e),n).reply))}async announce(e){try{let n=await this.announceInner(e);return this.announceFailing=!1,n}catch(n){let t=!this.announceFailing;return this.announceFailing=!0,{kind:"failed",error:w(n),first:t}}}async announceInner(e){let n=this.head();if(await un(this.name,n,e)==="ok")return this.noteHandedOut(n.epoch,n.version),{kind:"accepted",head:n};this.noteHandedOut(n.epoch,n.version+1);let t=this.withRecord((r,o,i)=>{if(!i&&o.epoch===n.epoch)D(r,this.spec,o);return L(o)});if(await un(this.name,t,e)==="ok")return this.noteHandedOut(t.epoch,t.version),{kind:"rotated",head:t};return{kind:"rotation-deferred",head:t}}description(){return`Replicated collection served by @econ-v1/app-sdk/replica (Phase 3 contract). Request {"e":<epoch held, "" for none>,"v":<version held>,"s":<schema>,"l":<row limit, at most 500>,"a":<resume key, optional>}. Reply {"e","v"} when nothing is new; {"e","v","u":[[key,value,ord?,part?]...],"x":[key...],"m":1?} with the changes since v; or {"e","v","f":1,"u":[...],"n":<next key>?}, a full copy in key order. Schemas served: ${this.schemas.join(", ")}. Called by the node (core.replica.sync), not by devices.`}}function Hn(e,n){return e.epoch===n.epoch&&e.version===n.version&&e.floor===n.floor&&e.dirty===n.dirty&&e.rotatedAt===n.rotatedAt&&e.reconciledAt===n.reconciledAt&&e.rotateOwed===n.rotateOwed}async function un(e,n,t){let r=JSON.parse(Fe({capability:e,epoch:n.epoch,version:n.version})),o=await t(Ne,r);try{return Xe(o)}catch(i){throw Error(`unexpected announce reply: ${w(i)}`)}}var ee=2;function Ae(e){return{meta:`${e}replica_meta`,collections:`${e}replica_collections`,rows:`${e}replica_rows`}}function Un(e,n){e.exec(`CREATE TABLE IF NOT EXISTS ${n.collections} (
3
+ name TEXT PRIMARY KEY NOT NULL,
4
+ epoch TEXT NOT NULL,
5
+ version INTEGER NOT NULL DEFAULT 0,
6
+ floor INTEGER NOT NULL DEFAULT 0,
7
+ dirty INTEGER NOT NULL DEFAULT 1,
8
+ rotated_at INTEGER NOT NULL DEFAULT 0,
9
+ reconciled_at INTEGER NOT NULL DEFAULT 0
10
+ )`),e.exec(`CREATE TABLE IF NOT EXISTS ${n.rows} (
11
+ collection TEXT NOT NULL,
12
+ row_key TEXT NOT NULL,
13
+ digest TEXT NOT NULL,
14
+ version INTEGER NOT NULL,
15
+ deleted INTEGER NOT NULL DEFAULT 0,
16
+ changed_at INTEGER NOT NULL,
17
+ PRIMARY KEY (collection, row_key)
18
+ )`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_version ON ${n.rows} (collection, version)`)}function Fn(e,n){e.exec(`ALTER TABLE ${n.collections} ADD COLUMN rotate_owed INTEGER NOT NULL DEFAULT 0`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_tombstone_version ON ${n.rows} (collection, version)
19
+ WHERE deleted = 1`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_tombstone_age ON ${n.rows} (collection, changed_at)
20
+ WHERE deleted = 1`)}var qn=[Fn];function V(e,n){if(typeof e==="number"&&Number.isSafeInteger(e))return e;if(typeof e==="bigint"&&e>=0n&&e<=BigInt(Number.MAX_SAFE_INTEGER))return Number(e);throw s.store(`${n} in the replica ledger is not an integer within 2^53 - 1: ${String(e)}`)}function S(e,n){let t=V(e,n);if(t<0)throw s.store(`negative ${t} in the replica ledger`);return t}function Le(e,n){if(typeof e!=="string")throw s.store(`${n} in the replica ledger is not text`);return e}function v(e,n){if(typeof e!=="object"||e===null)throw s.store("the replica ledger returned a non-row");return e[n]}var hn="epoch, version, floor, dirty, rotated_at, reconciled_at, rotate_owed",B="row_key, digest, version, deleted, changed_at";function Bn(e){return{epoch:Le(v(e,"epoch"),"an epoch"),version:S(v(e,"version"),"a version"),floor:S(v(e,"floor"),"a floor"),dirty:V(v(e,"dirty"),"dirty")!==0,rotatedAt:S(v(e,"rotated_at"),"rotated_at"),reconciledAt:S(v(e,"reconciled_at"),"reconciled_at"),rotateOwed:V(v(e,"rotate_owed"),"rotate_owed")!==0}}function X(e){return{key:Le(v(e,"row_key"),"a row key"),digest:Le(v(e,"digest"),"a digest"),version:S(v(e,"version"),"a version"),deleted:V(v(e,"deleted"),"deleted")!==0,changedAt:S(v(e,"changed_at"),"changed_at")}}function Te(e){try{return e()}catch(n){if(n instanceof s)throw n;throw s.store(w(n))}}class fn{store;t;constructor(e,n){this.store=e;this.t=n}q(e){return this.store.statement(e)}record(e){return this.store.readRecordIn(this.t,e)}putRecord(e,n){this.q(`INSERT INTO ${this.t.collections} (name, ${hn})
21
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
22
+ ON CONFLICT(name) DO UPDATE SET epoch = excluded.epoch, version = excluded.version,
23
+ floor = excluded.floor, dirty = excluded.dirty, rotated_at = excluded.rotated_at,
24
+ reconciled_at = excluded.reconciled_at, rotate_owed = excluded.rotate_owed`).run(e,n.epoch,n.version,n.floor,n.dirty?1:0,n.rotatedAt,n.reconciledAt,n.rotateOwed?1:0)}entry(e,n){let t=this.q(`SELECT ${B} FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).get(e,n);return t===null||t===void 0?null:X(t)}entries(e){return this.q(`SELECT ${B} FROM ${this.t.rows} WHERE collection = ?1 ORDER BY row_key`).all(e).map(X)}putEntry(e,n){this.q(`INSERT INTO ${this.t.rows} (collection, row_key, digest, version, deleted, changed_at)
25
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)
26
+ ON CONFLICT(collection, row_key) DO UPDATE SET digest = excluded.digest,
27
+ version = excluded.version, deleted = excluded.deleted, changed_at = excluded.changed_at`).run(e,n.key,n.digest,n.version,n.deleted?1:0,n.changedAt)}deleteEntry(e,n){this.q(`DELETE FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).run(e,n)}changesAfter(e,n,t){return this.q(`SELECT ${B} FROM ${this.t.rows} WHERE collection = ?1 AND version > ?2
28
+ ORDER BY version LIMIT ?3`).all(e,n,t).map(X)}liveAfter(e,n,t){if(n===null)return this.q(`SELECT ${B} FROM ${this.t.rows} WHERE collection = ?1 AND deleted = 0
29
+ ORDER BY row_key LIMIT ?2`).all(e,t).map(X);return this.q(`SELECT ${B} FROM ${this.t.rows} WHERE collection = ?1 AND deleted = 0
30
+ AND row_key > ?2 ORDER BY row_key LIMIT ?3`).all(e,n,t).map(X)}pruneTombstones(e,n,t){let r=this.t.rows,o=this.q(`SELECT MAX(version) AS highest FROM ${r} WHERE collection = ?1 AND deleted = 1 AND changed_at < ?2`).get(e,n),i=v(o,"highest"),a=i===null||i===void 0?null:S(i,"a version");if(a!==null)this.q(`DELETE FROM ${r} WHERE collection = ?1 AND deleted = 1 AND changed_at < ?2`).run(e,n);let u=this.q(`SELECT version FROM ${r} WHERE collection = ?1 AND deleted = 1 ORDER BY version DESC LIMIT 1 OFFSET ?2`).get(e,t),d=u===null||u===void 0?null:S(v(u,"version"),"a version");if(d!==null)this.q(`DELETE FROM ${r} WHERE collection = ?1 AND deleted = 1 AND version <= ?2`).run(e,d);return{highest:a===null?d:d===null?a:Math.max(a,d),overKeep:!1}}}var j="node_app_replica";class ne{db;statements=new Map;constructor(e){this.db=e}statement(e){let n=this.statements.get(e);if(n===void 0)n=this.db.query(e),this.statements.set(e,n);return n}inTransaction(e){let n=this.begin(),t;try{t=e(),this.db.exec(n?`RELEASE ${j}`:"COMMIT")}catch(r){try{if(this.db.exec(n?`ROLLBACK TO ${j}`:"ROLLBACK"),n)this.db.exec(`RELEASE ${j}`)}catch{}if(r instanceof s)throw r;throw s.store(w(r))}return t}begin(){if(this.db.inTransaction===!0)return Te(()=>this.db.exec(`SAVEPOINT ${j}`)),!0;try{return this.db.exec("BEGIN IMMEDIATE"),!1}catch(e){if(this.db.inTransaction===void 0&&this.insideAppTransaction())return Te(()=>this.db.exec(`SAVEPOINT ${j}`)),!0;throw s.store(w(e))}}insideAppTransaction(){try{this.db.exec("BEGIN DEFERRED")}catch{return!0}try{this.db.exec("ROLLBACK")}catch{}return!1}ensure(e){let n=Ae(e);this.inTransaction(()=>this.bringUp(n))}bringUp(e){this.db.exec(`CREATE TABLE IF NOT EXISTS ${e.meta} (key TEXT PRIMARY KEY NOT NULL, value INTEGER NOT NULL)`);let n=this.db.query(`SELECT value FROM ${e.meta} WHERE key = 'layout'`).get(),t;if(n!==null&&n!==void 0)t=V(v(n,"value"),"the layout");else if(this.db.query("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?1").get(e.collections))t=1;else Un(this.db,e),t=1;if(t<1||t>ee)throw s.store(`the replica ledger's layout is ${t}; this helper knows layouts 1 to ${ee}`);while(t<ee){let r=qn[t-1];if(r===void 0)throw s.store(`no upgrade from layout ${t}`);r(this.db,e),t+=1}this.db.query(`INSERT INTO ${e.meta} (key, value) VALUES ('layout', ?1)
31
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(t),this.statements.clear()}write(e,n){let t=Ae(e);this.inTransaction(()=>n(new fn(this,t)))}readRecordIn(e,n){let t=this.statement(`SELECT ${hn} FROM ${e.collections} WHERE name = ?1`).get(n);return t===null||t===void 0?null:Bn(t)}readRecord(e,n){return Te(()=>this.readRecordIn(Ae(e),n))}}function Xn(e){return typeof e.write==="function"&&typeof e.ensure==="function"}var pn=0;function Pt(e,n=5000){return async(t,r)=>{pn+=1;let o=`replica-${Date.now().toString(36)}-${pn.toString(36)}`,i=await e({id:o,capability:t,payload:r},n);if(!i.success)throw Error(w(i.payload));return i.payload}}var jn=2000,Vn=60000;class Se{firstMs;maxMs;job;timer=null;delay;stopped=!1;constructor(e,n,t){this.firstMs=e;this.maxMs=n;this.job=t;this.delay=e}failed(){if(this.stopped||this.timer!==null)return;this.timer=setTimeout(()=>{this.timer=null,this.job()},this.delay),this.delay=Math.min(this.delay*2,this.maxMs)}succeeded(){this.cancel(),this.delay=this.firstMs}pending(){return this.timer!==null}cancel(){if(this.timer!==null)clearTimeout(this.timer);this.timer=null}stop(){this.stopped=!0,this.cancel()}}class gn{ledger;options;invoke;warn;coalesceMs;name;timer=null;announcing=null;announceAgain=!1;announced=null;reconcileFailing=!1;reconcileRetry;announceRetry;constructor(e,n,t,r,o,i){this.ledger=e;this.options=n;this.invoke=t;this.warn=r;this.coalesceMs=o;this.name=e.name,this.reconcileRetry=new Se(i.firstMs,i.maxMs,()=>this.reconcileNow()),this.announceRetry=new Se(i.firstMs,i.maxMs,()=>void this.announce())}load(e){if(e===null)return this.options.list();if(this.options.get!==void 0)return this.options.get(e);let n=new Set(e);return this.options.list().filter((t)=>n.has(t.key))}changed(){try{this.ledger.markDirty()}catch(e){this.warn(`replica: ${this.name}: ${w(e)}`)}if(this.timer!==null)return;this.timer=setTimeout(()=>{this.timer=null,this.reconcileNow()},this.coalesceMs)}reconcileNow(){try{this.ledger.reconcile(this.options.list())}catch(e){if(!this.reconcileFailing)this.warn(`replica: reconciling ${this.name} failed (retrying with backoff): ${w(e)}`);this.reconcileFailing=!0,this.reconcileRetry.failed();return}this.reconcileFailing=!1,this.reconcileRetry.succeeded(),this.afterWrite()}touch(e){this.ledger.touch(e),this.afterWrite()}remove(e){this.ledger.remove(e),this.afterWrite()}reset(){this.ledger.reset(),this.afterWrite(),this.changed()}head(){return this.ledger.head()}afterWrite(){let e;try{e=this.ledger.head()}catch(n){this.warn(`replica: ${this.name}: ${w(n)}`),this.announceRetry.failed();return}if(this.announced===null||!q(e,this.announced))this.announce()}announce(){if(this.announceAgain=!0,this.announcing===null)this.announcing=this.runAnnounces();return this.announcing}async runAnnounces(){try{await Promise.resolve();while(this.announceAgain){this.announceAgain=!1;try{this.note(await this.ledger.announce(this.invoke))}catch(e){this.warn(`replica: announcing ${this.name} failed: ${w(e)}`),this.announceRetry.failed()}}}finally{this.announcing=null}}note(e){switch(e.kind){case"accepted":case"rotated":this.announced=e.head,this.announceRetry.succeeded();return;case"rotation-deferred":this.announced=null,this.announceRetry.failed();return;case"failed":if(e.first)this.warn(`replica: announcing ${this.name} failed (retrying with backoff; until an announce lands the node answers "nothing new" from the head it remembers, so devices do not see the change; an older node has no core.replica.announce): ${e.error}`);this.announceRetry.failed();return}}retrying(){return this.reconcileRetry.pending()||this.announceRetry.pending()}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.reconcileNow();while(this.announcing!==null)await this.announcing}stop(){if(this.timer!==null)clearTimeout(this.timer);this.timer=null,this.reconcileRetry.stop(),this.announceRetry.stop()}}class Yn{invoke;options;store;collections=new Map;tablePrefix;warn;constructor(e,n,t={}){this.invoke=n;this.options=t;this.store=Xn(e)?e:new ne(e),this.tablePrefix=t.tablePrefix??"",this.warn=t.warn??((r)=>console.warn(r))}collection(e,n){if(this.collections.has(e))throw s.config(`'${e}' is declared twice`);let t={tablePrefix:this.tablePrefix,schemas:n.schemas??[1],...this.options.env===void 0?{}:{env:this.options.env},...this.options.horizon===void 0?{}:{horizon:this.options.horizon}},r=new Q(this.store,e,t);r.ensure();let o={firstMs:this.options.retry?.firstMs??jn,maxMs:this.options.retry?.maxMs??Vn},i=new gn(r,n,this.invoke,this.warn,this.options.coalesceMs??50,o);return this.collections.set(e,i),i}provides(){return[...this.collections.values()].map((e)=>({name:e.name,description:e.ledger.description()}))}handles(e){return this.collections.has(e)}handle(e,n){try{let t=this.collections.get(e);if(t===void 0)throw s.request(`${e} is not a replicated collection of this app`);let r=t.ledger.answer(J(n),(o)=>t.load(o));if(r.headMoved)t.announce();return Promise.resolve(JSON.parse(K(r.reply)))}catch(t){return Promise.reject(t instanceof Error?t:Error(w(t)))}}async start(){await Promise.all([...this.collections.values()].map((e)=>e.announce()))}async flush(){await Promise.all([...this.collections.values()].map((e)=>e.flush()))}retrying(){return[...this.collections.values()].some((e)=>e.retrying())}stop(){for(let e of this.collections.values())e.stop()}}export{Ne as ANNOUNCE_CAPABILITY,Q as CollectionLedger,me as DEFAULT_HORIZON,ee as LEDGER_LAYOUT,Jn as MAX_EPOCH_CHARS,Me as MAX_KEY_BYTES,de as MAX_PART_BYTES,fe as MAX_REPLY_ROW_BYTES,he as MAX_ROWS_PER_REPLY,C as MAX_SAFE_INTEGER,Zn as MAX_SYNC_ENTRIES,Qn as MAX_SYNC_REPLY_BYTES,ue as MAX_VALUE_BYTES,oe as MAX_VALUE_DEPTH,ke as MemoryLedger,O as REPLICA_ERROR_PREFIXES,ze as ROTATION_MIN_INTERVAL_MS,Yn as Replica,s as ReplicaError,nt as SCHEMA_UNSUPPORTED_PREFIX,et as SYNC_CAPABILITY,ne as SqliteLedgerStore,Ve as TOMBSTONE_MAX_AGE_MS,Ye as TOMBSTONE_MAX_COUNT,Y as canonicalJson,En as canonicalValue,T as compareUtf8,gt as decodeAnnounce,Xe as decodeAnnounceReply,yt as decodeHeadsData,ht as decodePullReply,J as decodePullRequest,Tn as decodeRow,Sn as decodeSyncAnswer,Ln as decodeSyncEntry,pt as decodeSyncReply,ft as decodeSyncRequest,pe as effectiveLimit,Fe as encodeAnnounce,ut as encodeAnnounceReply,dt as encodeHeadsData,K as encodePullReply,at as encodePullRequest,Pe as encodeRow,An as encodeSyncAnswer,kn as encodeSyncEntry,lt as encodeSyncReply,ct as encodeSyncRequest,Ie as encodedDeleteBytes,ye as encodedRowBytes,wn as fnv1a64,rt as handedOut,Pt as hostInvoke,tt as initialPullRequest,ge as isEpoch,ot as isTruncated,ie as isWithinValueDepth,G as keyProblem,it as pullRequestOf,Ce as pullRequestProblem,Rn as rowDigest,st as syncAnswerOf,dn as systemEnvironment,F as toRow,_ as utf8Length};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@econ-v1/app-sdk",
3
- "version": "7.6.222",
3
+ "version": "7.6.223",
4
4
  "description": "TypeScript SDK for building Node mini-app plugins (Bun runtime) on the Lightning-powered marketplace daemon",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": "Node contributors",
@@ -30,6 +30,10 @@
30
30
  "burger": "./dist/burger/index.js",
31
31
  "default": "./dist/index.js"
32
32
  },
33
+ "./replica": {
34
+ "types": "./dist/replica.d.ts",
35
+ "default": "./dist/replica.js"
36
+ },
33
37
  "./burger-build": {
34
38
  "types": "./dist/burger-build/index.d.ts",
35
39
  "default": "./dist/burger-build/index.js"
@@ -72,7 +76,7 @@
72
76
  "bun": ">=1.0"
73
77
  },
74
78
  "scripts": {
75
- "build": "rm -rf dist && bun build src/index.ts --outdir dist --target=bun --minify && bun run build:burger && tsc --emitDeclarationOnly --declaration --outDir dist && bun run build:toolchain",
79
+ "build": "rm -rf dist && bun build src/index.ts src/replica.ts --outdir dist --target=bun --minify && bun run build:burger && tsc --emitDeclarationOnly --declaration --outDir dist && bun run build:toolchain",
76
80
  "build:burger": "bun ../burger-build/src/cli.ts build src/index.ts --outdir dist/burger",
77
81
  "build:toolchain": "bun scripts/build-burger-toolchain.ts",
78
82
  "prepublishOnly": "npm run build",