@econ-v1/app-sdk 7.7.16 → 7.7.18

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.
@@ -69,6 +69,8 @@ export interface PullRequest {
69
69
  limit: number;
70
70
  /** The last key of the previous page of a paged full copy. */
71
71
  resume?: string;
72
+ /** The custom recent-history window, in days, when requested by the device. */
73
+ windowDays?: number;
72
74
  }
73
75
  /** "I hold nothing": the first request for a collection. */
74
76
  export declare function initialPullRequest(schema: number): PullRequest;
@@ -117,13 +119,14 @@ export type PullReply =
117
119
  export declare function handedOut(reply: PullReply): number;
118
120
  /** True when the caller must ask again to get the rest (`"m":1` or `"n"`). */
119
121
  export declare function isTruncated(reply: PullReply): boolean;
120
- /** One entry of a device check: `[pullCapability, schema, epoch, version, resume?]`. */
122
+ /** One device check entry. A custom window adds a nullable resume slot and the number of days. */
121
123
  export interface SyncEntry {
122
124
  capability: string;
123
125
  schema: number;
124
126
  epoch: string;
125
127
  version: number;
126
128
  resume?: string;
129
+ windowDays?: number;
127
130
  }
128
131
  /** The pull request the node sends the app for one entry of a check. */
129
132
  export declare function pullRequestOf(entry: SyncEntry, limit: number): PullRequest;
@@ -162,6 +165,7 @@ export interface SyncReply {
162
165
  /** The payload of `core.replica.announce`. */
163
166
  export interface Announce {
164
167
  capability: string;
168
+ windowDays?: number;
165
169
  epoch: string;
166
170
  version: number;
167
171
  }
@@ -193,7 +197,7 @@ export declare function encodedDeleteBytes(key: string): number;
193
197
  export declare function encodePullRequest(request: PullRequest): string;
194
198
  /** The exact bytes of an app's pull reply. */
195
199
  export declare function encodePullReply(reply: PullReply): string;
196
- /** `["friends.people.pull",1,"k3f9a2c1",41]` plus the resume key. */
200
+ /** Four fields normally, five with a resume key, six when selecting a custom window. */
197
201
  export declare function encodeSyncEntry(entry: SyncEntry): string;
198
202
  /** `{"c":[…]}` plus `"origin"`. */
199
203
  export declare function encodeSyncRequest(request: SyncRequest): string;
@@ -213,7 +217,7 @@ export declare function decodeRow(value: unknown): Row;
213
217
  export declare function decodePullRequest(value: unknown): PullRequest;
214
218
  /** An app's pull reply. */
215
219
  export declare function decodePullReply(value: unknown): PullReply;
216
- /** One entry of a check: `[capability, schema, epoch, version, resume?]`. */
220
+ /** One entry of a check, with an optional resume key and custom window. */
217
221
  export declare function decodeSyncEntry(value: unknown): SyncEntry;
218
222
  /** The payload of `core.replica.sync`. */
219
223
  export declare function decodeSyncRequest(value: unknown): SyncRequest;
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 xn(e){return typeof e==="string"?Array.from(e).slice(0,64).join(""):""}class c 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 c("config",`${N.config} ${e}`,e)}static row(e,n){let t=xn(e);return new c("row",`${N.row} row '${t}': ${n}`,n,t)}static request(e){return new c("request",`${N.request} ${e}`,e)}static schema(e,n){let t=`schema ${n} is not served by ${e}`;return new c("schema",`${N.schema} ${t}`,t)}static load(e){return new c("load",`${N.load} ${e}`,e)}static store(e){return new c("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 kn}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 An=new TextEncoder;function O(e){if(e.length>128)return An.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&&le(e.charCodeAt(t+1)))n+=4,t+=1;else n+=3}return n}function le(e){return e>=56320&&e<=57343}function q(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t<55296||t>57343)continue;if(t<=56319&&le(e.charCodeAt(n+1))){n+=1;continue}return!0}return!1}var G=128;function Tn(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>=G)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 Ln="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 Ce(e,n){if(q(e))throw new k(`${n} holds a lone surrogate`);return JSON.stringify(e)}function ce(e,n,t){switch(typeof e){case"string":return Ce(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>=G)throw new k(Ln);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(`${Ce(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"),Sn=/^(?:0|[1-9][0-9]*)$/,$n=/[\ud800-\uffff]/,W=new Map,On=64,_n=8;function Pe(e){if(e.some((n)=>n==="__proto__"||Sn.test(n)||$n.test(n)))return null;return e.sort()}function Mn(e){if(e.length<=_n)return Pe(e);let n=JSON.stringify(e),t=W.get(n);if(t===void 0){if(t=Pe(e),W.size>=On)W.clear();W.set(n,t)}return t}function ae(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>=G)return x;if(Array.isArray(e)){let o=[];for(let i=0;i<e.length;i+=1){let s=e[i]===void 0?x:ae(e[i],n+1);if(s===x)return x;o.push(s)}return o}if(!Ie(e))return x;let t=Mn(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=ae(i,n+1);if(s===x)return x;r[o]=s}return r}function K(e){let n=ae(e,0);if(n!==x){let t=JSON.stringify(n);if(!t.includes("\\ud"))return t}return Nn(e)}function Nn(e){return ce(e,"value",0)}class De{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&&le(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 Cn(e){return new De().update(e).hex()}function ue(e){let n=K(e.value),t=`[${n},${e.ord},${JSON.stringify(e.part)}]`;return{digest:`s1.${kn("sha256").update(t).digest("hex").slice(0,32)}`,valueBytes:O(n)}}function Pn(e){return ue(e).digest}var He=256,he=65536,I=Number.MAX_SAFE_INTEGER,fe=128,ft=16,pe=500,ge=262144,pt=64,gt=786432,yt="core.replica.sync",Ue="core.replica.announce",mt="replica_schema_unsupported:";function B(e){if(typeof e!=="object"||e===null)throw c.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 c.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 wt(e){return{epoch:"",version:0,schema:e,limit:pe}}function ye(e){return Math.min(e.limit,pe)}function Fe(e){if(e.epoch!==""&&!me(e.epoch))return'e must be "" or 1-16 characters of [a-z0-9]';if(e.version>I)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=Q(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 vt(e){if(e.kind==="changes")return e.more;if(e.kind==="full-copy")return e.next!==void 0;return!1}function bt(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 In=["unknown","schema","unavailable","busy"];function Et(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 me(e){return/^[a-z0-9]{1,16}$/.test(e)}var Dn=/[\u0000-\u001f\u007f-\u009f]/;function Q(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>He)return`key is ${n} bytes; at most ${He} are allowed`;if(Dn.test(e))return"key must not contain control characters";if(q(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 c.store(`${e} is not an integer within 2^53 - 1`);return String(e)}function Hn(e){try{return K(e.value)}catch(n){if(n instanceof k)throw c.row(e.key,n.message);throw n}}var qe=new WeakMap;function Be(e){let n=qe.get(e);if(n!==void 0)return n;let t=`[${p(e.key)},${Hn(e)}`;if(e.part!=="")return`${t},${b(e.ord)},${p(e.part)}]`;if(e.ord!==0)return`${t},${b(e.ord)}]`;return`${t}]`}function we(e){let n=Be(e);return qe.set(e,n),O(n)+1}function Xe(e){return O(p(e))+1}function je(e){return`[${e.map(Be).join(",")}]`}function Un(e){return`[${e.map(p).join(",")}]`}function xt(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 Ye(e,n,t,r){return`"v":${b(e)},"u":${je(n)},"x":${Un(t)}${r?',"m":1':""}`}function ze(e,n,t,r){return`"e":${p(e)},"v":${b(n)},"f":1,"u":${je(t)}${r===void 0?"":`,"n":${p(r)}`}`}function ee(e){switch(e.kind){case"nothing-new":return`{"e":${p(e.epoch)},"v":${b(e.version)}}`;case"changes":return`{"e":${p(e.epoch)},${Ye(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":{let n=e.head===void 0?"":`,"h":${b(e.head)}`;return`{${ze(e.epoch,e.version,e.rows,e.next)}${n}}`}}}function Fn(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 kt(e){let n=e.origin===void 0?"":`,"origin":${p(e.origin)}`;return`{"c":[${e.entries.map(Fn).join(",")}]${n}}`}function qn(e){switch(e.kind){case"nothing-new":return"0";case"changes":return`{${Ye(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":return`{${ze(e.epoch,e.version,e.rows,e.next)}}`;case"error":return`{"err":${p(e.code)}}`}}function At(e){return`{"r":[${e.answers.map(qn).join(",")}]}`}function Ve(e){return`{"c":${p(e.capability)},"e":${p(e.epoch)},"v":${b(e.version)}}`}function Tt(e){return e==="ok"?'{"ok":true}':'{"rotate":true}'}function Lt(e){return`{"h":[${e.heads.map((t)=>`[${p(t.capability)},${p(t.epoch)},${b(t.version)}]`).join(",")}]}`}function g(e){return c.request(e)}function We(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function C(e,n){if(!We(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 E(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=I){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>t){let r=t===I?"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 de=4294967295;function J(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 Bn(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 Z(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw g(`${n} must be an array of row entries`);return e.map(Bn)}function Ge(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 ne(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",de),limit:t===void 0?pe:A(t,"l",de)},o=R(n,"a");if(o!==void 0)r.resume=y(o,"a");return r}function St(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 g("a pull reply: missing field `e`");let o=y(r,"e"),i=R(n,"u"),s=R(n,"x");if(J(n,"f")){let l={kind:"full-copy",epoch:o,version:t,rows:Z(i,"u")},d=R(n,"n");if(d!==void 0)l.next=y(d,"n");let u=R(n,"h");if(u!==void 0)l.head=A(u,"h");return l}if(i!==void 0||s!==void 0)return{kind:"changes",epoch:o,version:t,upserts:Z(i,"u"),deletes:Ge(s,"x"),more:J(n,"m")};return{kind:"nothing-new",epoch:o,version:t}}function Xn(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",de),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 $t(e){let n=C(e,"a sync request"),t=E(n,"c","a sync request");if(!Array.isArray(t))throw g("c must be an array of sync entries");let r={entries:t.map(Xn)},o=R(n,"origin");if(o!==void 0)r.origin=y(o,"origin");return r}function jn(e){if(e===0)return{kind:"nothing-new"};if(!We(e))throw g("a sync answer is 0, a changes object, a full copy or an error");if("err"in e){let t=In.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(E(e,"v","a sync answer"),"v");if(J(e,"f")){let t={kind:"full-copy",epoch:y(E(e,"e","a sync answer"),"e"),version:n,rows:Z(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:Z(R(e,"u"),"u"),deletes:Ge(R(e,"x"),"x"),more:J(e,"m")}}function Ot(e){let n=E(C(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(jn)}}function _t(e){let n=C(e,"an announce");return{capability:y(E(n,"c","an announce"),"c"),epoch:y(E(n,"e","an announce"),"e"),version:A(E(n,"v","an announce"),"v")}}function Ke(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 g(`${i} must be a boolean`);return s},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 Mt(e){let n=E(C(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 Je=2592000000,Ze=5000,Qe=60000,Re={maxAgeMs:Je,maxCount:Ze};function _(e){return{epoch:e.epoch,version:e.version}}function X(e,n){return e.epoch===n.epoch&&e.version===n.version}function ve(e){return e.map((n)=>({row:n,digest:re(n)}))}function re(e){let n=Q(e.key);if(n!==null)throw c.row(e.key,n);let t,r;try{({digest:t,valueBytes:r}=ue(e))}catch(i){if(i instanceof k)throw c.row(e.key,i.message);throw i}if(r>he)throw c.row(e.key,`value is ${r} bytes encoded; at most ${he} are allowed`);if(!Number.isInteger(e.ord)||Math.abs(e.ord)>I)throw c.row(e.key,"ord must be within \xB1(2^53 - 1)");if(typeof e.part!=="string")throw c.row(e.key,"part must be a string");let o=O(e.part);if(o>fe)throw c.row(e.key,`part is ${o} bytes; at most ${fe} are allowed`);if(q(e.part))throw c.row(e.key,"part must not contain a lone surrogate");return t}function en(e,n){for(let t=0;t<4;t+=1){let r=e.env.newEpoch();if(!me(r))throw c.store("the environment produced an epoch outside [a-z0-9]{1,16}");if(r!==n)return r}throw c.store("the environment keeps producing the current epoch")}function te(e,n,t){if(t.rotateOwed)U(e,n,t);if(t.version>=I)throw c.store(`version of ${t.epoch} would pass 2^53 - 1`);return t.version+=1,t.version}function nn(e,n){let t=e.record(n.name);if(t!==null)return t;let r={epoch:en(n,null),version:0,floor:0,dirty:!0,rotatedAt:n.env.nowMs(),reconciledAt:0,rotateOwed:!1};return e.putRecord(n.name,r),r}function be(e,n){let t=e.env.nowMs();return n.rotatedAt===0||t<n.rotatedAt||t-n.rotatedAt>=Qe}function Ee(e,n,t){if(be(n,t))return U(e,n,t),!0;return t.rotateOwed=!0,!1}function tn(e,n,t,r){if(r||t.rotateOwed&&be(n,t))return U(e,n,t),!0;return!1}function rn(e,n){return!(n.rotateOwed&&be(e,n))}function U(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=en(n,t.epoch),t.version=o,t.floor=0,t.rotatedAt=r,t.rotateOwed=!1}function on(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=te(e,n,t);return e.putEntry(n.name,{key:r.key,digest:o,version:l,deleted:!1,changedAt:i}),!0}function sn(e,n,t,r,o){let i=e.entry(n.name,r);if(i===null||i.deleted)return!1;let s=te(e,n,t);return e.putEntry(n.name,{key:r,digest:i.digest,version:s,deleted:!0,changedAt:o}),!0}function xe(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)Ee(e,n,t)}function ke(e,n,t,r){let o=n.env.nowMs(),i=[...r];i.sort((a,f)=>L(a.row.key,f.row.key));for(let a=1;a<i.length;a+=1){let f=i[a-1],h=i[a];if(f!==void 0&&h!==void 0&&f.row.key===h.row.key)throw c.row(f.row.key,"the key appears twice in the list")}let s=e.entries(n.name),l=[],d=[],u=0;for(let a of i){while(u<s.length&&L(D(s,u).key,a.row.key)<0){let h=D(s,u);if(!h.deleted)d.push(h);u+=1}let f=!1;if(u<s.length&&D(s,u).key===a.row.key){let h=D(s,u);f=!h.deleted&&h.digest===a.digest,u+=1}if(!f)l.push(a)}for(;u<s.length;u+=1){let a=D(s,u);if(!a.deleted)d.push(a)}for(let{row:a,digest:f}of l){let h=te(e,n,t);e.putEntry(n.name,{key:a.key,digest:f,version:h,deleted:!1,changedAt:o})}for(let a of d){let f=te(e,n,t);e.putEntry(n.name,{key:a.key,digest:a.digest,version:f,deleted:!0,changedAt:o})}xe(e,n,t,o),t.dirty=!1,t.reconciledAt=o}function D(e,n){let t=e[n];if(t===void 0)throw c.store("ledger index out of range");return t}function cn(e,n,t,{row:r,digest:o}){let i=n.env.nowMs();on(e,n,t,r,o,i),xe(e,n,t,i)}function an(e,n,t,r){let o=Q(r);if(o!==null)throw c.row(r,o);let i=n.env.nowMs();sn(e,n,t,r,i),xe(e,n,t,i)}function H(e,n,t,r,o){return{kind:"full-copy",version:r,entries:e.liveAfter(n.name,t,o)}}function Yn(e,n,t,r){let o=ye(r)+1;if(r.epoch!==t.epoch)return H(e,n,null,t.version,o);if(r.version>t.version)return U(e,n,t),H(e,n,null,t.version,o);if(r.resume!==void 0){if(r.version>=t.floor)return H(e,n,r.resume,r.version,o);return H(e,n,null,t.version,o)}if(r.version<t.floor)return H(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 zn(e,n,t,r,o){let i=n.env.nowMs(),s=!1;for(let l of r){if(l.deleted)continue;let d=o.get(l.key);if(d===void 0)s=sn(e,n,t,l.key,i)||s;else{let u=re(d);if(u!==l.digest)s=on(e,n,t,d,u,i)||s}}return s}function Ae(e,n){if(!e.schemas.includes(n.schema))throw c.schema(e.name,n.schema);let t=Fe(n);if(t!==null)throw c.request(t)}function ln(e,n){let t;try{t=e(n)}catch(r){throw c.load(w(r))}return t.map(B)}function Te(e){return ve(ln(e,null))}function un(e,n,t,r,o,i){if(Ae(n,r),t.dirty)ke(e,n,t,i??Te(o));let s=ye(r),l=!1,d=0;for(;;){let u=l?H(e,n,null,t.version,s+1):Yn(e,n,t,r);if(u.kind==="nothing-new")return{kind:"nothing-new",epoch:t.epoch,version:t.version};let a=u.entries.slice(0,s),f=a.filter((S)=>!S.deleted).map((S)=>S.key),h=new Map;if(f.length>0){let S=new Set(f);for(let P of ln(o,f))if(S.has(P.key))h.set(P.key,P)}if(d<2&&zn(e,n,t,a,h)){d+=1;continue}let T=Vn(t,r,u,s,h);if(T!==null)return T;if(l)throw c.store("a full copy could not be built");l=!0}}function Vn(e,n,t,r,o){if(t.kind==="changes"){let a=[],f=0,h=!1;for(let m of t.entries){if(a.length===r){h=!0;break}let F=o.get(m.key),Ne=m.deleted?Xe(m.key):F!==void 0?we(F):0;if(a.length>0&&f+Ne>ge){h=!0;break}f+=Ne,a.push(m)}let T;if(h){let m=0;while(m<a.length&&a[m]?.version===n.version+m+1)m+=1;if(m===0)return null;a.length=m,T=n.version+m}else T=e.version;let S=[],P=[];for(let m of a){if(m.deleted){P.push(m.key);continue}let F=o.get(m.key);if(F!==void 0)S.push(F)}return{kind:"changes",epoch:e.epoch,version:T,upserts:S,deletes:P,more:h}}let i=[],s=0,l=null,d=!1;for(let a=0;a<t.entries.length;a+=1){let f=D(t.entries,a);if(a===r){d=!0;break}let h=o.get(f.key);if(h===void 0){l=f.key;continue}let T=we(h);if(a>0&&s+T>ge){d=!0;break}i.push(h),s+=T,l=f.key}let u={kind:"full-copy",epoch:e.epoch,version:t.version,rows:i};if(d&&l!==null)u.next=l;if(e.version>t.version)u.head=e.version;return u}function Le(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 Gn(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 dn(e){let n=new Map;for(let[t,r]of e)n.set(t,Gn(r));return n}function hn(e){if(e===void 0)return[];return[...e.entries.values()].sort((n,t)=>L(n.key,t.key))}class fn{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 hn(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 hn(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((u)=>u.deleted).sort((u,a)=>u.version-a.version||u.changedAt-a.changedAt||L(u.key,a.key)),s=Math.max(0,i.length-t),l=null,d=0;return i.forEach((u,a)=>{if(a<s||u.changedAt<n)this.saveEntry(r,e,u.key),o.delete(u.key),l=l===null?u.version:Math.max(l,u.version);else d+=1}),{highest:l,overKeep:d>t}}}class Se{tables=new Map;ensure(){}write(e,n){let t=new fn(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 Se;return e.tables=dn(this.tables),e}restoreFrom(e){this.tables=dn(e.tables)}}var wn={nowMs:()=>Date.now(),newEpoch:Kn},pn="abcdefghijklmnopqrstuvwxyz0123456789",gn=0;function Kn(){let e=new Uint8Array(8),n=globalThis.crypto;if(n?.getRandomValues!==void 0)n.getRandomValues(e);else{gn+=1;let r=Date.now()+gn;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+=pn.charAt(r%pn.length);return t}var Jn=16,Zn=/^[a-z][a-z0-9_-]*$/,Qn=/^(?:[A-Za-z_][A-Za-z0-9_]{0,47})?$/;class oe{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??wn,horizon:t.horizon??Re}}check(){let e=this.name.split(".");if(e.length<3||e[e.length-1]!=="pull"||!e.every((n)=>Zn.test(n)))throw c.config(`'${this.name}' is not a pull capability '<app>.<collection>.pull'`);if(this.name.startsWith("core."))throw c.config(`'${this.name}' is in the reserved 'core.' namespace`);if(!Qn.test(this.tablePrefix))throw c.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 c.config("the tombstone horizon must keep at least one tombstone");if(!this.schemas.every((n)=>Number.isInteger(n)&&n>=0&&n<=4294967295))throw c.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,Jn)}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=nn(t,this.spec),o={...r},i=tn(t,this.spec,r,this.wentBack(r)),s=e(t,r,i);if(!yn(r,o))t.putRecord(this.spec.name,r);n={value:s}}),n===null)throw c.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=Le(this.store,this.tablePrefix,this.name);if(e===null||this.wentBack(e)||!rn(this.spec,e))return null;return e}ensure(){this.check(),this.store.ensure(this.tablePrefix)}reconcile(e){let n=e.map(B),t=this.before(()=>ve(n));return this.withRecord((r,o)=>{let i=_(o);return ke(r,this.spec,o,t),X(_(o),i)?null:o.version})}touch(e){let n=B(e),t=this.before(()=>({row:n,digest:re(n)}));return this.withRecord((r,o)=>(cn(r,this.spec,o,t),o.version))}remove(e){return this.withRecord((n,t)=>(an(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||Ee(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(Ae(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=Le(this.store,this.tablePrefix,this.name),r=t===null||t.dirty?this.before(()=>Te(n)):null,{answered:o,head:i}=this.withRecord((s,l,d)=>{let u=_(l),a=t===null?l.version===0:yn(l,t),f=un(s,this.spec,l,e,n,a?r:null),h=_(l);return{answered:{reply:f,headMoved:d||!X(h,u)},head:h}});return this.noteHandedOut(i.epoch,i.version),o}pull(e,n){return JSON.parse(ee(this.answer(ne(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 mn(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)U(r,this.spec,o);return _(o)});if(await mn(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 yn(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 mn(e,n,t){let r=JSON.parse(Ve({capability:e,epoch:n.epoch,version:n.version})),o=await t(Ue,r);try{return Ke(o)}catch(i){throw Error(`unexpected announce reply: ${w(i)}`)}}var ie=2;function $e(e){return{meta:`${e}replica_meta`,collections:`${e}replica_collections`,rows:`${e}replica_rows`}}function et(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 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} (
3
3
  name TEXT PRIMARY KEY NOT NULL,
4
4
  epoch TEXT NOT NULL,
5
5
  version INTEGER NOT NULL DEFAULT 0,
@@ -15,17 +15,17 @@ var N={config:"replica_config_invalid:",row:"replica_row_invalid:",request:"repl
15
15
  deleted INTEGER NOT NULL DEFAULT 0,
16
16
  changed_at INTEGER NOT NULL,
17
17
  PRIMARY KEY (collection, row_key)
18
- )`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_version ON ${n.rows} (collection, version)`)}function nt(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)
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 tt=[nt];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 c.store(`${n} in the replica ledger is not an integer within 2^53 - 1: ${String(e)}`)}function M(e,n){let t=V(e,n);if(t<0)throw c.store(`negative ${t} in the replica ledger`);return t}function _e(e,n){if(typeof e!=="string")throw c.store(`${n} in the replica ledger is not text`);return e}function v(e,n){if(typeof e!=="object"||e===null)throw c.store("the replica ledger returned a non-row");return e[n]}var Rn="epoch, version, floor, dirty, rotated_at, reconciled_at, rotate_owed",j="row_key, digest, version, deleted, changed_at";function rt(e){return{epoch:_e(v(e,"epoch"),"an epoch"),version:M(v(e,"version"),"a version"),floor:M(v(e,"floor"),"a floor"),dirty:V(v(e,"dirty"),"dirty")!==0,rotatedAt:M(v(e,"rotated_at"),"rotated_at"),reconciledAt:M(v(e,"reconciled_at"),"reconciled_at"),rotateOwed:V(v(e,"rotate_owed"),"rotate_owed")!==0}}function Y(e){return{key:_e(v(e,"row_key"),"a row key"),digest:_e(v(e,"digest"),"a digest"),version:M(v(e,"version"),"a version"),deleted:V(v(e,"deleted"),"deleted")!==0,changedAt:M(v(e,"changed_at"),"changed_at")}}function Oe(e){try{return e()}catch(n){if(n instanceof c)throw n;throw c.store(w(n))}}class vn{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, ${Rn})
20
+ WHERE deleted = 1`)}var ot=[rt];function W(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=W(e,n);if(t<0)throw a.store(`negative ${t} in the replica ledger`);return t}function Me(e,n){if(typeof e!=="string")throw a.store(`${n} in the replica ledger is not text`);return e}function v(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",Y="row_key, digest, version, deleted, changed_at";function it(e){return{epoch:Me(v(e,"epoch"),"an epoch"),version:M(v(e,"version"),"a version"),floor:M(v(e,"floor"),"a floor"),dirty:W(v(e,"dirty"),"dirty")!==0,rotatedAt:M(v(e,"rotated_at"),"rotated_at"),reconciledAt:M(v(e,"reconciled_at"),"reconciled_at"),rotateOwed:W(v(e,"rotate_owed"),"rotate_owed")!==0}}function z(e){return{key:Me(v(e,"row_key"),"a row key"),digest:Me(v(e,"digest"),"a digest"),version:M(v(e,"version"),"a version"),deleted:W(v(e,"deleted"),"deleted")!==0,changedAt:M(v(e,"changed_at"),"changed_at")}}function _e(e){try{return e()}catch(n){if(n instanceof a)throw n;throw a.store(w(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 ${j} FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).get(e,n);return t===null||t===void 0?null:Y(t)}entries(e){return this.q(`SELECT ${j} FROM ${this.t.rows} WHERE collection = ?1 ORDER BY row_key`).all(e).map(Y)}putEntry(e,n){this.q(`INSERT INTO ${this.t.rows} (collection, row_key, digest, version, deleted, changed_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 ${Y} FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).get(e,n);return t===null||t===void 0?null:z(t)}entries(e){return this.q(`SELECT ${Y} FROM ${this.t.rows} WHERE collection = ?1 ORDER BY row_key`).all(e).map(z)}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 ${j} FROM ${this.t.rows} WHERE collection = ?1 AND version > ?2
28
- ORDER BY version LIMIT ?3`).all(e,n,t).map(Y)}liveAfter(e,n,t){if(n===null)return this.q(`SELECT ${j} FROM ${this.t.rows} WHERE collection = ?1 AND deleted = 0
29
- ORDER BY row_key LIMIT ?2`).all(e,t).map(Y);return this.q(`SELECT ${j} 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(Y)}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"),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 l=this.q(`SELECT version FROM ${r} WHERE collection = ?1 AND deleted = 1 ORDER BY version DESC LIMIT 1 OFFSET ?2`).get(e,t),d=l===null||l===void 0?null:M(v(l,"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:s===null?d:d===null?s:Math.max(s,d),overKeep:!1}}}var z="node_app_replica";class se{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 ${z}`:"COMMIT")}catch(r){try{if(this.db.exec(n?`ROLLBACK TO ${z}`:"ROLLBACK"),n)this.db.exec(`RELEASE ${z}`)}catch{}if(r instanceof c)throw r;throw c.store(w(r))}return t}begin(){if(this.db.inTransaction===!0)return Oe(()=>this.db.exec(`SAVEPOINT ${z}`)),!0;try{return this.db.exec("BEGIN IMMEDIATE"),!1}catch(e){if(this.db.inTransaction===void 0&&this.insideAppTransaction())return Oe(()=>this.db.exec(`SAVEPOINT ${z}`)),!0;throw c.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=$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=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 et(this.db,e),t=1;if(t<1||t>ie)throw c.store(`the replica ledger's layout is ${t}; this helper knows layouts 1 to ${ie}`);while(t<ie){let r=tt[t-1];if(r===void 0)throw c.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 vn(this,t)))}readRecordIn(e,n){let t=this.statement(`SELECT ${Rn} FROM ${e.collections} WHERE name = ?1`).get(n);return t===null||t===void 0?null:rt(t)}readRecord(e,n){return Oe(()=>this.readRecordIn($e(e),n))}}function ot(e){return typeof e.write==="function"&&typeof e.ensure==="function"}var bn=0;function Jt(e,n=5000){return async(t,r)=>{bn+=1;let o=`replica-${Date.now().toString(36)}-${bn.toString(36)}`,i=await e({id:o,capability:t,payload:r},n);if(!i.success)throw Error(w(i.payload));return i.payload}}var it=2000,st=60000;class Me{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 En{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 Me(i.firstMs,i.maxMs,()=>this.reconcileNow()),this.announceRetry=new Me(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||!X(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 ct{invoke;options;store;collections=new Map;tablePrefix;warn;constructor(e,n,t={}){this.invoke=n;this.options=t;this.store=ot(e)?e:new se(e),this.tablePrefix=t.tablePrefix??"",this.warn=t.warn??((r)=>console.warn(r))}collection(e,n){if(this.collections.has(e))throw c.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 oe(this.store,e,t);r.ensure();let o={firstMs:this.options.retry?.firstMs??it,maxMs:this.options.retry?.maxMs??st},i=new En(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 c.request(`${e} is not a replicated collection of this app`);let r=t.ledger.answer(ne(n),(o)=>t.load(o));if(r.headMoved)t.announce();return Promise.resolve(JSON.parse(ee(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{Ue as ANNOUNCE_CAPABILITY,oe as CollectionLedger,Re as DEFAULT_HORIZON,ie as LEDGER_LAYOUT,ft as MAX_EPOCH_CHARS,He as MAX_KEY_BYTES,fe as MAX_PART_BYTES,ge as MAX_REPLY_ROW_BYTES,pe as MAX_ROWS_PER_REPLY,I as MAX_SAFE_INTEGER,pt as MAX_SYNC_ENTRIES,gt as MAX_SYNC_REPLY_BYTES,he as MAX_VALUE_BYTES,G as MAX_VALUE_DEPTH,Se as MemoryLedger,N as REPLICA_ERROR_PREFIXES,Qe as ROTATION_MIN_INTERVAL_MS,ct as Replica,c as ReplicaError,mt as SCHEMA_UNSUPPORTED_PREFIX,yt as SYNC_CAPABILITY,se as SqliteLedgerStore,Je as TOMBSTONE_MAX_AGE_MS,Ze as TOMBSTONE_MAX_COUNT,K as canonicalJson,Hn as canonicalValue,L as compareUtf8,_t as decodeAnnounce,Ke as decodeAnnounceReply,Mt as decodeHeadsData,St as decodePullReply,ne as decodePullRequest,Bn as decodeRow,jn as decodeSyncAnswer,Xn as decodeSyncEntry,Ot as decodeSyncReply,$t as decodeSyncRequest,ye as effectiveLimit,Ve as encodeAnnounce,Tt as encodeAnnounceReply,Lt as encodeHeadsData,ee as encodePullReply,xt as encodePullRequest,Be as encodeRow,qn as encodeSyncAnswer,Fn as encodeSyncEntry,At as encodeSyncReply,kt as encodeSyncRequest,Xe as encodedDeleteBytes,we as encodedRowBytes,Cn as fnv1a64,Rt as handedOut,Jt as hostInvoke,wt as initialPullRequest,me as isEpoch,vt as isTruncated,Tn as isWithinValueDepth,Q as keyProblem,bt as pullRequestOf,Fe as pullRequestProblem,Pn as rowDigest,Et as syncAnswerOf,wn as systemEnvironment,B as toRow,O as utf8Length};
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 ${Y} FROM ${this.t.rows} WHERE collection = ?1 AND version > ?2
28
+ ORDER BY version LIMIT ?3`).all(e,n,t).map(z)}liveAfter(e,n,t){if(n===null)return this.q(`SELECT ${Y} FROM ${this.t.rows} WHERE collection = ?1 AND deleted = 0
29
+ ORDER BY row_key LIMIT ?2`).all(e,t).map(z);return this.q(`SELECT ${Y} 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(z)}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"),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 l=this.q(`SELECT version FROM ${r} WHERE collection = ?1 AND deleted = 1 ORDER BY version DESC LIMIT 1 OFFSET ?2`).get(e,t),u=l===null||l===void 0?null:M(v(l,"version"),"a version");if(u!==null)this.q(`DELETE FROM ${r} WHERE collection = ?1 AND deleted = 1 AND version <= ?2`).run(e,u);return{highest:s===null?u:u===null?s:Math.max(s,u),overKeep:!1}}}var V="node_app_replica";class ae{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 ${V}`:"COMMIT")}catch(r){try{if(this.db.exec(n?`ROLLBACK TO ${V}`:"ROLLBACK"),n)this.db.exec(`RELEASE ${V}`)}catch{}if(r instanceof a)throw r;throw a.store(w(r))}return t}begin(){if(this.db.inTransaction===!0)return _e(()=>this.db.exec(`SAVEPOINT ${V}`)),!0;try{return this.db.exec("BEGIN IMMEDIATE"),!1}catch(e){if(this.db.inTransaction===void 0&&this.insideAppTransaction())return _e(()=>this.db.exec(`SAVEPOINT ${V}`)),!0;throw a.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=Oe(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=W(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 tt(this.db,e),t=1;if(t<1||t>se)throw a.store(`the replica ledger's layout is ${t}; this helper knows layouts 1 to ${se}`);while(t<se){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=Oe(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 _e(()=>this.readRecordIn(Oe(e),n))}}function st(e){return typeof e.write==="function"&&typeof e.ensure==="function"}var xn=0;function Qt(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(w(i.payload));return i.payload}}var at=2000,ct=60000;class Ne{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 Ne(i.firstMs,i.maxMs,()=>this.reconcileNow()),this.announceRetry=new Ne(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||!j(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 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 ae(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 ie(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(te(n),(o)=>t.load(o));if(r.headMoved)t.announce();return Promise.resolve(JSON.parse(ne(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{Fe as ANNOUNCE_CAPABILITY,ie as CollectionLedger,ve as DEFAULT_HORIZON,se as LEDGER_LAYOUT,gt as MAX_EPOCH_CHARS,Ue as MAX_KEY_BYTES,pe as MAX_PART_BYTES,ye as MAX_REPLY_ROW_BYTES,ge as MAX_ROWS_PER_REPLY,D as MAX_SAFE_INTEGER,yt as MAX_SYNC_ENTRIES,mt as MAX_SYNC_REPLY_BYTES,fe as MAX_VALUE_BYTES,K as MAX_VALUE_DEPTH,$e as MemoryLedger,N as REPLICA_ERROR_PREFIXES,nn as ROTATION_MIN_INTERVAL_MS,lt as Replica,a as ReplicaError,Rt as SCHEMA_UNSUPPORTED_PREFIX,wt as SYNC_CAPABILITY,ae as SqliteLedgerStore,Qe as TOMBSTONE_MAX_AGE_MS,en as TOMBSTONE_MAX_COUNT,J as canonicalJson,Fn as canonicalValue,L as compareUtf8,Nt as decodeAnnounce,Ze as decodeAnnounceReply,Ct as decodeHeadsData,Ot as decodePullReply,te as decodePullRequest,jn as decodeRow,zn as decodeSyncAnswer,Yn as decodeSyncEntry,Mt as decodeSyncReply,_t as decodeSyncRequest,me as effectiveLimit,We as encodeAnnounce,St as encodeAnnounceReply,$t as encodeHeadsData,ne as encodePullReply,At as encodePullRequest,Xe as encodeRow,Xn as encodeSyncAnswer,Bn as encodeSyncEntry,Lt as encodeSyncReply,Tt as encodeSyncRequest,je as encodedDeleteBytes,Re as encodedRowBytes,Dn as fnv1a64,bt as handedOut,Qt as hostInvoke,vt as initialPullRequest,we as isEpoch,Et as isTruncated,Sn as isWithinValueDepth,ee as keyProblem,xt as pullRequestOf,qe as pullRequestProblem,In as rowDigest,kt as syncAnswerOf,vn as systemEnvironment,X 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.16",
3
+ "version": "7.7.18",
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",