@econ-v1/app-sdk 7.7.39 → 7.7.41
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.
|
@@ -75,9 +75,10 @@ export declare class CollectionLedger {
|
|
|
75
75
|
private wentBack;
|
|
76
76
|
/**
|
|
77
77
|
* Runs `work` on this collection's record in one write transaction and writes
|
|
78
|
-
* the record back
|
|
79
|
-
* the
|
|
80
|
-
* told whether that
|
|
78
|
+
* the record back when it changed: a pass that changes nothing writes nothing.
|
|
79
|
+
* Before the work, a database that went back in time rotates the epoch, and so
|
|
80
|
+
* does an owed rotation whose minute has passed; `work` is told whether that
|
|
81
|
+
* happened.
|
|
81
82
|
*/
|
|
82
83
|
private withRecord;
|
|
83
84
|
/**
|
package/dist/replica/ledger.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* TypeScript: the same plan, the same cut, the same rotation rules. One thing is
|
|
5
5
|
* done elsewhere: rows are checked before the transaction (see {@link checkRows}).
|
|
6
6
|
*/
|
|
7
|
-
import type
|
|
7
|
+
import { type CollectionRecord, type LedgerTx } from "./store.js";
|
|
8
8
|
import { type PullReply, type PullRequest, type ReplicaRow, type Row } from "./wire.js";
|
|
9
9
|
/** How long, and how many, tombstones are kept (section 4.7). */
|
|
10
10
|
export interface Horizon {
|
|
@@ -87,6 +87,9 @@ export declare function rotateNow(tx: LedgerTx, spec: Spec, record: CollectionRe
|
|
|
87
87
|
* Whole-list mode: `rows` is every current row. A new key or a changed digest
|
|
88
88
|
* gets the next version; a ledger key missing from `rows` becomes a tombstone at
|
|
89
89
|
* the next version. The rows were all checked before anything is written.
|
|
90
|
+
*
|
|
91
|
+
* A pass that changes nothing writes nothing: `reconciledAt` moves only together
|
|
92
|
+
* with another change to the record, so it never causes a write alone.
|
|
90
93
|
*/
|
|
91
94
|
export declare function reconcile(tx: LedgerTx, spec: Spec, record: CollectionRecord, rows: readonly CheckedRow[]): void;
|
|
92
95
|
export declare function touch(tx: LedgerTx, spec: Spec, record: CollectionRecord, { row, digest }: CheckedRow): void;
|
package/dist/replica/store.d.ts
CHANGED
|
@@ -28,7 +28,12 @@ export interface CollectionRecord {
|
|
|
28
28
|
dirty: boolean;
|
|
29
29
|
/** Unix ms of the last epoch rotation. */
|
|
30
30
|
rotatedAt: number;
|
|
31
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* Unix ms of the last reconcile that changed the record (a new version or
|
|
33
|
+
* epoch, the floor, an owed rotation, `dirty` cleared). A reconcile that
|
|
34
|
+
* changes nothing leaves it, so the record is never written for it alone: a
|
|
35
|
+
* pass that changes nothing writes nothing.
|
|
36
|
+
*/
|
|
32
37
|
reconciledAt: number;
|
|
33
38
|
/**
|
|
34
39
|
* A rotation was asked for within a minute of the last one and is still to
|
|
@@ -37,6 +42,8 @@ export interface CollectionRecord {
|
|
|
37
42
|
*/
|
|
38
43
|
rotateOwed: boolean;
|
|
39
44
|
}
|
|
45
|
+
/** Whether two headers hold the same values, every field compared. */
|
|
46
|
+
export declare function sameRecord(a: CollectionRecord, b: CollectionRecord): boolean;
|
|
40
47
|
/** One row of the ledger (`replica_rows`): a key and what is known about it, never its value. */
|
|
41
48
|
export interface LedgerEntry {
|
|
42
49
|
key: string;
|
package/dist/replica.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var N={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 An(e){return typeof e==="string"?Array.from(e).slice(0,64).join(""):""}class a 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 a("config",`${N.config} ${e}`,e)}static row(e,n){let t=An(e);return new a("row",`${N.row} row '${t}': ${n}`,n,t)}static request(e){return new a("request",`${N.request} ${e}`,e)}static schema(e,n){let t=`schema ${n} is not served by ${e}`;return new a("schema",`${N.schema} ${t}`,t)}static load(e){return new a("load",`${N.load} ${e}`,e)}static store(e){return new a("store",`${N.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)}}import{createHash as Tn}from"crypto";function L(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}var Ln=new TextEncoder;function O(e){if(e.length>128)return Ln.encode(e).length;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&&de(e.charCodeAt(t+1)))n+=4,t+=1;else n+=3}return n}function de(e){return e>=56320&&e<=57343}function B(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t<55296||t>57343)continue;if(t<=56319&&de(e.charCodeAt(n+1))){n+=1;continue}return!0}return!1}var K=128;function Sn(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>=K)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 $n="value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";class k extends Error{}function Ie(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Pe(e,n){if(B(e))throw new k(`${n} holds a lone surrogate`);return JSON.stringify(e)}function ce(e,n,t){switch(typeof e){case"string":return Pe(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>=K)throw new k($n);if(Array.isArray(e)){let i=[];for(let s=0;s<e.length;s+=1){let l=e[s];if(l===void 0)throw new k(`${n}[${s}] is undefined`);i.push(ce(l,`${n}[${s}]`,t+1))}return`[${i.join(",")}]`}if(!Ie(e))throw new k(`${n} is not a plain object`);let r=Object.keys(e).filter((i)=>e[i]!==void 0).sort(L),o=[];for(let i of r)o.push(`${Pe(i,`${n} key`)}:${ce(e[i],`${n}.${i}`,t+1)}`);return`{${o.join(",")}}`}default:throw new k(`${n} is ${e===void 0?"undefined":`a ${typeof e}`}, not JSON`)}}var x=Symbol("unusual"),On=/^(?:0|[1-9][0-9]*)$/,_n=/[\ud800-\uffff]/,G=new Map,Mn=64,Nn=8;function De(e){if(e.some((n)=>n==="__proto__"||On.test(n)||_n.test(n)))return null;return e.sort()}function Cn(e){if(e.length<=Nn)return De(e);let n=JSON.stringify(e),t=G.get(n);if(t===void 0){if(t=De(e),G.size>=Mn)G.clear();G.set(n,t)}return t}function le(e,n){switch(typeof e){case"string":case"boolean":return e;case"number":return Number.isFinite(e)?e:x;case"object":break;default:return x}if(e===null)return null;if(n+1>=K)return x;if(Array.isArray(e)){let o=[];for(let i=0;i<e.length;i+=1){let s=e[i]===void 0?x:le(e[i],n+1);if(s===x)return x;o.push(s)}return o}if(!Ie(e))return x;let t=Cn(Object.keys(e));if(t===null)return x;let r={};for(let o of t){let i=e[o];if(i===void 0)continue;if(i===null||typeof i==="string"){r[o]=i;continue}let s=le(i,n+1);if(s===x)return x;r[o]=s}return r}function J(e){let n=le(e,0);if(n!==x){let t=JSON.stringify(n);if(!t.includes("\\ud"))return t}return Pn(e)}function Pn(e){return ce(e,"value",0)}class He{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&&de(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 Dn(e){return new He().update(e).hex()}function ue(e){let n=J(e.value),t=`[${n},${e.ord},${JSON.stringify(e.part)}]`;return{digest:`s1.${Tn("sha256").update(t).digest("hex").slice(0,32)}`,valueBytes:O(n)}}function In(e){return ue(e).digest}var Ue=256,fe=65536,D=Number.MAX_SAFE_INTEGER,pe=128,gt=16,ge=500,ye=262144,yt=64,mt=786432,wt="core.replica.sync",Fe="core.replica.announce",Rt="replica_schema_unsupported:";function X(e){if(typeof e!=="object"||e===null)throw a.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 a.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 vt(e){return{epoch:"",version:0,schema:e,limit:ge}}function me(e){return Math.min(e.limit,ge)}function qe(e){if(e.epoch!==""&&!we(e.epoch))return'e must be "" or 1-16 characters of [a-z0-9]';if(e.version>D)return"v must be at most 2^53 - 1";if(e.windowDays!==void 0&&!Ke(e.windowDays))return"window_days must be a positive safe integer";if(e.limit===0)return"l must be at least 1";if(e.resume!==void 0){let n=ee(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 bt(e){if(e.kind==="full-copy"&&e.head!==void 0)return Math.max(e.version,e.head);return e.version}function Et(e){if(e.kind==="changes")return e.more;if(e.kind==="full-copy")return e.next!==void 0;return!1}function xt(e,n){let t={epoch:e.epoch,version:e.version,schema:e.schema,limit:n};if(e.resume!==void 0)t.resume=e.resume;if(e.windowDays!==void 0)t.windowDays=e.windowDays;return t}var Hn=["unknown","schema","unavailable","busy"];function kt(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 we(e){return/^[a-z0-9]{1,16}$/.test(e)}var Un=/[\u0000-\u001f\u007f-\u009f]/;function ee(e){if(typeof e!=="string")return"key must be a string";if(e.length===0)return"key must not be empty";let n=O(e);if(n>Ue)return`key is ${n} bytes; at most ${Ue} are allowed`;if(Un.test(e))return"key must not contain control characters";if(B(e))return"key must not contain a lone surrogate";return null}function g(e){return JSON.stringify(e)}function b(e){if(!Number.isSafeInteger(e))throw a.store(`${e} is not an integer within 2^53 - 1`);return String(e)}function Fn(e){try{return J(e.value)}catch(n){if(n instanceof k)throw a.row(e.key,n.message);throw n}}var Be=new WeakMap;function Xe(e){let n=Be.get(e);if(n!==void 0)return n;let t=`[${g(e.key)},${Fn(e)}`;if(e.part!=="")return`${t},${b(e.ord)},${g(e.part)}]`;if(e.ord!==0)return`${t},${b(e.ord)}]`;return`${t}]`}function Re(e){let n=Xe(e);return Be.set(e,n),O(n)+1}function je(e){return O(g(e))+1}function Ye(e){return`[${e.map(Xe).join(",")}]`}function qn(e){return`[${e.map(g).join(",")}]`}function At(e){let n=e.resume===void 0?"":`,"a":${g(e.resume)}`,t=e.windowDays===void 0?"":`,"window_days":${I(e.windowDays)}`;return`{"e":${g(e.epoch)},"v":${b(e.version)},"s":${b(e.schema)},"l":${b(e.limit)}${n}${t}}`}function ze(e,n,t,r){return`"v":${b(e)},"u":${Ye(n)},"x":${qn(t)}${r?',"m":1':""}`}function Ve(e,n,t,r){return`"e":${g(e)},"v":${b(n)},"f":1,"u":${Ye(t)}${r===void 0?"":`,"n":${g(r)}`}`}function ne(e){switch(e.kind){case"nothing-new":return`{"e":${g(e.epoch)},"v":${b(e.version)}}`;case"changes":return`{"e":${g(e.epoch)},${ze(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":{let n=e.head===void 0?"":`,"h":${b(e.head)}`;return`{${Ve(e.epoch,e.version,e.rows,e.next)}${n}}`}}}function Bn(e){let n=e.resume===void 0?"":`,${g(e.resume)}`;if(e.windowDays!==void 0){if(e.resume===void 0)n=",null";n+=`,${I(e.windowDays,e.capability)}`}return`[${g(e.capability)},${b(e.schema)},${g(e.epoch)},${b(e.version)}${n}]`}function Tt(e){let n=e.origin===void 0?"":`,"origin":${g(e.origin)}`;return`{"c":[${e.entries.map(Bn).join(",")}]${n}}`}function Xn(e){switch(e.kind){case"nothing-new":return"0";case"changes":return`{${ze(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":return`{${Ve(e.epoch,e.version,e.rows,e.next)}}`;case"error":return`{"err":${g(e.code)}}`}}function Lt(e){return`{"r":[${e.answers.map(Xn).join(",")}]}`}function We(e){let n=e.windowDays===void 0?"":`,"window_days":${I(e.windowDays,e.capability)}`;return`{"c":${g(e.capability)},"e":${g(e.epoch)},"v":${b(e.version)}${n}}`}function St(e){return e==="ok"?'{"ok":true}':'{"rotate":true}'}function $t(e){return`{"h":[${e.heads.map((t)=>`[${g(t.capability)},${g(t.epoch)},${b(t.version)}]`).join(",")}]}`}function p(e){return a.request(e)}function Ge(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function C(e,n){if(!Ge(e))throw p(`${n} must be an object`);return e}function R(e,n){let t=e[n];return t===null?void 0:t}function E(e,n,t){let r=R(e,n);if(r===void 0)throw p(`${t}: missing field \`${n}\``);return r}function y(e,n){if(typeof e!=="string")throw p(`${n} must be a string`);return e}function Ke(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>0}function I(e,n){if(!Ke(e))throw p("window_days must be a positive safe integer");if(n!==void 0&&!/^[^.]+\.recent_[^.]+\.pull$/.test(n))throw p("window_days requires a recent collection");return e}function A(e,n,t=D){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>t){let r=t===D?"from 0 to 2^53 - 1":t===Number.MAX_VALUE?"of at least 0":`from 0 to ${t}`;throw p(`${n} must be an integer ${r}`)}return e}var he=4294967295;function Z(e,n){let t=R(e,n);if(t===void 0)return!1;if(A(t,n,255)!==1)throw p(`${n} must be 1 when present, got ${JSON.stringify(t)}`);return!0}function jn(e){if(!Array.isArray(e)||e.length<2||e.length>4)throw p("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 p("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 Q(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw p(`${n} must be an array of row entries`);return e.map(jn)}function Je(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw p(`${n} must be an array of keys`);return e.map((t)=>y(t,`an entry of ${n}`))}function te(e){let n=C(e,"a pull request"),t=R(n,"l"),r={epoch:y(E(n,"e","a pull request"),"e"),version:A(E(n,"v","a pull request"),"v",Number.MAX_VALUE),schema:A(E(n,"s","a pull request"),"s",he),limit:t===void 0?ge:A(t,"l",he)},o=R(n,"a");if(o!==void 0)r.resume=y(o,"a");if(n.window_days!==void 0)r.windowDays=I(n.window_days);return r}function Ot(e){let n=C(e,"a pull reply"),t=A(E(n,"v","a pull reply"),"v"),r=R(n,"e");if(r===void 0)throw p("a pull reply: missing field `e`");let o=y(r,"e"),i=R(n,"u"),s=R(n,"x");if(Z(n,"f")){let l={kind:"full-copy",epoch:o,version:t,rows:Q(i,"u")},u=R(n,"n");if(u!==void 0)l.next=y(u,"n");let d=R(n,"h");if(d!==void 0)l.head=A(d,"h");return l}if(i!==void 0||s!==void 0)return{kind:"changes",epoch:o,version:t,upserts:Q(i,"u"),deletes:Je(s,"x"),more:Z(n,"m")};return{kind:"nothing-new",epoch:o,version:t}}function Yn(e){if(!Array.isArray(e)||e.length<4||e.length>6)throw p("a sync entry is [capability, schema, epoch, version, resume?, windowDays?]");let n=e,t={capability:y(n[0],"a sync entry's capability"),schema:A(n[1],"a sync entry's schema",he),epoch:y(n[2],"a sync entry's epoch"),version:A(n[3],"a sync entry's version")};if(n.length>=5&&!(n.length===6&&n[4]===null))t.resume=y(n[4],"a sync entry's resume key");if(n.length===6)t.windowDays=I(n[5],t.capability);return t}function _t(e){let n=C(e,"a sync request"),t=E(n,"c","a sync request");if(!Array.isArray(t))throw p("c must be an array of sync entries");let r={entries:t.map(Yn)},o=R(n,"origin");if(o!==void 0)r.origin=y(o,"origin");return r}function zn(e){if(e===0)return{kind:"nothing-new"};if(!Ge(e))throw p("a sync answer is 0, a changes object, a full copy or an error");if("err"in e){let t=Hn.find((r)=>r===e.err);if(t===void 0)throw p("err must be a known error code");return{kind:"error",code:t}}let n=A(E(e,"v","a sync answer"),"v");if(Z(e,"f")){let t={kind:"full-copy",epoch:y(E(e,"e","a sync answer"),"e"),version:n,rows:Q(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:Q(R(e,"u"),"u"),deletes:Je(R(e,"x"),"x"),more:Z(e,"m")}}function Mt(e){let n=E(C(e,"a sync reply"),"r","a sync reply");if(!Array.isArray(n))throw p("r must be an array of answers");return{answers:n.map(zn)}}function Nt(e){let n=C(e,"an announce"),t=y(E(n,"c","an announce"),"c");return{capability:t,...n.window_days===void 0?{}:{windowDays:I(n.window_days,t)},epoch:y(E(n,"e","an announce"),"e"),version:A(E(n,"v","an announce"),"v")}}function Ze(e){let n=C(e,"an announce reply"),t=(i)=>{let s=R(n,i);if(s===void 0)return!1;if(typeof s!=="boolean")throw p(`${i} must be a boolean`);return s},r=t("rotate"),o=t("ok");if(r)return"rotate";if(o)return"ok";throw p('an announce reply is {"ok":true} or {"rotate":true}')}function Ct(e){let n=E(C(e,"replica.heads data"),"h","replica.heads data");if(!Array.isArray(n))throw p("h must be an array of heads");return{heads:n.map((t)=>{if(!Array.isArray(t)||t.length!==3)throw p("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 Qe=2592000000,en=5000,nn=60000,ve={maxAgeMs:Qe,maxCount:en};function _(e){return{epoch:e.epoch,version:e.version}}function j(e,n){return e.epoch===n.epoch&&e.version===n.version}function be(e){return e.map((n)=>({row:n,digest:oe(n)}))}function oe(e){let n=ee(e.key);if(n!==null)throw a.row(e.key,n);let t,r;try{({digest:t,valueBytes:r}=ue(e))}catch(i){if(i instanceof k)throw a.row(e.key,i.message);throw i}if(r>fe)throw a.row(e.key,`value is ${r} bytes encoded; at most ${fe} are allowed`);if(!Number.isInteger(e.ord)||Math.abs(e.ord)>D)throw a.row(e.key,"ord must be within \xB1(2^53 - 1)");if(typeof e.part!=="string")throw a.row(e.key,"part must be a string");let o=O(e.part);if(o>pe)throw a.row(e.key,`part is ${o} bytes; at most ${pe} are allowed`);if(B(e.part))throw a.row(e.key,"part must not contain a lone surrogate");return t}function tn(e,n){for(let t=0;t<4;t+=1){let r=e.env.newEpoch();if(!we(r))throw a.store("the environment produced an epoch outside [a-z0-9]{1,16}");if(r!==n)return r}throw a.store("the environment keeps producing the current epoch")}function re(e,n,t){if(t.rotateOwed)F(e,n,t);if(t.version>=D)throw a.store(`version of ${t.epoch} would pass 2^53 - 1`);return t.version+=1,t.version}function rn(e,n){let t=e.record(n.name);if(t!==null)return t;let r={epoch:tn(n,null),version:0,floor:0,dirty:!0,rotatedAt:n.env.nowMs(),reconciledAt:0,rotateOwed:!1};return e.putRecord(n.name,r),r}function Ee(e,n){let t=e.env.nowMs();return n.rotatedAt===0||t<n.rotatedAt||t-n.rotatedAt>=nn}function xe(e,n,t){if(Ee(n,t))return F(e,n,t),!0;return t.rotateOwed=!0,!1}function on(e,n,t,r){if(r||t.rotateOwed&&Ee(n,t))return F(e,n,t),!0;return!1}function sn(e,n){return!(n.rotateOwed&&Ee(e,n))}function F(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=tn(n,t.epoch),t.version=o,t.floor=0,t.rotatedAt=r,t.rotateOwed=!1}function an(e,n,t,r,o,i){let s=e.entry(n.name,r.key);if(s!==null&&!s.deleted&&s.digest===o)return!1;let l=re(e,n,t);return e.putEntry(n.name,{key:r.key,digest:o,version:l,deleted:!1,changedAt:i}),!0}function cn(e,n,t,r,o){let i=e.entry(n.name,r);if(i===null||i.deleted)return!1;let s=re(e,n,t);return e.putEntry(n.name,{key:r,digest:i.digest,version:s,deleted:!0,changedAt:o}),!0}function ke(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)xe(e,n,t)}function Ae(e,n,t,r){let o=n.env.nowMs(),i=[...r];i.sort((c,f)=>L(c.row.key,f.row.key));for(let c=1;c<i.length;c+=1){let f=i[c-1],h=i[c];if(f!==void 0&&h!==void 0&&f.row.key===h.row.key)throw a.row(f.row.key,"the key appears twice in the list")}let s=e.entries(n.name),l=[],u=[],d=0;for(let c of i){while(d<s.length&&L(H(s,d).key,c.row.key)<0){let h=H(s,d);if(!h.deleted)u.push(h);d+=1}let f=!1;if(d<s.length&&H(s,d).key===c.row.key){let h=H(s,d);f=!h.deleted&&h.digest===c.digest,d+=1}if(!f)l.push(c)}for(;d<s.length;d+=1){let c=H(s,d);if(!c.deleted)u.push(c)}for(let{row:c,digest:f}of l){let h=re(e,n,t);e.putEntry(n.name,{key:c.key,digest:f,version:h,deleted:!1,changedAt:o})}for(let c of u){let f=re(e,n,t);e.putEntry(n.name,{key:c.key,digest:c.digest,version:f,deleted:!0,changedAt:o})}ke(e,n,t,o),t.dirty=!1,t.reconciledAt=o}function H(e,n){let t=e[n];if(t===void 0)throw a.store("ledger index out of range");return t}function ln(e,n,t,{row:r,digest:o}){let i=n.env.nowMs();an(e,n,t,r,o,i),ke(e,n,t,i)}function dn(e,n,t,r){let o=ee(r);if(o!==null)throw a.row(r,o);let i=n.env.nowMs();cn(e,n,t,r,i),ke(e,n,t,i)}function U(e,n,t,r,o){return{kind:"full-copy",version:r,entries:e.liveAfter(n.name,t,o)}}function Vn(e,n,t,r){let o=me(r)+1;if(r.epoch!==t.epoch)return U(e,n,null,t.version,o);if(r.version>t.version)return F(e,n,t),U(e,n,null,t.version,o);if(r.resume!==void 0){if(r.version>=t.floor)return U(e,n,r.resume,r.version,o);return U(e,n,null,t.version,o)}if(r.version<t.floor)return U(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 Wn(e,n,t,r,o){let i=n.env.nowMs(),s=!1;for(let l of r){if(l.deleted)continue;let u=o.get(l.key);if(u===void 0)s=cn(e,n,t,l.key,i)||s;else{let d=oe(u);if(d!==l.digest)s=an(e,n,t,u,d,i)||s}}return s}function Te(e,n){if(!e.schemas.includes(n.schema))throw a.schema(e.name,n.schema);let t=qe(n);if(t!==null)throw a.request(t)}function un(e,n){let t;try{t=e(n)}catch(r){throw a.load(w(r))}return t.map(X)}function Le(e){return be(un(e,null))}function hn(e,n,t,r,o,i){if(Te(n,r),t.dirty)Ae(e,n,t,i??Le(o));let s=me(r),l=!1,u=0;for(;;){let d=l?U(e,n,null,t.version,s+1):Vn(e,n,t,r);if(d.kind==="nothing-new")return{kind:"nothing-new",epoch:t.epoch,version:t.version};let c=d.entries.slice(0,s),f=c.filter((S)=>!S.deleted).map((S)=>S.key),h=new Map;if(f.length>0){let S=new Set(f);for(let P of un(o,f))if(S.has(P.key))h.set(P.key,P)}if(u<2&&Wn(e,n,t,c,h)){u+=1;continue}let T=Gn(t,r,d,s,h);if(T!==null)return T;if(l)throw a.store("a full copy could not be built");l=!0}}function Gn(e,n,t,r,o){if(t.kind==="changes"){let c=[],f=0,h=!1;for(let m of t.entries){if(c.length===r){h=!0;break}let q=o.get(m.key),Ce=m.deleted?je(m.key):q!==void 0?Re(q):0;if(c.length>0&&f+Ce>ye){h=!0;break}f+=Ce,c.push(m)}let T;if(h){let m=0;while(m<c.length&&c[m]?.version===n.version+m+1)m+=1;if(m===0)return null;c.length=m,T=n.version+m}else T=e.version;let S=[],P=[];for(let m of c){if(m.deleted){P.push(m.key);continue}let q=o.get(m.key);if(q!==void 0)S.push(q)}return{kind:"changes",epoch:e.epoch,version:T,upserts:S,deletes:P,more:h}}let i=[],s=0,l=null,u=!1;for(let c=0;c<t.entries.length;c+=1){let f=H(t.entries,c);if(c===r){u=!0;break}let h=o.get(f.key);if(h===void 0){l=f.key;continue}let T=Re(h);if(c>0&&s+T>ye){u=!0;break}i.push(h),s+=T,l=f.key}let d={kind:"full-copy",epoch:e.epoch,version:t.version,rows:i};if(u&&l!==null)d.next=l;if(e.version>t.version)d.head=e.version;return d}function Se(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 Jn(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 fn(e){let n=new Map;for(let[t,r]of e)n.set(t,Jn(r));return n}function pn(e){if(e===void 0)return[];return[...e.entries.values()].sort((n,t)=>L(n.key,t.key))}class gn{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 pn(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 pn(this.get(e)).filter((r)=>!r.deleted&&(n===null||L(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((d)=>d.deleted).sort((d,c)=>d.version-c.version||d.changedAt-c.changedAt||L(d.key,c.key)),s=Math.max(0,i.length-t),l=null,u=0;return i.forEach((d,c)=>{if(c<s||d.changedAt<n)this.saveEntry(r,e,d.key),o.delete(d.key),l=l===null?d.version:Math.max(l,d.version);else u+=1}),{highest:l,overKeep:u>t}}}class $e{tables=new Map;ensure(){}write(e,n){let t=new gn(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 $e;return e.tables=fn(this.tables),e}restoreFrom(e){this.tables=fn(e.tables)}}var vn={nowMs:()=>Date.now(),newEpoch:Zn},yn="abcdefghijklmnopqrstuvwxyz0123456789",mn=0;function Zn(){let e=new Uint8Array(8),n=globalThis.crypto;if(n?.getRandomValues!==void 0)n.getRandomValues(e);else{mn+=1;let r=Date.now()+mn;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+=yn.charAt(r%yn.length);return t}var Qn=16,et=/^[a-z][a-z0-9_-]*$/,nt=/^(?:[A-Za-z_][A-Za-z0-9_]{0,47})?$/;class ie{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??vn,horizon:t.horizon??ve}}check(){let e=this.name.split(".");if(e.length<3||e[e.length-1]!=="pull"||!e.every((n)=>et.test(n)))throw a.config(`'${this.name}' is not a pull capability '<app>.<collection>.pull'`);if(this.name.startsWith("core."))throw a.config(`'${this.name}' is in the reserved 'core.' namespace`);if(!nt.test(this.tablePrefix))throw a.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 a.config("the tombstone horizon must keep at least one tombstone");if(!this.schemas.every((n)=>Number.isInteger(n)&&n>=0&&n<=4294967295))throw a.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,Qn)}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=rn(t,this.spec),o={...r},i=on(t,this.spec,r,this.wentBack(r)),s=e(t,r,i);if(!wn(r,o))t.putRecord(this.spec.name,r);n={value:s}}),n===null)throw a.store("the store did not run the ledger work");return n.value}before(e){try{return e()}catch(n){return this.withRecord(()=>{throw n})}}readSettled(){this.check();let e=Se(this.store,this.tablePrefix,this.name);if(e===null||this.wentBack(e)||!sn(this.spec,e))return null;return e}ensure(){this.check(),this.store.ensure(this.tablePrefix)}reconcile(e){let n=e.map(X),t=this.before(()=>be(n));return this.withRecord((r,o)=>{let i=_(o);return Ae(r,this.spec,o,t),j(_(o),i)?null:o.version})}touch(e){let n=X(e),t=this.before(()=>({row:n,digest:oe(n)}));return this.withRecord((r,o)=>(ln(r,this.spec,o,t),o.version))}remove(e){return this.withRecord((n,t)=>(dn(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||xe(e,this.spec,n);return n.dirty=!0,r})}head(){let e=this.readSettled();if(e!==null)return _(e);return this.withRecord((n,t)=>_(t))}answer(e,n){if(Te(this.spec,e),e.resume===void 0){let s=this.readSettled();if(s!==null&&!s.dirty&&s.epoch===e.epoch&&s.version===e.version)return this.noteHandedOut(s.epoch,s.version),{reply:{kind:"nothing-new",epoch:s.epoch,version:s.version},headMoved:!1}}let t=Se(this.store,this.tablePrefix,this.name),r=t===null||t.dirty?this.before(()=>Le(n)):null,{answered:o,head:i}=this.withRecord((s,l,u)=>{let d=_(l),c=t===null?l.version===0:wn(l,t),f=hn(s,this.spec,l,e,n,c?r:null),h=_(l);return{answered:{reply:f,headMoved:u||!j(h,d)},head:h}});return this.noteHandedOut(i.epoch,i.version),o}pull(e,n){return JSON.parse(ne(this.answer(te(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 Rn(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)F(r,this.spec,o);return _(o)});if(await Rn(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 wn(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 Rn(e,n,t){let r=JSON.parse(We({capability:e,epoch:n.epoch,version:n.version})),o=await t(Fe,r);try{return Ze(o)}catch(i){throw Error(`unexpected announce reply: ${w(i)}`)}}var se=2;function Oe(e){return{meta:`${e}replica_meta`,collections:`${e}replica_collections`,rows:`${e}replica_rows`}}function tt(e,n){e.exec(`CREATE TABLE IF NOT EXISTS ${n.collections} (
|
|
2
|
+
var N={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 An(e){return typeof e==="string"?Array.from(e).slice(0,64).join(""):""}class a 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 a("config",`${N.config} ${e}`,e)}static row(e,n){let t=An(e);return new a("row",`${N.row} row '${t}': ${n}`,n,t)}static request(e){return new a("request",`${N.request} ${e}`,e)}static schema(e,n){let t=`schema ${n} is not served by ${e}`;return new a("schema",`${N.schema} ${t}`,t)}static load(e){return new a("load",`${N.load} ${e}`,e)}static store(e){return new a("store",`${N.store} ${e}`,e)}}function R(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)}}import{createHash as Tn}from"crypto";function L(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}var Ln=new TextEncoder;function O(e){if(e.length>128)return Ln.encode(e).length;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&&ue(e.charCodeAt(t+1)))n+=4,t+=1;else n+=3}return n}function ue(e){return e>=56320&&e<=57343}function B(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t<55296||t>57343)continue;if(t<=56319&&ue(e.charCodeAt(n+1))){n+=1;continue}return!0}return!1}var J=128;function Sn(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>=J)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 $n="value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";class A extends Error{}function He(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function De(e,n){if(B(e))throw new A(`${n} holds a lone surrogate`);return JSON.stringify(e)}function le(e,n,t){switch(typeof e){case"string":return De(e,n);case"number":if(!Number.isFinite(e))throw new A(`${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>=J)throw new A($n);if(Array.isArray(e)){let i=[];for(let s=0;s<e.length;s+=1){let c=e[s];if(c===void 0)throw new A(`${n}[${s}] is undefined`);i.push(le(c,`${n}[${s}]`,t+1))}return`[${i.join(",")}]`}if(!He(e))throw new A(`${n} is not a plain object`);let r=Object.keys(e).filter((i)=>e[i]!==void 0).sort(L),o=[];for(let i of r)o.push(`${De(i,`${n} key`)}:${le(e[i],`${n}.${i}`,t+1)}`);return`{${o.join(",")}}`}default:throw new A(`${n} is ${e===void 0?"undefined":`a ${typeof e}`}, not JSON`)}}var k=Symbol("unusual"),On=/^(?:0|[1-9][0-9]*)$/,_n=/[\ud800-\uffff]/,K=new Map,Mn=64,Nn=8;function Ie(e){if(e.some((n)=>n==="__proto__"||On.test(n)||_n.test(n)))return null;return e.sort()}function Cn(e){if(e.length<=Nn)return Ie(e);let n=JSON.stringify(e),t=K.get(n);if(t===void 0){if(t=Ie(e),K.size>=Mn)K.clear();K.set(n,t)}return t}function de(e,n){switch(typeof e){case"string":case"boolean":return e;case"number":return Number.isFinite(e)?e:k;case"object":break;default:return k}if(e===null)return null;if(n+1>=J)return k;if(Array.isArray(e)){let o=[];for(let i=0;i<e.length;i+=1){let s=e[i]===void 0?k:de(e[i],n+1);if(s===k)return k;o.push(s)}return o}if(!He(e))return k;let t=Cn(Object.keys(e));if(t===null)return k;let r={};for(let o of t){let i=e[o];if(i===void 0)continue;if(i===null||typeof i==="string"){r[o]=i;continue}let s=de(i,n+1);if(s===k)return k;r[o]=s}return r}function Z(e){let n=de(e,0);if(n!==k){let t=JSON.stringify(n);if(!t.includes("\\ud"))return t}return Pn(e)}function Pn(e){return le(e,"value",0)}class Ue{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&&ue(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 Dn(e){return new Ue().update(e).hex()}function he(e){let n=Z(e.value),t=`[${n},${e.ord},${JSON.stringify(e.part)}]`;return{digest:`s1.${Tn("sha256").update(t).digest("hex").slice(0,32)}`,valueBytes:O(n)}}function In(e){return he(e).digest}function X(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}function fe(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 Hn(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 Fe(e){let n=new Map;for(let[t,r]of e)n.set(t,Hn(r));return n}function qe(e){if(e===void 0)return[];return[...e.entries.values()].sort((n,t)=>L(n.key,t.key))}class Be{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 qe(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 qe(this.get(e)).filter((r)=>!r.deleted&&(n===null||L(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((d)=>d.deleted).sort((d,l)=>d.version-l.version||d.changedAt-l.changedAt||L(d.key,l.key)),s=Math.max(0,i.length-t),c=null,f=0;return i.forEach((d,l)=>{if(l<s||d.changedAt<n)this.saveEntry(r,e,d.key),o.delete(d.key),c=c===null?d.version:Math.max(c,d.version);else f+=1}),{highest:c,overKeep:f>t}}}class pe{tables=new Map;ensure(){}write(e,n){let t=new Be(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 pe;return e.tables=Fe(this.tables),e}restoreFrom(e){this.tables=Fe(e.tables)}}var Xe=256,ye=65536,D=Number.MAX_SAFE_INTEGER,me=128,mt=16,we=500,Re=262144,wt=64,Rt=786432,vt="core.replica.sync",je="core.replica.announce",bt="replica_schema_unsupported:";function j(e){if(typeof e!=="object"||e===null)throw a.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 a.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 Et(e){return{epoch:"",version:0,schema:e,limit:we}}function ve(e){return Math.min(e.limit,we)}function Ye(e){if(e.epoch!==""&&!be(e.epoch))return'e must be "" or 1-16 characters of [a-z0-9]';if(e.version>D)return"v must be at most 2^53 - 1";if(e.windowDays!==void 0&&!en(e.windowDays))return"window_days must be a positive safe integer";if(e.limit===0)return"l must be at least 1";if(e.resume!==void 0){let n=ne(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 xt(e){if(e.kind==="full-copy"&&e.head!==void 0)return Math.max(e.version,e.head);return e.version}function kt(e){if(e.kind==="changes")return e.more;if(e.kind==="full-copy")return e.next!==void 0;return!1}function At(e,n){let t={epoch:e.epoch,version:e.version,schema:e.schema,limit:n};if(e.resume!==void 0)t.resume=e.resume;if(e.windowDays!==void 0)t.windowDays=e.windowDays;return t}var Un=["unknown","schema","unavailable","busy"];function Tt(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 be(e){return/^[a-z0-9]{1,16}$/.test(e)}var Fn=/[\u0000-\u001f\u007f-\u009f]/;function ne(e){if(typeof e!=="string")return"key must be a string";if(e.length===0)return"key must not be empty";let n=O(e);if(n>Xe)return`key is ${n} bytes; at most ${Xe} are allowed`;if(Fn.test(e))return"key must not contain control characters";if(B(e))return"key must not contain a lone surrogate";return null}function y(e){return JSON.stringify(e)}function E(e){if(!Number.isSafeInteger(e))throw a.store(`${e} is not an integer within 2^53 - 1`);return String(e)}function qn(e){try{return Z(e.value)}catch(n){if(n instanceof A)throw a.row(e.key,n.message);throw n}}var ze=new WeakMap;function Ve(e){let n=ze.get(e);if(n!==void 0)return n;let t=`[${y(e.key)},${qn(e)}`;if(e.part!=="")return`${t},${E(e.ord)},${y(e.part)}]`;if(e.ord!==0)return`${t},${E(e.ord)}]`;return`${t}]`}function Ee(e){let n=Ve(e);return ze.set(e,n),O(n)+1}function We(e){return O(y(e))+1}function Ge(e){return`[${e.map(Ve).join(",")}]`}function Bn(e){return`[${e.map(y).join(",")}]`}function Lt(e){let n=e.resume===void 0?"":`,"a":${y(e.resume)}`,t=e.windowDays===void 0?"":`,"window_days":${I(e.windowDays)}`;return`{"e":${y(e.epoch)},"v":${E(e.version)},"s":${E(e.schema)},"l":${E(e.limit)}${n}${t}}`}function Ke(e,n,t,r){return`"v":${E(e)},"u":${Ge(n)},"x":${Bn(t)}${r?',"m":1':""}`}function Je(e,n,t,r){return`"e":${y(e)},"v":${E(n)},"f":1,"u":${Ge(t)}${r===void 0?"":`,"n":${y(r)}`}`}function te(e){switch(e.kind){case"nothing-new":return`{"e":${y(e.epoch)},"v":${E(e.version)}}`;case"changes":return`{"e":${y(e.epoch)},${Ke(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":{let n=e.head===void 0?"":`,"h":${E(e.head)}`;return`{${Je(e.epoch,e.version,e.rows,e.next)}${n}}`}}}function Xn(e){let n=e.resume===void 0?"":`,${y(e.resume)}`;if(e.windowDays!==void 0){if(e.resume===void 0)n=",null";n+=`,${I(e.windowDays,e.capability)}`}return`[${y(e.capability)},${E(e.schema)},${y(e.epoch)},${E(e.version)}${n}]`}function St(e){let n=e.origin===void 0?"":`,"origin":${y(e.origin)}`;return`{"c":[${e.entries.map(Xn).join(",")}]${n}}`}function jn(e){switch(e.kind){case"nothing-new":return"0";case"changes":return`{${Ke(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":return`{${Je(e.epoch,e.version,e.rows,e.next)}}`;case"error":return`{"err":${y(e.code)}}`}}function $t(e){return`{"r":[${e.answers.map(jn).join(",")}]}`}function Ze(e){let n=e.windowDays===void 0?"":`,"window_days":${I(e.windowDays,e.capability)}`;return`{"c":${y(e.capability)},"e":${y(e.epoch)},"v":${E(e.version)}${n}}`}function Ot(e){return e==="ok"?'{"ok":true}':'{"rotate":true}'}function _t(e){return`{"h":[${e.heads.map((t)=>`[${y(t.capability)},${y(t.epoch)},${E(t.version)}]`).join(",")}]}`}function p(e){return a.request(e)}function Qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function C(e,n){if(!Qe(e))throw p(`${n} must be an object`);return e}function v(e,n){let t=e[n];return t===null?void 0:t}function x(e,n,t){let r=v(e,n);if(r===void 0)throw p(`${t}: missing field \`${n}\``);return r}function m(e,n){if(typeof e!=="string")throw p(`${n} must be a string`);return e}function en(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>0}function I(e,n){if(!en(e))throw p("window_days must be a positive safe integer");if(n!==void 0&&!/^[^.]+\.recent_[^.]+\.pull$/.test(n))throw p("window_days requires a recent collection");return e}function T(e,n,t=D){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>t){let r=t===D?"from 0 to 2^53 - 1":t===Number.MAX_VALUE?"of at least 0":`from 0 to ${t}`;throw p(`${n} must be an integer ${r}`)}return e}var ge=4294967295;function Q(e,n){let t=v(e,n);if(t===void 0)return!1;if(T(t,n,255)!==1)throw p(`${n} must be 1 when present, got ${JSON.stringify(t)}`);return!0}function Yn(e){if(!Array.isArray(e)||e.length<2||e.length>4)throw p("a row entry is [key, value, ord?, part?]");let n=e,t=m(n[0],"a row's key"),r=n[2];if(r!==void 0&&(typeof r!=="number"||!Number.isInteger(r)))throw p("a row's ord must be an integer");let o=n[3]===void 0?"":m(n[3],"a row's part");return{key:t,value:n[1],ord:typeof r==="number"?r:0,part:o}}function ee(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw p(`${n} must be an array of row entries`);return e.map(Yn)}function nn(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw p(`${n} must be an array of keys`);return e.map((t)=>m(t,`an entry of ${n}`))}function re(e){let n=C(e,"a pull request"),t=v(n,"l"),r={epoch:m(x(n,"e","a pull request"),"e"),version:T(x(n,"v","a pull request"),"v",Number.MAX_VALUE),schema:T(x(n,"s","a pull request"),"s",ge),limit:t===void 0?we:T(t,"l",ge)},o=v(n,"a");if(o!==void 0)r.resume=m(o,"a");if(n.window_days!==void 0)r.windowDays=I(n.window_days);return r}function Mt(e){let n=C(e,"a pull reply"),t=T(x(n,"v","a pull reply"),"v"),r=v(n,"e");if(r===void 0)throw p("a pull reply: missing field `e`");let o=m(r,"e"),i=v(n,"u"),s=v(n,"x");if(Q(n,"f")){let c={kind:"full-copy",epoch:o,version:t,rows:ee(i,"u")},f=v(n,"n");if(f!==void 0)c.next=m(f,"n");let d=v(n,"h");if(d!==void 0)c.head=T(d,"h");return c}if(i!==void 0||s!==void 0)return{kind:"changes",epoch:o,version:t,upserts:ee(i,"u"),deletes:nn(s,"x"),more:Q(n,"m")};return{kind:"nothing-new",epoch:o,version:t}}function zn(e){if(!Array.isArray(e)||e.length<4||e.length>6)throw p("a sync entry is [capability, schema, epoch, version, resume?, windowDays?]");let n=e,t={capability:m(n[0],"a sync entry's capability"),schema:T(n[1],"a sync entry's schema",ge),epoch:m(n[2],"a sync entry's epoch"),version:T(n[3],"a sync entry's version")};if(n.length>=5&&!(n.length===6&&n[4]===null))t.resume=m(n[4],"a sync entry's resume key");if(n.length===6)t.windowDays=I(n[5],t.capability);return t}function Nt(e){let n=C(e,"a sync request"),t=x(n,"c","a sync request");if(!Array.isArray(t))throw p("c must be an array of sync entries");let r={entries:t.map(zn)},o=v(n,"origin");if(o!==void 0)r.origin=m(o,"origin");return r}function Vn(e){if(e===0)return{kind:"nothing-new"};if(!Qe(e))throw p("a sync answer is 0, a changes object, a full copy or an error");if("err"in e){let t=Un.find((r)=>r===e.err);if(t===void 0)throw p("err must be a known error code");return{kind:"error",code:t}}let n=T(x(e,"v","a sync answer"),"v");if(Q(e,"f")){let t={kind:"full-copy",epoch:m(x(e,"e","a sync answer"),"e"),version:n,rows:ee(v(e,"u"),"u")},r=v(e,"n");if(r!==void 0)t.next=m(r,"n");return t}return{kind:"changes",version:n,upserts:ee(v(e,"u"),"u"),deletes:nn(v(e,"x"),"x"),more:Q(e,"m")}}function Ct(e){let n=x(C(e,"a sync reply"),"r","a sync reply");if(!Array.isArray(n))throw p("r must be an array of answers");return{answers:n.map(Vn)}}function Pt(e){let n=C(e,"an announce"),t=m(x(n,"c","an announce"),"c");return{capability:t,...n.window_days===void 0?{}:{windowDays:I(n.window_days,t)},epoch:m(x(n,"e","an announce"),"e"),version:T(x(n,"v","an announce"),"v")}}function tn(e){let n=C(e,"an announce reply"),t=(i)=>{let s=v(n,i);if(s===void 0)return!1;if(typeof s!=="boolean")throw p(`${i} must be a boolean`);return s},r=t("rotate"),o=t("ok");if(r)return"rotate";if(o)return"ok";throw p('an announce reply is {"ok":true} or {"rotate":true}')}function Dt(e){let n=x(C(e,"replica.heads data"),"h","replica.heads data");if(!Array.isArray(n))throw p("h must be an array of heads");return{heads:n.map((t)=>{if(!Array.isArray(t)||t.length!==3)throw p("a pushed head is [capability, epoch, version]");let r=t;return{capability:m(r[0],"a head's capability"),epoch:m(r[1],"a head's epoch"),version:T(r[2],"a head's version")}})}}var rn=2592000000,on=5000,sn=60000,xe={maxAgeMs:rn,maxCount:on};function _(e){return{epoch:e.epoch,version:e.version}}function Y(e,n){return e.epoch===n.epoch&&e.version===n.version}function ke(e){return e.map((n)=>({row:n,digest:ie(n)}))}function ie(e){let n=ne(e.key);if(n!==null)throw a.row(e.key,n);let t,r;try{({digest:t,valueBytes:r}=he(e))}catch(i){if(i instanceof A)throw a.row(e.key,i.message);throw i}if(r>ye)throw a.row(e.key,`value is ${r} bytes encoded; at most ${ye} are allowed`);if(!Number.isInteger(e.ord)||Math.abs(e.ord)>D)throw a.row(e.key,"ord must be within \xB1(2^53 - 1)");if(typeof e.part!=="string")throw a.row(e.key,"part must be a string");let o=O(e.part);if(o>me)throw a.row(e.key,`part is ${o} bytes; at most ${me} are allowed`);if(B(e.part))throw a.row(e.key,"part must not contain a lone surrogate");return t}function an(e,n){for(let t=0;t<4;t+=1){let r=e.env.newEpoch();if(!be(r))throw a.store("the environment produced an epoch outside [a-z0-9]{1,16}");if(r!==n)return r}throw a.store("the environment keeps producing the current epoch")}function oe(e,n,t){if(t.rotateOwed)F(e,n,t);if(t.version>=D)throw a.store(`version of ${t.epoch} would pass 2^53 - 1`);return t.version+=1,t.version}function cn(e,n){let t=e.record(n.name);if(t!==null)return t;let r={epoch:an(n,null),version:0,floor:0,dirty:!0,rotatedAt:n.env.nowMs(),reconciledAt:0,rotateOwed:!1};return e.putRecord(n.name,r),r}function Ae(e,n){let t=e.env.nowMs();return n.rotatedAt===0||t<n.rotatedAt||t-n.rotatedAt>=sn}function Te(e,n,t){if(Ae(n,t))return F(e,n,t),!0;return t.rotateOwed=!0,!1}function ln(e,n,t,r){if(r||t.rotateOwed&&Ae(n,t))return F(e,n,t),!0;return!1}function dn(e,n){return!(n.rotateOwed&&Ae(e,n))}function F(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=an(n,t.epoch),t.version=o,t.floor=0,t.rotatedAt=r,t.rotateOwed=!1}function un(e,n,t,r,o,i){let s=e.entry(n.name,r.key);if(s!==null&&!s.deleted&&s.digest===o)return!1;let c=oe(e,n,t);return e.putEntry(n.name,{key:r.key,digest:o,version:c,deleted:!1,changedAt:i}),!0}function hn(e,n,t,r,o){let i=e.entry(n.name,r);if(i===null||i.deleted)return!1;let s=oe(e,n,t);return e.putEntry(n.name,{key:r,digest:i.digest,version:s,deleted:!0,changedAt:o}),!0}function Le(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)Te(e,n,t)}function Se(e,n,t,r){let o=n.env.nowMs(),i={...t},s=[...r];s.sort((u,h)=>L(u.row.key,h.row.key));for(let u=1;u<s.length;u+=1){let h=s[u-1],g=s[u];if(h!==void 0&&g!==void 0&&h.row.key===g.row.key)throw a.row(h.row.key,"the key appears twice in the list")}let c=e.entries(n.name),f=[],d=[],l=0;for(let u of s){while(l<c.length&&L(H(c,l).key,u.row.key)<0){let g=H(c,l);if(!g.deleted)d.push(g);l+=1}let h=!1;if(l<c.length&&H(c,l).key===u.row.key){let g=H(c,l);h=!g.deleted&&g.digest===u.digest,l+=1}if(!h)f.push(u)}for(;l<c.length;l+=1){let u=H(c,l);if(!u.deleted)d.push(u)}for(let{row:u,digest:h}of f){let g=oe(e,n,t);e.putEntry(n.name,{key:u.key,digest:h,version:g,deleted:!1,changedAt:o})}for(let u of d){let h=oe(e,n,t);e.putEntry(n.name,{key:u.key,digest:u.digest,version:h,deleted:!0,changedAt:o})}if(Le(e,n,t,o),t.dirty=!1,!X(t,i))t.reconciledAt=o}function H(e,n){let t=e[n];if(t===void 0)throw a.store("ledger index out of range");return t}function fn(e,n,t,{row:r,digest:o}){let i=n.env.nowMs();un(e,n,t,r,o,i),Le(e,n,t,i)}function pn(e,n,t,r){let o=ne(r);if(o!==null)throw a.row(r,o);let i=n.env.nowMs();hn(e,n,t,r,i),Le(e,n,t,i)}function U(e,n,t,r,o){return{kind:"full-copy",version:r,entries:e.liveAfter(n.name,t,o)}}function Wn(e,n,t,r){let o=ve(r)+1;if(r.epoch!==t.epoch)return U(e,n,null,t.version,o);if(r.version>t.version)return F(e,n,t),U(e,n,null,t.version,o);if(r.resume!==void 0){if(r.version>=t.floor)return U(e,n,r.resume,r.version,o);return U(e,n,null,t.version,o)}if(r.version<t.floor)return U(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 Gn(e,n,t,r,o){let i=n.env.nowMs(),s=!1;for(let c of r){if(c.deleted)continue;let f=o.get(c.key);if(f===void 0)s=hn(e,n,t,c.key,i)||s;else{let d=ie(f);if(d!==c.digest)s=un(e,n,t,f,d,i)||s}}return s}function $e(e,n){if(!e.schemas.includes(n.schema))throw a.schema(e.name,n.schema);let t=Ye(n);if(t!==null)throw a.request(t)}function gn(e,n){let t;try{t=e(n)}catch(r){throw a.load(R(r))}return t.map(j)}function Oe(e){return ke(gn(e,null))}function yn(e,n,t,r,o,i){if($e(n,r),t.dirty)Se(e,n,t,i??Oe(o));let s=ve(r),c=!1,f=0;for(;;){let d=c?U(e,n,null,t.version,s+1):Wn(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,s),u=l.filter((S)=>!S.deleted).map((S)=>S.key),h=new Map;if(u.length>0){let S=new Set(u);for(let P of gn(o,u))if(S.has(P.key))h.set(P.key,P)}if(f<2&&Gn(e,n,t,l,h)){f+=1;continue}let g=Kn(t,r,d,s,h);if(g!==null)return g;if(c)throw a.store("a full copy could not be built");c=!0}}function Kn(e,n,t,r,o){if(t.kind==="changes"){let l=[],u=0,h=!1;for(let w of t.entries){if(l.length===r){h=!0;break}let q=o.get(w.key),Pe=w.deleted?We(w.key):q!==void 0?Ee(q):0;if(l.length>0&&u+Pe>Re){h=!0;break}u+=Pe,l.push(w)}let g;if(h){let w=0;while(w<l.length&&l[w]?.version===n.version+w+1)w+=1;if(w===0)return null;l.length=w,g=n.version+w}else g=e.version;let S=[],P=[];for(let w of l){if(w.deleted){P.push(w.key);continue}let q=o.get(w.key);if(q!==void 0)S.push(q)}return{kind:"changes",epoch:e.epoch,version:g,upserts:S,deletes:P,more:h}}let i=[],s=0,c=null,f=!1;for(let l=0;l<t.entries.length;l+=1){let u=H(t.entries,l);if(l===r){f=!0;break}let h=o.get(u.key);if(h===void 0){c=u.key;continue}let g=Ee(h);if(l>0&&s+g>Re){f=!0;break}i.push(h),s+=g,c=u.key}let d={kind:"full-copy",epoch:e.epoch,version:t.version,rows:i};if(f&&c!==null)d.next=c;if(e.version>t.version)d.head=e.version;return d}var vn={nowMs:()=>Date.now(),newEpoch:Zn},mn="abcdefghijklmnopqrstuvwxyz0123456789",wn=0;function Zn(){let e=new Uint8Array(8),n=globalThis.crypto;if(n?.getRandomValues!==void 0)n.getRandomValues(e);else{wn+=1;let r=Date.now()+wn;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+=mn.charAt(r%mn.length);return t}var Qn=16,et=/^[a-z][a-z0-9_-]*$/,nt=/^(?:[A-Za-z_][A-Za-z0-9_]{0,47})?$/;class se{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??vn,horizon:t.horizon??xe}}check(){let e=this.name.split(".");if(e.length<3||e[e.length-1]!=="pull"||!e.every((n)=>et.test(n)))throw a.config(`'${this.name}' is not a pull capability '<app>.<collection>.pull'`);if(this.name.startsWith("core."))throw a.config(`'${this.name}' is in the reserved 'core.' namespace`);if(!nt.test(this.tablePrefix))throw a.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 a.config("the tombstone horizon must keep at least one tombstone");if(!this.schemas.every((n)=>Number.isInteger(n)&&n>=0&&n<=4294967295))throw a.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,Qn)}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=cn(t,this.spec),o={...r},i=ln(t,this.spec,r,this.wentBack(r)),s=e(t,r,i);if(!X(r,o))t.putRecord(this.spec.name,r);n={value:s}}),n===null)throw a.store("the store did not run the ledger work");return n.value}before(e){try{return e()}catch(n){return this.withRecord(()=>{throw n})}}readSettled(){this.check();let e=fe(this.store,this.tablePrefix,this.name);if(e===null||this.wentBack(e)||!dn(this.spec,e))return null;return e}ensure(){this.check(),this.store.ensure(this.tablePrefix)}reconcile(e){let n=e.map(j),t=this.before(()=>ke(n));return this.withRecord((r,o)=>{let i=_(o);return Se(r,this.spec,o,t),Y(_(o),i)?null:o.version})}touch(e){let n=j(e),t=this.before(()=>({row:n,digest:ie(n)}));return this.withRecord((r,o)=>(fn(r,this.spec,o,t),o.version))}remove(e){return this.withRecord((n,t)=>(pn(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||Te(e,this.spec,n);return n.dirty=!0,r})}head(){let e=this.readSettled();if(e!==null)return _(e);return this.withRecord((n,t)=>_(t))}answer(e,n){if($e(this.spec,e),e.resume===void 0){let s=this.readSettled();if(s!==null&&!s.dirty&&s.epoch===e.epoch&&s.version===e.version)return this.noteHandedOut(s.epoch,s.version),{reply:{kind:"nothing-new",epoch:s.epoch,version:s.version},headMoved:!1}}let t=fe(this.store,this.tablePrefix,this.name),r=t===null||t.dirty?this.before(()=>Oe(n)):null,{answered:o,head:i}=this.withRecord((s,c,f)=>{let d=_(c),l=t===null?c.version===0:X(c,t),u=yn(s,this.spec,c,e,n,l?r:null),h=_(c);return{answered:{reply:u,headMoved:f||!Y(h,d)},head:h}});return this.noteHandedOut(i.epoch,i.version),o}pull(e,n){return JSON.parse(te(this.answer(re(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:R(n),first:t}}}async announceInner(e){let n=this.head();if(await Rn(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)F(r,this.spec,o);return _(o)});if(await Rn(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.`}}async function Rn(e,n,t){let r=JSON.parse(Ze({capability:e,epoch:n.epoch,version:n.version})),o=await t(je,r);try{return tn(o)}catch(i){throw Error(`unexpected announce reply: ${R(i)}`)}}var ae=2;function _e(e){return{meta:`${e}replica_meta`,collections:`${e}replica_collections`,rows:`${e}replica_rows`}}function tt(e,n){e.exec(`CREATE TABLE IF NOT EXISTS ${n.collections} (
|
|
3
3
|
name TEXT PRIMARY KEY NOT NULL,
|
|
4
4
|
epoch TEXT NOT NULL,
|
|
5
5
|
version INTEGER NOT NULL DEFAULT 0,
|
|
@@ -17,15 +17,15 @@ var N={config:"replica_config_invalid:",row:"replica_row_invalid:",request:"repl
|
|
|
17
17
|
PRIMARY KEY (collection, row_key)
|
|
18
18
|
)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_version ON ${n.rows} (collection, version)`)}function rt(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
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 ot=[rt];function
|
|
20
|
+
WHERE deleted = 1`)}var ot=[rt];function G(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 a.store(`${n} in the replica ledger is not an integer within 2^53 - 1: ${String(e)}`)}function M(e,n){let t=G(e,n);if(t<0)throw a.store(`negative ${t} in the replica ledger`);return t}function Ne(e,n){if(typeof e!=="string")throw a.store(`${n} in the replica ledger is not text`);return e}function b(e,n){if(typeof e!=="object"||e===null)throw a.store("the replica ledger returned a non-row");return e[n]}var bn="epoch, version, floor, dirty, rotated_at, reconciled_at, rotate_owed",z="row_key, digest, version, deleted, changed_at";function it(e){return{epoch:Ne(b(e,"epoch"),"an epoch"),version:M(b(e,"version"),"a version"),floor:M(b(e,"floor"),"a floor"),dirty:G(b(e,"dirty"),"dirty")!==0,rotatedAt:M(b(e,"rotated_at"),"rotated_at"),reconciledAt:M(b(e,"reconciled_at"),"reconciled_at"),rotateOwed:G(b(e,"rotate_owed"),"rotate_owed")!==0}}function V(e){return{key:Ne(b(e,"row_key"),"a row key"),digest:Ne(b(e,"digest"),"a digest"),version:M(b(e,"version"),"a version"),deleted:G(b(e,"deleted"),"deleted")!==0,changedAt:M(b(e,"changed_at"),"changed_at")}}function Me(e){try{return e()}catch(n){if(n instanceof a)throw n;throw a.store(R(n))}}class En{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, ${bn})
|
|
21
21
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
|
|
22
22
|
ON CONFLICT(name) DO UPDATE SET epoch = excluded.epoch, version = excluded.version,
|
|
23
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 ${
|
|
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 ${z} FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).get(e,n);return t===null||t===void 0?null:V(t)}entries(e){return this.q(`SELECT ${z} FROM ${this.t.rows} WHERE collection = ?1 ORDER BY row_key`).all(e).map(V)}putEntry(e,n){this.q(`INSERT INTO ${this.t.rows} (collection, row_key, digest, version, deleted, changed_at)
|
|
25
25
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
|
26
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 ${
|
|
28
|
-
ORDER BY version LIMIT ?3`).all(e,n,t).map(
|
|
29
|
-
ORDER BY row_key LIMIT ?2`).all(e,t).map(
|
|
30
|
-
AND row_key > ?2 ORDER BY row_key LIMIT ?3`).all(e,n,t).map(
|
|
31
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(t),this.statements.clear()}write(e,n){let t=
|
|
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 ${z} FROM ${this.t.rows} WHERE collection = ?1 AND version > ?2
|
|
28
|
+
ORDER BY version LIMIT ?3`).all(e,n,t).map(V)}liveAfter(e,n,t){if(n===null)return this.q(`SELECT ${z} FROM ${this.t.rows} WHERE collection = ?1 AND deleted = 0
|
|
29
|
+
ORDER BY row_key LIMIT ?2`).all(e,t).map(V);return this.q(`SELECT ${z} 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(V)}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=b(o,"highest"),s=i===null||i===void 0?null:M(i,"a version");if(s!==null)this.q(`DELETE FROM ${r} WHERE collection = ?1 AND deleted = 1 AND changed_at < ?2`).run(e,n);let c=this.q(`SELECT version FROM ${r} WHERE collection = ?1 AND deleted = 1 ORDER BY version DESC LIMIT 1 OFFSET ?2`).get(e,t),f=c===null||c===void 0?null:M(b(c,"version"),"a version");if(f!==null)this.q(`DELETE FROM ${r} WHERE collection = ?1 AND deleted = 1 AND version <= ?2`).run(e,f);return{highest:s===null?f:f===null?s:Math.max(s,f),overKeep:!1}}}var W="node_app_replica";class ce{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 ${W}`:"COMMIT")}catch(r){try{if(this.db.exec(n?`ROLLBACK TO ${W}`:"ROLLBACK"),n)this.db.exec(`RELEASE ${W}`)}catch{}if(r instanceof a)throw r;throw a.store(R(r))}return t}begin(){if(this.db.inTransaction===!0)return Me(()=>this.db.exec(`SAVEPOINT ${W}`)),!0;try{return this.db.exec("BEGIN IMMEDIATE"),!1}catch(e){if(this.db.inTransaction===void 0&&this.insideAppTransaction())return Me(()=>this.db.exec(`SAVEPOINT ${W}`)),!0;throw a.store(R(e))}}insideAppTransaction(){try{this.db.exec("BEGIN DEFERRED")}catch{return!0}try{this.db.exec("ROLLBACK")}catch{}return!1}ensure(e){let n=_e(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=G(b(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 tt(this.db,e),t=1;if(t<1||t>ae)throw a.store(`the replica ledger's layout is ${t}; this helper knows layouts 1 to ${ae}`);while(t<ae){let r=ot[t-1];if(r===void 0)throw a.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=_e(e);this.inTransaction(()=>n(new En(this,t)))}readRecordIn(e,n){let t=this.statement(`SELECT ${bn} FROM ${e.collections} WHERE name = ?1`).get(n);return t===null||t===void 0?null:it(t)}readRecord(e,n){return Me(()=>this.readRecordIn(_e(e),n))}}function st(e){return typeof e.write==="function"&&typeof e.ensure==="function"}var xn=0;function er(e,n=5000){return async(t,r)=>{xn+=1;let o=`replica-${Date.now().toString(36)}-${xn.toString(36)}`,i=await e({id:o,capability:t,payload:r},n);if(!i.success)throw Error(R(i.payload));return i.payload}}var at=2000,ct=60000;class Ce{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 kn{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 Ce(i.firstMs,i.maxMs,()=>this.reconcileNow()),this.announceRetry=new Ce(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}: ${R(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): ${R(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}: ${R(n)}`),this.announceRetry.failed();return}if(this.announced===null||!Y(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: ${R(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 lt{invoke;options;store;collections=new Map;tablePrefix;warn;constructor(e,n,t={}){this.invoke=n;this.options=t;this.store=st(e)?e:new ce(e),this.tablePrefix=t.tablePrefix??"",this.warn=t.warn??((r)=>console.warn(r))}collection(e,n){if(this.collections.has(e))throw a.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 se(this.store,e,t);r.ensure();let o={firstMs:this.options.retry?.firstMs??at,maxMs:this.options.retry?.maxMs??ct},i=new kn(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 a.request(`${e} is not a replicated collection of this app`);let r=t.ledger.answer(re(n),(o)=>t.load(o));if(r.headMoved)t.announce();return Promise.resolve(JSON.parse(te(r.reply)))}catch(t){return Promise.reject(t instanceof Error?t:Error(R(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{je as ANNOUNCE_CAPABILITY,se as CollectionLedger,xe as DEFAULT_HORIZON,ae as LEDGER_LAYOUT,mt as MAX_EPOCH_CHARS,Xe as MAX_KEY_BYTES,me as MAX_PART_BYTES,Re as MAX_REPLY_ROW_BYTES,we as MAX_ROWS_PER_REPLY,D as MAX_SAFE_INTEGER,wt as MAX_SYNC_ENTRIES,Rt as MAX_SYNC_REPLY_BYTES,ye as MAX_VALUE_BYTES,J as MAX_VALUE_DEPTH,pe as MemoryLedger,N as REPLICA_ERROR_PREFIXES,sn as ROTATION_MIN_INTERVAL_MS,lt as Replica,a as ReplicaError,bt as SCHEMA_UNSUPPORTED_PREFIX,vt as SYNC_CAPABILITY,ce as SqliteLedgerStore,rn as TOMBSTONE_MAX_AGE_MS,on as TOMBSTONE_MAX_COUNT,Z as canonicalJson,qn as canonicalValue,L as compareUtf8,Pt as decodeAnnounce,tn as decodeAnnounceReply,Dt as decodeHeadsData,Mt as decodePullReply,re as decodePullRequest,Yn as decodeRow,Vn as decodeSyncAnswer,zn as decodeSyncEntry,Ct as decodeSyncReply,Nt as decodeSyncRequest,ve as effectiveLimit,Ze as encodeAnnounce,Ot as encodeAnnounceReply,_t as encodeHeadsData,te as encodePullReply,Lt as encodePullRequest,Ve as encodeRow,jn as encodeSyncAnswer,Xn as encodeSyncEntry,$t as encodeSyncReply,St as encodeSyncRequest,We as encodedDeleteBytes,Ee as encodedRowBytes,Dn as fnv1a64,xt as handedOut,er as hostInvoke,Et as initialPullRequest,be as isEpoch,kt as isTruncated,Sn as isWithinValueDepth,ne as keyProblem,At as pullRequestOf,Ye as pullRequestProblem,In as rowDigest,Tt as syncAnswerOf,vn as systemEnvironment,j as toRow,O as utf8Length};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@econ-v1/app-sdk",
|
|
3
|
-
"version": "7.7.
|
|
3
|
+
"version": "7.7.41",
|
|
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",
|