@loro-dev/flock-sqlite 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- let e=require(`@loro-dev/unisqlite`);const t=16,n=17,r=18,i=32,a=33,o=34,s=35,c=36,l=37,u=new TextEncoder;function ee(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function te(e){let t=BigInt(e),n=[];do{let e=Number(t&127n);t>>=7n,t!==0n&&(e|=128),n.push(e)}while(t!==0n);return new Uint8Array(n)}function ne(e){let t=BigInt(e),n=[],r=!0;for(;r;){let e=Number(t&127n);t>>=7n;let i=(e&64)!=0;t===0n&&!i||t===-1n&&i?r=!1:e|=128,n.push(e)}return new Uint8Array(n)}async function re(e){let t=typeof crypto<`u`?crypto:void 0;if(t?.subtle){let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=await t.subtle.digest(`SHA-256`,n);return new Uint8Array(r)}try{let{createHash:t}=await import(`crypto`),n=t(`sha256`);return n.update(e),new Uint8Array(n.digest())}catch{throw Error(`No crypto implementation available for digest`)}}var ie=class{chunks=[];writeTag(e){this.chunks.push(e&255)}writeBool(e){this.chunks.push(e?1:0)}writeBytes(e){this.writeLen(e.length);for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeRawBytes(e){for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeLen(e){this.writeRawBytes(te(e))}writeI64(e){this.writeRawBytes(ne(e))}writeF64(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e,!1);let n=new Uint8Array(t.buffer);this.writeRawBytes(n)}writeString(e){this.writeBytes(u.encode(e))}writeJson(e){if(e===null){this.writeTag(32);return}if(typeof e==`boolean`){this.writeTag(33),this.writeBool(e);return}if(typeof e==`number`){this.writeTag(34),this.writeF64(e);return}if(typeof e==`string`){this.writeTag(35),this.writeString(e);return}if(Array.isArray(e)){this.writeTag(36),this.writeLen(e.length);for(let t of e)this.writeJson(t);return}if(e&&typeof e==`object`){let t=Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeTag(37),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n);return}throw TypeError(`Unsupported JSON value in digest`)}writeRawValue(e){if(this.writeTag(16),e.data===void 0?this.writeBool(!1):(this.writeBool(!0),this.writeJson(e.data)),this.writeTag(18),!e.metadata||typeof e.metadata!=`object`)this.writeBool(!1);else{let t=Object.entries(e.metadata).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeBool(!0),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n)}this.writeTag(17),this.writeF64(e.clock.physicalTime),this.writeI64(Math.trunc(e.clock.logicalCounter)),this.writeBytes(u.encode(e.clock.peerId))}async finish(){return re(new Uint8Array(this.chunks))}};function ae(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch{return}}function oe(e){if(e!=null)return JSON.parse(e)}async function se(e){let t=oe(e.data);if(t===void 0)return null;let n=ae(e.metadata),r=new ie;return r.writeBytes(e.key),r.writeRawValue({data:t,metadata:n,clock:{physicalTime:Number(e.physical),logicalCounter:Number(e.logical),peerId:String(e.peer)}}),r.finish()}async function ce(e){let t=new Uint8Array(32);for(let n of e){let e=await se(n);if(e)for(let n=0;n<t.length;n+=1)t[n]^=e[n]}return ee(t)}var le=class{txnEventSink;debounceState;runtime;emit;constructor(e){this.runtime=e.runtime,this.emit=e.emit,this.txnEventSink=void 0,this.debounceState=void 0}handleCommitEvents(e,t,n){if(t.length!==0){if(n&&this.txnEventSink){this.txnEventSink.push(...t);return}if(n&&this.debounceState){this.debounceState.pendingEvents.push(...t),this.resetDebounceTimer();return}this.emit(e,t)}}beforeImport(){this.debounceState!==void 0&&this.commit()}async txn(e){if(this.txnEventSink!==void 0)throw Error(`Nested transactions are not supported`);if(this.debounceState!==void 0)throw Error(`Cannot start transaction while autoDebounceCommit is active`);let t=[];this.txnEventSink=t;try{let n=await e();return t.length>0&&this.emit(`local`,t),n}finally{this.txnEventSink=void 0}}isInTxn(){return this.txnEventSink!==void 0}autoDebounceCommit(e,t){if(this.txnEventSink!==void 0)throw Error(`Cannot enable autoDebounceCommit while transaction is active`);if(this.debounceState!==void 0)throw Error(`autoDebounceCommit is already active`);this.debounceState={timeout:e,maxDebounceTime:t?.maxDebounceTime??1e4,timerId:void 0,maxTimerId:void 0,pendingEvents:[]}}disableAutoDebounceCommit(){if(this.debounceState===void 0)return;let{timerId:e,maxTimerId:t,pendingEvents:n}=this.debounceState;e!==void 0&&this.runtime.clearTimeout(e),t!==void 0&&this.runtime.clearTimeout(t),this.debounceState=void 0,n.length>0&&this.emit(`local`,n)}commit(){if(this.debounceState===void 0)return;let{timerId:e,maxTimerId:t,pendingEvents:n}=this.debounceState;e!==void 0&&(this.runtime.clearTimeout(e),this.debounceState.timerId=void 0),t!==void 0&&(this.runtime.clearTimeout(t),this.debounceState.maxTimerId=void 0),n.length>0&&(this.emit(`local`,n),this.debounceState.pendingEvents=[])}isAutoDebounceActive(){return this.debounceState!==void 0}close(){if(this.debounceState!==void 0&&this.disableAutoDebounceCommit(),this.txnEventSink!==void 0){let e=this.txnEventSink;this.txnEventSink=void 0,e.length>0&&this.emit(`local`,e)}}resetDebounceTimer(){this.debounceState!==void 0&&(this.debounceState.timerId!==void 0&&this.runtime.clearTimeout(this.debounceState.timerId),this.debounceState.timerId=this.runtime.setTimeout(()=>{this.commit()},this.debounceState.timeout),this.debounceState.maxTimerId===void 0&&this.debounceState.pendingEvents.length===1&&(this.debounceState.maxTimerId=this.runtime.setTimeout(()=>{this.commit()},this.debounceState.maxDebounceTime)))}},ue=class{map=new Map;constructor(e){if(this.maxSize=e,!Number.isFinite(e)||e<=0)throw Error(`LruMap maxSize must be a positive number, got ${e}`)}get size(){return this.map.size}has(e){return this.map.has(e)}get(e){if(!this.map.has(e))return;let t=this.map.get(e);return this.map.delete(e),this.map.set(e,t),t}set(e,t){this.map.has(e)&&this.map.delete(e),this.map.set(e,t),this.evictIfNeeded()}delete(e){return this.map.delete(e)}clear(){this.map.clear()}evictIfNeeded(){for(;this.map.size>this.maxSize;){let e=this.map.keys().next().value;if(e===void 0)return;this.map.delete(e)}}},de=class{map;constructor(e){this.map=new ue(e)}has(e){return this.map.get(e)!==void 0}add(e){this.map.set(e,!0)}clear(){this.map.clear()}};const fe={hi:2146959360,lo:1};var pe=class extends Error{};function d(){throw new pe}const me=(e,t)=>e<t?-1:e>t?1:0,he=(e,t)=>e===t,f=e=>BigInt(e.hi)*4294967296n+BigInt(e.lo>>>0),ge=e=>-e,_e=(e,t)=>e+t,ve=(e,t)=>e*t,ye=(e,t)=>e/t,be=(e,t)=>e%t,xe=(e,t)=>e>>BigInt(t),Se=e=>Number(BigInt.asUintN(32,e))|0,Ce=e=>Number(BigInt.asIntN(32,e));function p(e,t){if(t<0||t>=e.length)throw Error(`Index out of bounds`)}const we=(e,t)=>e.toString(t);function Te(e,t){let n=new Uint8Array(e);return t!==0&&n.fill(t),n}const m=(e,t)=>{e.push(t)},Ee={$tag:0};function De(e){this._0=e}De.prototype.$tag=1;function Oe(e){this._0=e}Oe.prototype.$tag=2;function ke(e){this._0=e}ke.prototype.$tag=3;function Ae(e){this._0=e}Ae.prototype.$tag=4;const je=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setUint32(0,t.hi),n.setUint32(4,t.lo),n.getFloat64(0)},Me=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setFloat64(0,t),{hi:n.getInt32(0),lo:n.getInt32(4)}},Ne=e=>e.hi*4294967296+(e.lo>>>0),Pe=e=>{if(isNaN(e))return{hi:0,lo:0};if(e>=0x8000000000000000)return{hi:2147483647,lo:4294967295};if(e<=-0x8000000000000000)return{hi:-2147483648,lo:0};let t=!1;e<0&&(t=!0,e=-e);let n=1/4294967296*e|0,r=e>>>0;return t&&(r===0?n=~n+1:(n=~n,r=~r+1)),{hi:n,lo:r}},Fe=new Uint8Array,h={hi:0,lo:255},Ie={hi:0,lo:0},Le={hi:-1,lo:-1},Re={hi:-2147483648,lo:0};function ze(e){this._0=e}ze.prototype.$tag=0;function Be(e){this._0=e}Be.prototype.$tag=1;function Ve(e){this._0=e}Ve.prototype.$tag=2;const g={$tag:1},He={$tag:0},Ue={hi:0,lo:1},We={hi:0,lo:256};function _(e){this._0=e}_.prototype.$tag=0;function v(e){this._0=e}v.prototype.$tag=1;function Ge(e){this._0=e}Ge.prototype.$tag=0;function Ke(e){this._0=e}Ke.prototype.$tag=1;function qe(e){this._0=e}qe.prototype.$tag=0;function Je(e){this._0=e}Je.prototype.$tag=1;function Ye(e){this._0=e}Ye.prototype.$tag=2;function Xe(e){this._0=e}Xe.prototype.$tag=3;const Ze={$tag:4},Qe={$tag:5};function $e(e){this._0=e}$e.prototype.$tag=0;function et(e){this._0=e}et.prototype.$tag=1;function tt(e){this._0=e}tt.prototype.$tag=0;function nt(e){this._0=e}nt.prototype.$tag=1;function rt(e){this._0=e}rt.prototype.$tag=2;const it={$tag:3},at={$tag:4},ot=`;`,st=1,ct=3,lt=4,ut=tn(fe);function dt(e){return d()}function ft(e){return d()}function pt(e){return d()}function y(e){d()}function mt(e){return d()}function ht(e){return en(e)}function gt(e,t){if(e.end-e.start|0){let n=e.buf[e.start],r=e.buf,i=1+e.start|0,a={buf:r,start:i,end:e.end},o=T(n),s=o.end-o.start|0,c=a.end-a.start|0,l=0;for(;;){let e=l;if(e<c){let n=r[i+e|0],a=s,o=T(n);s=a+((o.end-o.start|0)+(t.end-t.start|0)|0)|0,l=e+1|0;continue}else break}s<<=1;let u=Mt(s);if(D(u,o.str,o.start,o.end-o.start|0),Lt(t.str,0,t.start,t.end)){let e=a.end-a.start|0,t=0;for(;;){let n=t;if(n<e){let e=r[i+n|0],a=T(e);D(u,a.str,a.start,a.end-a.start|0),t=n+1|0;continue}else break}}else{let e=a.end-a.start|0,n=0;for(;;){let a=n;if(a<e){let e=r[i+a|0],o=T(e);D(u,t.str,t.start,t.end-t.start|0),D(u,o.str,o.start,o.end-o.start|0),n=a+1|0;continue}else break}}return u.val}else return``}function _t(e,t){t(t=>(Wt(e,t),1))}function vt(e,t){return gt({buf:e,start:0,end:e.length},t)}function yt(e,t){return me(e,t)}function bt(e,t){return he(e,t)}function xt(e){return ge(e)}function St(e,t){return _e(e,t)}function Ct(e,t){return ve(e,t)}function wt(e,t){return ye(e,t)}function Tt(e,t){return be(e,t)}function Et(e,t){return t<0&&y(`negative shift count`),xe(e,t)}function Dt(e){let t=Se(Et(e,32)),n=Se(e);return dn(fn(ht(t),32),ht(n))}function b(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.bytes,r=e.start+t|0;return p(n,r),n[r]}else return pt(`index out of bounds: the len is from 0 to ${E(e.end-e.start|0)} but the index is ${E(t)}`)}function x(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e,start:a,end:i}:ft(`Invalid index for View`)}function S(e,t,n){let r=e.end-e.start|0,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e.bytes,start:e.start+a|0,end:(e.start+a|0)+(i-a|0)|0}:ft(`Invalid index for View`)}function Ot(e){return t=>{let n=e.end-e.start|0,r=0;for(;;){let i=r;if(i<n){if(t(b(e,i))!==1)return 0;r=i+1|0;continue}else return 1}}}function kt(e){let t={val:0},n=e.end-e.start|0;return()=>{if(t.val<n){let n=t.val,r=e.bytes,i=e.start+n|0;p(r,i);let a=r[i];return t.val=t.val+1|0,a}else return-1}}function C(e){return yn(e.end-e.start|0,t=>Sn(e,t))}function At(e){let t=qt(e);return C({buf:t,start:0,end:t.length})}function w(e){return en(e)}function T(e){return{str:e,start:0,end:e.length}}function jt(e,t,n,r,i){if(e===n&&t<r){let a=0;for(;;){let o=a;if(o<i){let i=t+o|0,s=r+o|0;p(n,s),p(e,i),e[i]=n[s],a=o+1|0;continue}else return}}else{let a=i-1|0;for(;;){let i=a;if(i>=0){let o=t+i|0,s=r+i|0;p(n,s),p(e,o),e[o]=n[s],a=i-1|0;continue}else return}}}function Mt(e){return{val:``}}function Nt(e,t){let n=e;n.val=`${n.val}${String.fromCodePoint(t)}`}function Pt(e,t){let n=e;n.val=`${n.val}${t}`}function Ft(e,t){return yt(e,t)>0}function E(e){let t=Mt(0);return Yt(e,{self:t,method_0:Pt,method_1:D,method_2:Nt}),t.val}function It(e,t){return we(e,t)}function Lt(e,t,n,r){let i;i=r===void 0?e.length:r;let a=n,o=0;for(;;){let n=a,r=o;if(n<i&&r<t){let t=e.charCodeAt(n);if(55296<=t&&t<=56319&&(n+1|0)<i){let t=n+1|0,i=e.charCodeAt(t);if(56320<=i&&i<=57343){a=n+2|0,o=r+1|0;continue}else y(`invalid surrogate pair`)}a=n+1|0,o=r+1|0;continue}else return r===t&&n===i}}function Rt(e,t,n){let r=e.length,i;return i=n===void 0?r:n,t>=0&&t<=i&&i<=r?e.substring(t,i):d()}function D(e,t,n,r){let i=e;i.val=`${i.val}${Rt(t,n,n+r|0)}`}function zt(e){return[]}function Bt(e){return[]}function Vt(e){return[]}function Ht(e,t){m(e,t)}function Ut(e,t){m(e,t)}function O(e,t){m(e,t)}function k(e,t){m(e,t)}function Wt(e,t){m(e,t)}function Gt(e){return String.fromCodePoint(e)}function Kt(e,t){let n={val:Ee};e(e=>(t(e),1));let r=n.val;switch(r.$tag){case 0:return;case 1:r._0;return;case 2:return r._0;case 3:d();return;default:d();return}}function qt(e){let t=[];return Kt(e,e=>{O(t,e)}),t}function Jt(e){return e()}function Yt(e,t){t.method_0(t.self,It(e,10))}function Xt(e){return t=>{let n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];if(t(n)!==1)return 0;r=i+1|0;continue}else return 1}}}function Zt(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{buf:e,start:a,end:i}:mt(`View index out of bounds`)}function Qt(e){return{hi:0,lo:e}}function $t(e){return Qt(e)}function en(e){return $t(e)}function tn(e){return je(e)}function nn(e){return{hi:e>>31&-1,lo:e|0}}function rn(e){return nn(e)}function an(e){return e.lo}function A(e){return an(e)&255}function on(e,t){return{hi:e.hi&t.hi,lo:e.lo&t.lo}}function sn(e,t){return{hi:e.hi|t.hi,lo:e.lo|t.lo}}function cn(e,t){return{hi:e.hi^t.hi,lo:e.lo^t.lo}}function ln(e,t){let n=t&63;if(n===0)return e;if(n<32){let t=e.hi,r=e.lo,i=t,a=r;return{hi:i<<n|a>>>(32-n|0)|0,lo:a<<n}}else return{hi:e.lo<<(n-32|0),lo:0}}function un(e,t){let n=t&63;return n===0?e:n<32?{hi:e.hi>>>n|0,lo:e.lo>>>n|e.hi<<(32-n|0)}:{hi:0,lo:e.hi>>>(n-32|0)|0}}function dn(e,t){return sn(e,t)}function fn(e,t){return ln(e,t)}function pn(e){return Ne(e)}function mn(e){return pn(e)}function hn(e){return je(e)}function gn(e){return Me(e)}function _n(e,t){let n=e,r=t;return n.hi===r.hi&&n.lo===r.lo}function j(e,t){return on(e,t)}function M(e,t){return sn(e,t)}function N(e,t){return cn(e,t)}function P(e,t){return ln(e,t)}function F(e,t){return un(e,t)}function vn(e){return Pe(e)}function yn(e,t){if(e<=0)return Fe;let n=Te(e,t(0)),r=1;for(;;){let i=r;if(i<e){p(n,i),n[i]=t(i),r=i+1|0;continue}else break}return n}function bn(e){console.log(e)}function xn(e,t,n,r,i){let a=(t+i|0)-1|0,o=(r+i|0)-1|0,s=e.length,c=n.length;if(i>=0&&t>=0&&a<s&&r>=0&&o<c){jt(e,t,n,r,i);return}else{d();return}}function Sn(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.buf,r=e.start+t|0;return p(n,r),n[r]}else return pt(`index out of bounds: the len is from 0 to ${E(e.end-e.start|0)} but the index is ${E(t)}`)}function Cn(e){let t=e.length,n=Array(t),r=0;for(;;){let i=r;if(i<t){n[i]=e[(t-i|0)-1|0],r=i+1|0;continue}else break}return n}function wn(e,t){let n=e.data.length<=0?1:e.data.length,r,i=n;for(;;){let e=i;if(e>=t){r=e;break}i=Math.imul(e,2)|0}if(r!==e.data.length){let t=Te(r,0);jt(t,0,e.data,0,e.len),e.data=t;return}else return}function I(e,t){wn(e,e.len+1|0);let n=e.data,r=e.len;p(n,r),n[r]=t,e.len=e.len+1|0}function L(e){return C(Zt(e.data,0,e.len))}function R(e){return{data:Te(e<1?1:e,0),len:0}}function Tn(e,t){let n=t.length;wn(e,e.len+n|0),xn(e.data,e.len,t,0,n),e.len=e.len+n|0}function En(e){switch(e){case 0:return`40`;case 1:return`41`;case 2:return`42`;case 3:return`43`;case 4:return`44`;case 5:return`45`;case 6:return`46`;case 7:return`47`;default:return`49`}}function Dn(e){switch(e){case 0:return`30`;case 1:return`31`;case 2:return`32`;case 3:return`33`;case 4:return`34`;case 5:return`35`;case 6:return`36`;case 7:return`37`;default:return`39`}}function On(e){let t=[],n=e.color;n===void 0||k(t,Dn(n));let r=e.bg_color;r===void 0||k(t,En(r));let i=e.formats,a=i.length,o=0;for(;;){let e=o;if(e<a){switch(i[e]){case 0:k(t,`1`);break;case 1:k(t,`4`);break;case 2:k(t,`5`);break;case 3:k(t,`7`);break;case 4:k(t,`8`);break;case 5:k(t,`9`);break;default:k(t,`3`)}o=e+1|0;continue}else break}return t.length>0?`[${vt(t,{str:`;`,start:0,end:1})}m${e.str}[0m`:e.str}function kn(e){return{str:e,bg_color:void 0,color:void 0,formats:[]}}function An(e){return{str:e.str,bg_color:e.bg_color,color:1,formats:e.formats}}function jn(e){return{str:e.str,bg_color:e.bg_color,color:3,formats:e.formats}}function Mn(e){return{str:e.str,bg_color:e.bg_color,color:4,formats:e.formats}}function Nn(e){let t=e.str,n=e.bg_color,r=e.color,i=[];return Wt(i,0),_t(i,Xt(e.formats)),{str:t,bg_color:n,color:r,formats:i}}function Pn(e,t){let n=`${On(An(Nn(kn(`Panic: `))))}${On(jn(kn(e)))} at ${On(Mn(kn(t)))}`;bn(n),y(n)}function Fn(e){let t=Vt(0),n=0;for(;n<e.length;){let r=n;p(e,r);let i=e.charCodeAt(r);if(i>=55296&&i<=56319&&(n+1|0)<e.length){let r=n+1|0;p(e,r);let a=e.charCodeAt(r);if(a>=56320&&a<=57343){let e=(65536+(i-55296<<10)|0)+(a-56320|0)|0;O(t,(240|e>>18)&255),O(t,(128|e>>12&63)&255),O(t,(128|e>>6&63)&255),O(t,(128|e&63)&255),n=n+1|0}else O(t,(224|i>>12)&255),O(t,(128|i>>6&63)&255),O(t,(128|i&63)&255)}else i<128?O(t,i&255):i<2048?(O(t,(192|i>>6)&255),O(t,(128|i&63)&255)):(O(t,(224|i>>12)&255),O(t,(128|i>>6&63)&255),O(t,(128|i&63)&255));n=n+1|0}return C({buf:t,start:0,end:t.length})}function In(e){return{bytes:Fn(e)}}function Ln(e){let t=0;for(;t<(e.end-e.start|0);){let n=b(e,t);if(!(n&128))t=t+1|0;else if((n&224)==192){if((t+1|0)>=(e.end-e.start|0)||(b(e,t+1|0)&192)!=128)return!1;t=t+2|0}else if((n&240)==224){if((t+2|0)>=(e.end-e.start|0))return!1;let n=b(e,t+1|0),r=b(e,t+2|0),i;if(i=(n&192)==128?(r&192)!=128:!0,i)return!1;t=t+3|0}else if((n&248)==240){if((t+3|0)>=(e.end-e.start|0))return!1;let n=b(e,t+1|0),r=b(e,t+2|0),i=b(e,t+3|0),a;if((n&192)!=128)a=!0;else{let e;e=(r&192)==128?(i&192)!=128:!0,a=e}if(a)return!1;t=t+4|0}else return!1}return!0}function Rn(e){if(Ln(S(e,0,void 0)))return{bytes:At(Ot(e))}}function zn(e){let t=0,n=``;for(;t<e.length;){let r=t;p(e,r);let i=e[r],a;if(!(i&128))a=i;else if((i&224)==192){if((t+1|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n];if((r&192)!=128)return;t=t+1|0,a=(i&31)<<6|r&63}else if((i&240)==224){if((t+2|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c;if(c=(r&192)==128?(s&192)!=128:!0,c)return;t=t+2|0,a=(i&15)<<12|(r&63)<<6|s&63}else if((i&248)==240){if((t+3|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c=t+3|0;p(e,c);let l=e[c],u;if((r&192)!=128)u=!0;else{let e;e=(s&192)==128?(l&192)!=128:!0,u=e}if(u)return;t=t+3|0,a=(i&7)<<18|(r&63)<<12|(s&63)<<6|l&63}else return;n=`${n}${Gt(a)}`,t=t+1|0}return n}function Bn(e){let t=zn(e.bytes);return t===void 0?d():t}function Vn(e){return gn(e)}function Hn(e){return hn(e)}function Un(e){let t=Vt(0);return O(t,A(j(F(e,56),h))),O(t,A(j(F(e,48),h))),O(t,A(j(F(e,40),h))),O(t,A(j(F(e,32),h))),O(t,A(j(F(e,24),h))),O(t,A(j(F(e,16),h))),O(t,A(j(F(e,8),h))),O(t,A(j(e,h))),C({buf:t,start:0,end:t.length})}function Wn(e){e.length!==8&&Pn(`Invalid byte array length`,`/Users/zxch3n/Code/flock/moon/memcomparable/utils.mbt:28:5-28:54`);let t=Ie,n=t;p(e,0),t=M(n,P(w(e[0]),56));let r=t;p(e,1),t=M(r,P(w(e[1]),48));let i=t;p(e,2),t=M(i,P(w(e[2]),40));let a=t;p(e,3),t=M(a,P(w(e[3]),32));let o=t;p(e,4),t=M(o,P(w(e[4]),24));let s=t;p(e,5),t=M(s,P(w(e[5]),16));let c=t;p(e,6),t=M(c,P(w(e[6]),8));let l=t;return p(e,7),t=M(l,w(e[7])),t}function Gn(){return{parts:Bt(0)}}function z(e,t){Ht(e.parts,t)}function Kn(e){return e===e?e:e<0?-ut:ut}function qn(e,t){I(t,1);let n=kt(e);for(;;){let e=Jt(n);if(e===-1)break;{let n=e;I(t,n),n===0&&I(t,255);continue}}I(t,0)}function Jn(e,t){I(t,2);let n=e.bytes,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];I(t,r),r===0&&I(t,255),i=e+1|0;continue}else break}I(t,0)}function Yn(e,t){I(t,33);let n=Kn(e),r=Un(n<0?N(Vn(n),Le):N(Vn(n),Re)),i=r.length,a=0;for(;;){let e=a;if(e<i){let n=r[e];I(t,n),a=e+1|0;continue}else return}}function Xn(e){let t=[],n=e;for(;Ft(n,0n);)O(t,Ce(Tt(n,256n))&255),n=wt(n,256n);let r=Cn(t);return C({buf:r,start:0,end:r.length})}function Zn(e,t){if(bt(e,0n)){I(t,20);return}let n=Ft(e,0n),r=Xn(n?e:xt(e)),i=r.length;if(n===!1){i<=8?I(t,(20-(i&255)|0)&255):(I(t,11),i>255&&y(`n is too large`),I(t,(i&255^255)&255));let e=R(0),n=0;for(;;){let t=n;if(t<r.length){p(r,t);let i=r[t];I(e,(i^255)&255),n=t+1|0;continue}else break}Tn(t,L(e));return}else{i<=8?I(t,(20+(i&255)|0)&255):(I(t,29),i>255&&y(`n is too large`),I(t,i&255)),Tn(t,r);return}}function Qn(e,t){switch(e.$tag){case 0:{let n=e._0;qn(x(n,0,n.length),t);return}case 1:{let n=e._0;Jn(n,t);return}case 2:{let n=e._0;Zn(n,t);return}case 3:{let n=e._0;Yn(n,t);return}case 4:I(t,38);return;default:I(t,39);return}}function $n(e){let t=R(0),n=e.parts,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];Qn(r,t),i=e+1|0;continue}else break}return L(t)}function er(e,t){let n=R(0),r=t;for(;r<(e.end-e.start|0);){let t=b(e,r);if(r=r+1|0,t===0){let t;if(t=r<(e.end-e.start|0)?b(e,r)===255:!1,t){I(n,0),r=r+1|0;continue}else{let e=L(n);return new Be({_0:x(e,0,e.length),_1:r})}}I(n,t)}return new ze(g)}function B(e){let t=f(Ie),n=f(Ue),r=(e.end-e.start|0)-1|0;for(;;){let i=r;if(i>=0){let a=f(rn(b(e,i)));t=St(t,Ct(n,a)),n=Ct(n,f(We)),r=i-1|0;continue}else break}return t}function tr(e,t){let n;if(n=20<=t?t<=28:!1,n){let n=(t-20|0)&255;if((e.end-e.start|0)<n)return new _(g);let r=S(e,0,n);return new v({_0:S(e,n,void 0),_1:B(r)})}else{let n;if(n=12<=t?t<20:!1,n){let n=(20-t|0)&255;if((e.end-e.start|0)<n)return new _(g);let r=S(e,0,n),i=S(e,n,void 0),a=R(0),o=0;for(;;){let e=o;if(e<(r.end-r.start|0)){I(a,(b(r,e)^255)&255),o=e+1|0;continue}else break}let s=L(a);return new v({_0:i,_1:xt(B(x(s,0,s.length)))})}else if(t===11){if((e.end-e.start|0)<1)return new _(g);let t=(b(e,0)^255)&255;if((e.end-e.start|0)<(t+1|0))return new _(g);let n=S(e,1,t+1|0),r=S(e,t+1|0,void 0),i=R(0),a=0;for(;;){let e=a;if(e<(n.end-n.start|0)){I(i,(b(n,e)^255)&255),a=e+1|0;continue}else break}let o=L(i);return new v({_0:r,_1:xt(B(x(o,0,o.length)))})}else if(t===29){if((e.end-e.start|0)<1)return new _(g);let t=b(e,0);if((e.end-e.start|0)<(t+1|0))return new _(g);let n=S(e,1,t+1|0);return new v({_0:S(e,t+1|0,void 0),_1:B(n)})}else return new _(new Ve(t))}}function nr(e,t){if((t+8|0)>(e.end-e.start|0))return new Ge(g);let n=Vt(0),r=0;for(;;){let i=r;if(i<8){O(n,b(e,t+i|0)),r=i+1|0;continue}else break}let i=Wn(C({buf:n,start:0,end:n.length}));return new Ke({_0:_n(j(i,Re),Ie)?Hn(N(i,Le)):Hn(N(i,Re)),_1:t+8|0})}function rr(e){let t=Gn(),n=0;for(;n<(e.end-e.start|0);){let r=b(e,n);if(n=n+1|0,r===2){let r=er(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1,s=Rn(a);if(s===void 0)return new $e(He);z(t,new Je(s)),n=o}else if(r===1){let r=er(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;z(t,new qe(At(Ot(a)))),n=o}else if(r>=11&&r<=29){let i=tr(S(e,n,void 0),r),a;if(i.$tag===1)a=i._0;else return i;let o=a._0,s=a._1;z(t,new Ye(s)),n=(e.end-e.start|0)-(o.end-o.start|0)|0}else if(r===33){let r=nr(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;z(t,new Xe(a)),n=o}else if(r===38)z(t,Ze);else if(r===39)z(t,Qe);else return new $e(new Ve(r))}return new et(t)}function ir(e){switch(e.$tag){case 0:{let t=e._0;return new rt(t)}case 1:{let t=e._0;return new nt(Bn(t))}case 2:{let t=e._0;return new tt(mn(Dt(t)))}case 3:{let t=e._0;return new tt(t)}case 4:return at;default:return it}}function ar(e){switch(e.$tag){case 2:{let t=e._0;return new qe(t)}case 1:{let t=e._0;return new Je(In(t))}case 0:{let t=e._0;return mn(vn(t))===t?new Ye(f(vn(t))):new Xe(t)}case 3:return Qe;default:return Ze}}function or(e){let t=Gn(),n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];Ht(t.parts,ar(n)),r=i+1|0;continue}else break}return $n(t)}function sr(e){let t;_L:{_L$2:{let n=rr(x(e,0,e.length));if(n.$tag===1)t=n._0;else{n._0;break _L$2}break _L}t=dt(`Failed to decode key`)}let n=zt(0),r=t.parts,i=r.length,a=0;for(;;){let e=a;if(e<i){let t=r[e];Ut(n,ir(t)),a=e+1|0;continue}else break}return n}function cr(e){if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Key parts must be finite numbers`);return{$tag:0,_0:e}}if(typeof e==`string`)return{$tag:1,_0:e};if(e===!0)return{$tag:3};if(e===!1)return{$tag:4};throw TypeError(`Key parts must be strings, numbers, or booleans`)}function lr(e){if(e instanceof Uint8Array)return e;if(e&&typeof e==`object`){let t=e.buf;if(t instanceof Uint8Array){let n=e.start??0,r=e.end??t.length;return t.subarray(n,r)}}throw TypeError(`Invalid bytes payload in memcomparable decode`)}function ur(e){switch(e?.$tag){case 0:return e._0;case 1:return e._0;case 3:return!0;case 4:return!1;case 2:return lr(e._0);default:throw TypeError(`Unsupported memcomparable key part`)}}function V(e){return or(e.map(cr))}function dr(e){return sr(e).map(e=>ur(e))}function fr(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return e.length===t.length?0:e.length<t.length?-1:1}function pr(e){if(e.length===0)return;let t=Array.from(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n<255)return t[e]=n+1,new Uint8Array(t.slice(0,e+1))}}function mr(e){return JSON.stringify(e)}function hr(){return{now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),randomUUID:()=>{try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return`${Date.now()}_${Math.random().toString(16).slice(2)}`}}}function gr(e){if(!(typeof BroadcastChannel>`u`))try{let t=new BroadcastChannel(e);return{postMessage:e=>{try{t.postMessage(e)}catch{}},subscribe:e=>{let n=t=>{e(t.data)};return t.addEventListener(`message`,n),()=>{t.removeEventListener(`message`,n)}},close:()=>{try{t.close()}catch{}}}}catch{return}}function _r(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.t===`req`||t.t===`res`||t.t===`commit`}function vr(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{name:`Error`,message:String(e)}}const yr=3e3,br=1024;function xr(e){return e instanceof Error?!!(e.name===`HostLost`||e.message.includes(`Timed out waiting for host response`)):!1}function Sr(e){return e<=0?25:Math.min(500,25*2**(e-1))}function H(e,t){return e.origin===t&&e.source===`local`}function Cr(e,t){return`${e}|${t}`}function wr(e){let t=Error(e.message);return t.name=e.name,e.stack&&(t.stack=e.stack),t}var Tr=class{runtime;tabId;roleValue;roleListeners;roleUnsubscribe;closed;constructor(e,t,n){this.runtime=e,this.tabId=t,this.roleValue=n.getRole(),this.roleListeners=new Set,this.roleUnsubscribe=n.subscribeRoleChange?.(e=>{this.setRole(e)}),this.closed=!1}getRole(){return this.roleValue}isHost(){return this.roleValue===`host`}subscribeRoleChange(e){this.roleListeners.add(e);try{e(this.roleValue)}catch{}return()=>{this.roleListeners.delete(e)}}setRole(e){if(e!==this.roleValue){this.roleValue=e;for(let t of this.roleListeners)try{t(e)}catch{}}}closeRole(){this.roleUnsubscribe?.(),this.roleUnsubscribe=void 0,this.setRole(`unknown`)}},Er=class extends Tr{writeQueue;ingestCommit;executeWriteRequest;constructor(e){super(e.runtime,e.tabId,e.roleProvider),this.ingestCommit=e.ingestCommit,this.executeWriteRequest=e.executeWriteRequest,this.writeQueue=Promise.resolve()}enqueueWrite(e){let t=this.writeQueue.then(e,e);return this.writeQueue=t.then(()=>void 0,()=>void 0),t}async dispatchWriteRequest(e){if(this.closed)throw Error(`FlockSQLite is closed`);let t=this.runtime.randomUUID(),{commit:n,result:r}=await this.enqueueWrite(()=>this.executeWriteRequest(e,this.tabId,t));return this.ingestCommit(n,H(n,this.tabId)),{commit:n,result:r}}close(){this.closed=!0,this.closeRole()}},Dr=class extends Tr{transport;transportUnsubscribe;pendingRequests;hostResponseCache;hostInFlight;writeQueue;ingestCommit;executeWriteRequest;constructor(e){super(e.runtime,e.tabId,e.roleProvider),this.transport=e.transport,this.transportUnsubscribe=this.transport.subscribe(e=>{try{this.handleTransportMessage(e)}catch{}}),this.pendingRequests=new Map,this.hostResponseCache=new ue(1024),this.hostInFlight=new Map,this.writeQueue=Promise.resolve(),this.ingestCommit=e.ingestCommit,this.executeWriteRequest=e.executeWriteRequest}enqueueWrite(e){let t=this.writeQueue.then(e,e);return this.writeQueue=t.then(()=>void 0,()=>void 0),t}shouldForwardWrites(){return this.roleValue!==`host`}handleTransportMessage(e){if(_r(e)){if(e.t===`res`){if(e.to!==this.tabId)return;let t=this.pendingRequests.get(e.id);if(!t)return;this.runtime.clearTimeout(t.timeoutId),this.pendingRequests.delete(e.id),t.resolve(e);return}if(e.t===`commit`){let t=e.commit;this.ingestCommit(t,H(t,this.tabId));return}if(e.t===`req`){if(e.from===this.tabId||this.roleValue!==`host`||this.closed)return;this.processHostRequest(e)}}}broadcastCommit(e){this.closed||this.roleValue===`host`&&this.transport.postMessage({t:`commit`,commit:e})}async forwardWriteRequest(e,t,n=3e3){if(this.closed)throw Error(`FlockSQLite is closed`);let r={t:`req`,from:this.tabId,id:t,payload:e},i=await new Promise((e,i)=>{let a=this.runtime.setTimeout(()=>{this.pendingRequests.delete(t),i(Error(`Timed out waiting for host response`))},n);this.pendingRequests.set(t,{resolve:e,reject:i,timeoutId:a}),this.transport.postMessage(r)});if(!i.ok)throw i.error?wr(i.error):Error(`Host rejected request`);let a=i.commit;return a&&this.ingestCommit(a,H(a,this.tabId)),{commit:a,result:i.result}}async dispatchWriteRequest(e){if(this.closed)throw Error(`FlockSQLite is closed`);let t=this.runtime.randomUUID(),n;for(let r=1;r<=5;r+=1){if(!this.shouldForwardWrites()){let{commit:n,result:r}=await this.enqueueWrite(()=>this.executeWriteRequest(e,this.tabId,t));return this.ingestCommit(n,H(n,this.tabId)),this.broadcastCommit(n),{commit:n,result:r}}try{let n=await this.forwardWriteRequest(e,t);if(!n.commit)throw Error(`Host did not return commit`);return{commit:n.commit,result:n.result}}catch(e){if(n=e,r>=5||!xr(e))throw e;await new Promise(e=>{this.runtime.setTimeout(()=>e(),Sr(r))})}}throw n??Error(`Failed to dispatch write request`)}async processHostRequest(e){let t=Cr(e.from,e.id),n=this.hostResponseCache.get(t);if(n){n.ok&&n.commit&&this.broadcastCommit(n.commit),this.transport.postMessage(n);return}let r=this.hostInFlight.get(t);r||(r=this.enqueueWrite(async()=>{if(this.roleValue!==`host`||this.closed)return{t:`res`,to:e.from,id:e.id,ok:!1,error:{name:`HostLost`,message:`Host role was lost`}};try{let{commit:t,result:n}=await this.executeWriteRequest(e.payload,e.from,e.id);return this.ingestCommit(t,H(t,this.tabId)),this.broadcastCommit(t),{t:`res`,to:e.from,id:e.id,ok:!0,commit:t,result:n}}catch(t){return{t:`res`,to:e.from,id:e.id,ok:!1,error:vr(t)}}}),this.hostInFlight.set(t,r),r.finally(()=>{this.hostInFlight.delete(t)}));let i=await r;this.hostResponseCache.set(t,i),this.transport.postMessage(i)}close(){if(!this.closed){this.closed=!0,this.transportUnsubscribe?.(),this.transportUnsubscribe=void 0,this.transport.close?.();for(let{reject:e,timeoutId:t}of this.pendingRequests.values()){this.runtime.clearTimeout(t);try{e(Error(`FlockSQLite closed`))}catch{}}this.pendingRequests.clear(),this.closeRole()}}};function Or(e){return e.transport?new Dr({...e,transport:e.transport}):new Er(e)}const kr=new TextEncoder,Ar=new TextDecoder,jr=globalThis.structuredClone;function Mr(e){return kr.encode(e).length}function U(e){return typeof e==`string`&&Mr(e)<128}function Nr(){let e=new Uint8Array(32),t=typeof crypto<`u`?crypto:void 0;if(t?.getRandomValues)t.getRandomValues(e);else if(t?.randomBytes){let n=t.randomBytes(32);e.set(n)}else for(let t=0;t<32;t+=1)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function W(e){if(e===void 0)return Nr();if(!U(e))throw TypeError(`peerId must be a UTF-8 string under 128 bytes`);return e}function G(e){return e===void 0?e:jr?jr(e):JSON.parse(JSON.stringify(e))}function K(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return G(e)}function Pr(e){return K(e)??{}}function Fr(e,t){if(!(!t||typeof t!=`object`)){if(`data`in t){let n=t.data;e.data=n===void 0?void 0:G(n)}`metadata`in t&&(e.metadata=K(t.metadata))}}function q(e){let t={};return Fr(t,e),t}function J(e,t){let n=q(e);return Fr(n,t),n}function Ir(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r]-t[r];if(n!==0)return n}return e.length-t.length}function Lr(e){if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r||!U(n))continue;let{physicalTime:e,logicalCounter:i}=r;if(typeof e!=`number`||!Number.isFinite(e)||typeof i!=`number`||!Number.isFinite(i))continue;let a=kr.encode(n);t.push({peer:n,peerBytes:a,timestamp:Math.trunc(e),counter:Math.max(0,Math.trunc(i))})}return t.sort((e,t)=>{if(e.timestamp!==t.timestamp)return e.timestamp-t.timestamp;let n=Ir(e.peerBytes,t.peerBytes);return n===0?e.counter-t.counter:n}),t}function Y(e,t){if(!Number.isFinite(e)||e<0)throw TypeError(`leb128 values must be finite and non-negative`);let n=Math.trunc(e);if(n===0){t.push(0);return}for(;n>0;){let e=n%128;n=Math.floor(n/128),t.push(n>0?e|128:e)}}function Rr(e,t){Y(e.length,t);for(let n=0;n<e.length;n+=1)t.push(e[n])}const X=new Uint8Array([86,69,86,69]);function zr(e){let t=Lr(e),n=Array.from(X);if(t.length===0)return Uint8Array.from(n);let r=0;for(let e=0;e<t.length;e+=1){let i=t[e];if(i.timestamp<0)throw TypeError(`timestamp must be non-negative`);if(e===0)Y(i.timestamp,n),r=i.timestamp;else{let e=i.timestamp-r;if(e<0)throw TypeError(`version vector timestamps must be non-decreasing`);Y(e,n),r=i.timestamp}Y(i.counter,n),Rr(i.peerBytes,n)}return Uint8Array.from(n)}function Z(e,t){let n=0,r=1,i=0;for(;t+i<e.length;){let a=e[t+i];if(i+=1,n+=(a&127)*r,!(a&128))break;r*=128}return[n,i]}function Br(e,t){let[n,r]=Z(e,t),i=t+r,a=i+n;if(a>e.length)throw TypeError(`varString length exceeds buffer`);let o=e.subarray(i,a);return[Ar.decode(o),r+n]}function Vr(e){return e.length>=4&&e[0]===X[0]&&e[1]===X[1]&&e[2]===X[2]&&e[3]===X[3]}function Hr(e){let t=0,[n,r]=Z(e,t);t+=r;let[i,a]=Z(e,t);t+=a;let o={};for(let r=0;r<n;r+=1){let[n,r]=Br(e,t);if(t+=r,!U(n))throw TypeError(`invalid peer id in encoded version vector`);let[a,s]=Z(e,t);t+=s;let[c,l]=Z(e,t);t+=l,o[n]={physicalTime:i+a,logicalCounter:c}}return o}function Ur(e){let t=4,n={};if(t===e.length)return n;let[r,i]=Z(e,t);t+=i;let[a,o]=Z(e,t);t+=o;let[s,c]=Br(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);n[s]={physicalTime:r,logicalCounter:a};let l=r;for(;t<e.length;){let[r,i]=Z(e,t);t+=i;let[a,o]=Z(e,t);t+=o;let[s,c]=Br(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);let u=l+r;if(u<l)throw TypeError(`version vector timestamps must be non-decreasing`);n[s]={physicalTime:u,logicalCounter:a},l=u}return n}function Wr(e){return Vr(e)?Ur(e):Hr(e)}function Gr(e){return zr(e)}function Kr(e){return Wr(e)}function Q(e,t){let n={c:$r(e)};t.data!==void 0&&(n.d=G(t.data));let r=K(t.metadata);return r!==void 0&&(n.m=r),n}function qr(e){return!e||typeof e!=`object`?{accept:!0}:`accept`in e?e.accept?{accept:!0}:{accept:!1,reason:e.reason??`rejected`}:{accept:!0}}function Jr(e){return typeof e==`object`&&!!e&&(Object.prototype.hasOwnProperty.call(e,`hooks`)||Object.prototype.hasOwnProperty.call(e,`from`)||Object.prototype.hasOwnProperty.call(e,`pruneTombstonesBefore`)||Object.prototype.hasOwnProperty.call(e,`peerId`))}function Yr(e){return typeof e==`object`&&!!e&&Object.prototype.hasOwnProperty.call(e,`bundle`)}function Xr(e){if(e)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function $(e){if(e!=null)return JSON.parse(e)}function Zr(e){let t=e.split(`,`);if(t.length<3)return{physicalTime:0,logicalCounter:0,peerId:``};let n=Number(t[0]),r=Number(t[1]),i=t.slice(2).join(`,`);return{physicalTime:Number.isFinite(n)?n:0,logicalCounter:Number.isFinite(r)?Math.trunc(r):0,peerId:U(i)?i:``}}function Qr(e,t,n){if(!(typeof e!=`number`||typeof t!=`number`||typeof n!=`string`)&&U(n)&&!(!Number.isFinite(e)||!Number.isFinite(t)))return{physicalTime:e,logicalCounter:Math.trunc(t),peerId:n}}function $r(e){return`${e.physicalTime},${e.logicalCounter},${e.peerId}`}function ei(e,t){return e.physicalTime===t.physicalTime?e.logicalCounter===t.logicalCounter?e.peerId===t.peerId?0:e.peerId>t.peerId?1:-1:e.logicalCounter>t.logicalCounter?1:-1:e.physicalTime>t.physicalTime?1:-1}function ti(e){if(!e)return;let{physicalTime:t,logicalCounter:n}=e;if(!(!Number.isFinite(t)||!Number.isFinite(n)))return{physicalTime:t,logicalCounter:Math.trunc(n)}}function ni(e,t){if(t.length===0)return!0;if(e.length<t.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}async function ri(e){return e.map(e=>({key:e.key,data:e.data,metadata:e.metadata,physical:e.physical,logical:e.logical,peer:e.peer}))}function ii(e){if(!e)return``;if(typeof e!=`string`)throw TypeError(`tablePrefix must be a string`);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw TypeError(`tablePrefix must start with a letter/underscore and use only letters, digits, or underscores`);return e}function ai(e){return{kv:`${e}kv`,overridden:`${e}overridden`,meta:`${e}meta`,idxKvPeerClock:`${e}idx_kv_peer_clock_key`,idxOverriddenKey:`${e}idx_overridden_key`,idxOverriddenSupersededAt:`${e}idx_overridden_superseded_at`}}function oi(e){if(e===`host`||e===`participant`||e===`unknown`)return e}function si(e){let t=e.getRole?.(),n=oi(t);if(n)return n;let r=e.getSQLiteInfo?.();if(r&&typeof r==`object`){let{isHost:e,isReady:t}=r;if(e===!0&&t===!0)return`host`;if(t===!1)return`unknown`;if(t===!0)return`participant`}return`host`}function ci(e){let t=e.subscribeRoleChange;return{getRole:()=>si(e),subscribeRoleChange:typeof t==`function`?n=>t.call(e,e=>{let t=oi(e);t&&n(t)}):void 0}}const li=2048;function ui(e,t){return t?`flock:rpc:${e}:${t}`:`flock:rpc:${e}`}function di(e,t,n){if(typeof n==`string`&&n.length>0)return n;let r=e.getSQLiteInfo?.();if(r&&typeof r==`object`){let e=r.tabId;if(typeof e==`string`&&e.length>0)return e}return t.randomUUID()}var fi=class t{db;peerIdValue;vv;maxHlc;listeners;tables;runtime;eventBatcher;coordinator;seenCommitIds;closed;constructor(e,t,n,r,i,a,o,s,c){this.db=e,this.peerIdValue=t,this.vv=n,this.maxHlc=r,this.listeners=new Set,this.tables=i,this.runtime=o,this.eventBatcher=new le({runtime:o,emit:(e,t)=>this.emitEvents(e,t)}),this.seenCommitIds=new de(2048),this.coordinator=Or({runtime:o,tabId:a,transport:s,roleProvider:c,ingestCommit:(e,t)=>this.applyCommit(e,t),executeWriteRequest:(e,t,n)=>this.executeWriteRequest(e,t,n)}),this.closed=!1}static async open(n){let r=n.connection??await(0,e.openStore)({path:n.path}),i=ii(n.tablePrefix),a=ai(i);await t.ensureSchema(r,a);let o=await t.resolvePeerId(r,a,n.peerId),{vv:s,maxHlc:c}=await t.loadVersionState(r,a),l=n.multiTab?.runtime??hr(),u=n.multiTab?.roleProvider??ci(r),ee=ui(n.path,i),te=(n.multiTab?.transportFactory??gr)(ee);return new t(r,o,s,c,a,di(r,l,n.multiTab?.tabId),l,te,u)}static async fromJson(e){let n=await t.open(e);return await n.importJson(e.bundle),n}async close(){this.closed||(this.closed=!0,this.coordinator.close(),this.eventBatcher.close(),await this.db.close())}getRole(){return this.coordinator.getRole()}isHost(){return this.coordinator.isHost()}subscribeRoleChange(e){return this.coordinator.subscribeRoleChange(e)}dispatchWriteRequest(e){return this.coordinator.dispatchWriteRequest(e)}applyCommit(e,t){if(this.seenCommitIds.has(e.commitId))return;if(this.seenCommitIds.add(e.commitId),e.meta?.peerId)try{this.peerIdValue=W(e.meta.peerId)}catch{}let n=e.events.map(t=>({key:G(t.key),payload:q(t.payload),source:e.source,clock:{...t.clock}}));for(let e of n)this.bumpVersion(e.clock);n.length!==0&&this.eventBatcher.handleCommitEvents(e.source,n,t)}async executeWriteRequest(e,t,n){let r=[],i,a;if(e.kind===`apply`)await this.applyOperation({key:e.key,payload:e.payload,now:e.now,skipSameValue:e.skipSameValue,source:e.source,eventSink:r});else if(e.kind===`putMvr`)await this.putMvrInternal(e.key,e.value,e.now,r);else if(e.kind===`import`)i=await this.importBundleInternal(e.bundle,r);else if(e.kind===`setPeerId`)await this.setPeerIdInternal(e.peerId),a={peerId:this.peerIdValue};else{let t=e;throw Error(`Unsupported write payload ${String(t)}`)}return{commit:{commitId:`c:${t}:${n}`,origin:t,source:e.source,events:r.map(e=>({key:e.key.slice(),clock:{...e.clock},payload:q(e.payload)})),...a?{meta:a}:{}},result:i}}static async ensureSchema(e,t){await e.exec(`
1
+ let e=require(`@loro-dev/unisqlite`);const t=16,n=17,r=18,i=32,a=33,o=34,s=35,c=36,l=37,u=new TextEncoder;function ee(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function te(e){let t=BigInt(e),n=[];do{let e=Number(t&127n);t>>=7n,t!==0n&&(e|=128),n.push(e)}while(t!==0n);return new Uint8Array(n)}function ne(e){let t=BigInt(e),n=[],r=!0;for(;r;){let e=Number(t&127n);t>>=7n;let i=(e&64)!=0;t===0n&&!i||t===-1n&&i?r=!1:e|=128,n.push(e)}return new Uint8Array(n)}async function re(e){let t=typeof crypto<`u`?crypto:void 0;if(t?.subtle){let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=await t.subtle.digest(`SHA-256`,n);return new Uint8Array(r)}try{let{createHash:t}=await import(`crypto`),n=t(`sha256`);return n.update(e),new Uint8Array(n.digest())}catch{throw Error(`No crypto implementation available for digest`)}}var ie=class{chunks=[];writeTag(e){this.chunks.push(e&255)}writeBool(e){this.chunks.push(e?1:0)}writeBytes(e){this.writeLen(e.length);for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeRawBytes(e){for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeLen(e){this.writeRawBytes(te(e))}writeI64(e){this.writeRawBytes(ne(e))}writeF64(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e,!1);let n=new Uint8Array(t.buffer);this.writeRawBytes(n)}writeString(e){this.writeBytes(u.encode(e))}writeJson(e){if(e===null){this.writeTag(32);return}if(typeof e==`boolean`){this.writeTag(33),this.writeBool(e);return}if(typeof e==`number`){this.writeTag(34),this.writeF64(e);return}if(typeof e==`string`){this.writeTag(35),this.writeString(e);return}if(Array.isArray(e)){this.writeTag(36),this.writeLen(e.length);for(let t of e)this.writeJson(t);return}if(e&&typeof e==`object`){let t=Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeTag(37),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n);return}throw TypeError(`Unsupported JSON value in digest`)}writeRawValue(e){if(this.writeTag(16),e.data===void 0?this.writeBool(!1):(this.writeBool(!0),this.writeJson(e.data)),this.writeTag(18),!e.metadata||typeof e.metadata!=`object`)this.writeBool(!1);else{let t=Object.entries(e.metadata).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeBool(!0),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n)}this.writeTag(17),this.writeF64(e.clock.physicalTime),this.writeI64(Math.trunc(e.clock.logicalCounter)),this.writeBytes(u.encode(e.clock.peerId))}async finish(){return re(new Uint8Array(this.chunks))}};function ae(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch{return}}function oe(e){if(e!=null)return JSON.parse(e)}async function se(e){let t=oe(e.data);if(t===void 0)return null;let n=ae(e.metadata),r=new ie;return r.writeBytes(e.key),r.writeRawValue({data:t,metadata:n,clock:{physicalTime:Number(e.physical),logicalCounter:Number(e.logical),peerId:String(e.peer)}}),r.finish()}async function ce(e){let t=new Uint8Array(32);for(let n of e){let e=await se(n);if(e)for(let n=0;n<t.length;n+=1)t[n]^=e[n]}return ee(t)}var le=class{outbox=[];outboxCursor=0;draining=!1;txnEventSink;debounceState;runtime;emit;constructor(e){this.runtime=e.runtime,this.emit=e.emit,this.txnEventSink=void 0,this.debounceState=void 0}handleCommitEvents(e,t,n){if(t.length!==0){if(n&&this.txnEventSink){this.txnEventSink.push(...t);return}if(n&&this.debounceState){this.bufferLocalEvents(t);return}this.enqueueBatch({source:e,events:t})}}beforeImport(){this.debounceState!==void 0&&this.commit()}async txn(e){if(this.txnEventSink!==void 0)throw Error(`Nested transactions are not supported`);if(this.debounceState!==void 0)throw Error(`Cannot start transaction while autoDebounceCommit is active`);let t=[];this.txnEventSink=t;try{let n=await e();return t.length>0&&(this.txnEventSink=void 0,this.enqueueBatch({source:`local`,events:t})),n}finally{this.txnEventSink=void 0}}isInTxn(){return this.txnEventSink!==void 0}autoDebounceCommit(e,t){if(this.txnEventSink!==void 0)throw Error(`Cannot enable autoDebounceCommit while transaction is active`);if(this.debounceState!==void 0)throw Error(`autoDebounceCommit is already active`);this.debounceState={timeout:e,maxDebounceTime:t?.maxDebounceTime??1e4,timerId:void 0,deadlineAt:void 0,pendingEvents:[]}}disableAutoDebounceCommit(){if(this.debounceState===void 0)return;let e=this.takeDebouncedEvents();this.debounceState=void 0,e.length>0&&this.enqueueBatch({source:`local`,events:e})}commit(){this.debounceState!==void 0&&this.flushDebouncedEvents()}isAutoDebounceActive(){return this.debounceState!==void 0}close(){if(this.debounceState!==void 0&&this.disableAutoDebounceCommit(),this.txnEventSink!==void 0){let e=this.txnEventSink;if(this.txnEventSink=void 0,e.length>0){let t=e.slice();e.length=0,this.enqueueBatch({source:`local`,events:t})}}}enqueueBatch(e){this.outbox.push(e),this.drainOutbox()}drainOutbox(){if(!this.draining){this.draining=!0;try{for(;this.outboxCursor<this.outbox.length;){let e=this.outbox[this.outboxCursor];this.outboxCursor+=1,this.deliverBatch(e)}}finally{this.outbox=[],this.outboxCursor=0,this.draining=!1}}}deliverBatch(e){try{this.emit(e.source,e.events)}catch{}}bufferLocalEvents(e){if(this.debounceState===void 0||e.length===0)return;let t=this.debounceState,n=this.runtime.now();t.pendingEvents.length===0&&(t.deadlineAt=n+t.maxDebounceTime),t.pendingEvents.push(...e),this.scheduleDebounceFlush(n)}scheduleDebounceFlush(e){if(this.debounceState===void 0)return;let t=this.debounceState;if(t.pendingEvents.length===0)return;if(t.timeout<=0){this.flushDebouncedEvents();return}let n=t.deadlineAt??e+t.maxDebounceTime;t.deadlineAt=n;let r=Math.min(e+t.timeout,n);if(r<=e){this.flushDebouncedEvents();return}t.timerId!==void 0&&this.runtime.clearTimeout(t.timerId),t.timerId=this.runtime.setTimeout(()=>{this.flushDebouncedEvents()},Math.max(0,r-e))}takeDebouncedEvents(){if(this.debounceState===void 0)return[];let e=this.debounceState;if(e.timerId!==void 0&&(this.runtime.clearTimeout(e.timerId),e.timerId=void 0),e.deadlineAt=void 0,e.pendingEvents.length===0)return[];let t=e.pendingEvents;return e.pendingEvents=[],t}flushDebouncedEvents(){let e=this.takeDebouncedEvents();e.length!==0&&this.enqueueBatch({source:`local`,events:e})}},ue=class{map=new Map;constructor(e){if(this.maxSize=e,!Number.isFinite(e)||e<=0)throw Error(`LruMap maxSize must be a positive number, got ${e}`)}get size(){return this.map.size}has(e){return this.map.has(e)}get(e){if(!this.map.has(e))return;let t=this.map.get(e);return this.map.delete(e),this.map.set(e,t),t}set(e,t){this.map.has(e)&&this.map.delete(e),this.map.set(e,t),this.evictIfNeeded()}delete(e){return this.map.delete(e)}clear(){this.map.clear()}evictIfNeeded(){for(;this.map.size>this.maxSize;){let e=this.map.keys().next().value;if(e===void 0)return;this.map.delete(e)}}},de=class{map;constructor(e){this.map=new ue(e)}has(e){return this.map.get(e)!==void 0}add(e){this.map.set(e,!0)}clear(){this.map.clear()}};const fe={hi:2146959360,lo:1};var pe=class extends Error{};function d(){throw new pe}const me=(e,t)=>e<t?-1:e>t?1:0,he=(e,t)=>e===t,f=e=>BigInt(e.hi)*4294967296n+BigInt(e.lo>>>0),ge=e=>-e,_e=(e,t)=>e+t,ve=(e,t)=>e*t,ye=(e,t)=>e/t,be=(e,t)=>e%t,xe=(e,t)=>e>>BigInt(t),Se=e=>Number(BigInt.asUintN(32,e))|0,Ce=e=>Number(BigInt.asIntN(32,e));function p(e,t){if(t<0||t>=e.length)throw Error(`Index out of bounds`)}const we=(e,t)=>e.toString(t);function Te(e,t){let n=new Uint8Array(e);return t!==0&&n.fill(t),n}const m=(e,t)=>{e.push(t)},Ee={$tag:0};function De(e){this._0=e}De.prototype.$tag=1;function Oe(e){this._0=e}Oe.prototype.$tag=2;function ke(e){this._0=e}ke.prototype.$tag=3;function Ae(e){this._0=e}Ae.prototype.$tag=4;const je=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setUint32(0,t.hi),n.setUint32(4,t.lo),n.getFloat64(0)},Me=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setFloat64(0,t),{hi:n.getInt32(0),lo:n.getInt32(4)}},Ne=e=>e.hi*4294967296+(e.lo>>>0),Pe=e=>{if(isNaN(e))return{hi:0,lo:0};if(e>=0x8000000000000000)return{hi:2147483647,lo:4294967295};if(e<=-0x8000000000000000)return{hi:-2147483648,lo:0};let t=!1;e<0&&(t=!0,e=-e);let n=1/4294967296*e|0,r=e>>>0;return t&&(r===0?n=~n+1:(n=~n,r=~r+1)),{hi:n,lo:r}},Fe=new Uint8Array,h={hi:0,lo:255},Ie={hi:0,lo:0},Le={hi:-1,lo:-1},Re={hi:-2147483648,lo:0};function ze(e){this._0=e}ze.prototype.$tag=0;function Be(e){this._0=e}Be.prototype.$tag=1;function Ve(e){this._0=e}Ve.prototype.$tag=2;const g={$tag:1},He={$tag:0},Ue={hi:0,lo:1},We={hi:0,lo:256};function _(e){this._0=e}_.prototype.$tag=0;function v(e){this._0=e}v.prototype.$tag=1;function Ge(e){this._0=e}Ge.prototype.$tag=0;function Ke(e){this._0=e}Ke.prototype.$tag=1;function qe(e){this._0=e}qe.prototype.$tag=0;function Je(e){this._0=e}Je.prototype.$tag=1;function Ye(e){this._0=e}Ye.prototype.$tag=2;function Xe(e){this._0=e}Xe.prototype.$tag=3;const Ze={$tag:4},Qe={$tag:5};function $e(e){this._0=e}$e.prototype.$tag=0;function et(e){this._0=e}et.prototype.$tag=1;function tt(e){this._0=e}tt.prototype.$tag=0;function nt(e){this._0=e}nt.prototype.$tag=1;function rt(e){this._0=e}rt.prototype.$tag=2;const it={$tag:3},at={$tag:4},ot=`;`,st=1,ct=3,lt=4,ut=tn(fe);function dt(e){return d()}function ft(e){return d()}function pt(e){return d()}function y(e){d()}function mt(e){return d()}function ht(e){return en(e)}function gt(e,t){if(e.end-e.start|0){let n=e.buf[e.start],r=e.buf,i=1+e.start|0,a={buf:r,start:i,end:e.end},o=T(n),s=o.end-o.start|0,c=a.end-a.start|0,l=0;for(;;){let e=l;if(e<c){let n=r[i+e|0],a=s,o=T(n);s=a+((o.end-o.start|0)+(t.end-t.start|0)|0)|0,l=e+1|0;continue}else break}s<<=1;let u=Mt(s);if(D(u,o.str,o.start,o.end-o.start|0),Lt(t.str,0,t.start,t.end)){let e=a.end-a.start|0,t=0;for(;;){let n=t;if(n<e){let e=r[i+n|0],a=T(e);D(u,a.str,a.start,a.end-a.start|0),t=n+1|0;continue}else break}}else{let e=a.end-a.start|0,n=0;for(;;){let a=n;if(a<e){let e=r[i+a|0],o=T(e);D(u,t.str,t.start,t.end-t.start|0),D(u,o.str,o.start,o.end-o.start|0),n=a+1|0;continue}else break}}return u.val}else return``}function _t(e,t){t(t=>(Wt(e,t),1))}function vt(e,t){return gt({buf:e,start:0,end:e.length},t)}function yt(e,t){return me(e,t)}function bt(e,t){return he(e,t)}function xt(e){return ge(e)}function St(e,t){return _e(e,t)}function Ct(e,t){return ve(e,t)}function wt(e,t){return ye(e,t)}function Tt(e,t){return be(e,t)}function Et(e,t){return t<0&&y(`negative shift count`),xe(e,t)}function Dt(e){let t=Se(Et(e,32)),n=Se(e);return dn(fn(ht(t),32),ht(n))}function b(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.bytes,r=e.start+t|0;return p(n,r),n[r]}else return pt(`index out of bounds: the len is from 0 to ${E(e.end-e.start|0)} but the index is ${E(t)}`)}function x(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e,start:a,end:i}:ft(`Invalid index for View`)}function S(e,t,n){let r=e.end-e.start|0,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e.bytes,start:e.start+a|0,end:(e.start+a|0)+(i-a|0)|0}:ft(`Invalid index for View`)}function Ot(e){return t=>{let n=e.end-e.start|0,r=0;for(;;){let i=r;if(i<n){if(t(b(e,i))!==1)return 0;r=i+1|0;continue}else return 1}}}function kt(e){let t={val:0},n=e.end-e.start|0;return()=>{if(t.val<n){let n=t.val,r=e.bytes,i=e.start+n|0;p(r,i);let a=r[i];return t.val=t.val+1|0,a}else return-1}}function C(e){return yn(e.end-e.start|0,t=>Sn(e,t))}function At(e){let t=qt(e);return C({buf:t,start:0,end:t.length})}function w(e){return en(e)}function T(e){return{str:e,start:0,end:e.length}}function jt(e,t,n,r,i){if(e===n&&t<r){let a=0;for(;;){let o=a;if(o<i){let i=t+o|0,s=r+o|0;p(n,s),p(e,i),e[i]=n[s],a=o+1|0;continue}else return}}else{let a=i-1|0;for(;;){let i=a;if(i>=0){let o=t+i|0,s=r+i|0;p(n,s),p(e,o),e[o]=n[s],a=i-1|0;continue}else return}}}function Mt(e){return{val:``}}function Nt(e,t){let n=e;n.val=`${n.val}${String.fromCodePoint(t)}`}function Pt(e,t){let n=e;n.val=`${n.val}${t}`}function Ft(e,t){return yt(e,t)>0}function E(e){let t=Mt(0);return Yt(e,{self:t,method_0:Pt,method_1:D,method_2:Nt}),t.val}function It(e,t){return we(e,t)}function Lt(e,t,n,r){let i;i=r===void 0?e.length:r;let a=n,o=0;for(;;){let n=a,r=o;if(n<i&&r<t){let t=e.charCodeAt(n);if(55296<=t&&t<=56319&&(n+1|0)<i){let t=n+1|0,i=e.charCodeAt(t);if(56320<=i&&i<=57343){a=n+2|0,o=r+1|0;continue}else y(`invalid surrogate pair`)}a=n+1|0,o=r+1|0;continue}else return r===t&&n===i}}function Rt(e,t,n){let r=e.length,i;return i=n===void 0?r:n,t>=0&&t<=i&&i<=r?e.substring(t,i):d()}function D(e,t,n,r){let i=e;i.val=`${i.val}${Rt(t,n,n+r|0)}`}function zt(e){return[]}function Bt(e){return[]}function Vt(e){return[]}function Ht(e,t){m(e,t)}function Ut(e,t){m(e,t)}function O(e,t){m(e,t)}function k(e,t){m(e,t)}function Wt(e,t){m(e,t)}function Gt(e){return String.fromCodePoint(e)}function Kt(e,t){let n={val:Ee};e(e=>(t(e),1));let r=n.val;switch(r.$tag){case 0:return;case 1:r._0;return;case 2:return r._0;case 3:d();return;default:d();return}}function qt(e){let t=[];return Kt(e,e=>{O(t,e)}),t}function Jt(e){return e()}function Yt(e,t){t.method_0(t.self,It(e,10))}function Xt(e){return t=>{let n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];if(t(n)!==1)return 0;r=i+1|0;continue}else return 1}}}function Zt(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{buf:e,start:a,end:i}:mt(`View index out of bounds`)}function Qt(e){return{hi:0,lo:e}}function $t(e){return Qt(e)}function en(e){return $t(e)}function tn(e){return je(e)}function nn(e){return{hi:e>>31&-1,lo:e|0}}function rn(e){return nn(e)}function an(e){return e.lo}function A(e){return an(e)&255}function on(e,t){return{hi:e.hi&t.hi,lo:e.lo&t.lo}}function sn(e,t){return{hi:e.hi|t.hi,lo:e.lo|t.lo}}function cn(e,t){return{hi:e.hi^t.hi,lo:e.lo^t.lo}}function ln(e,t){let n=t&63;if(n===0)return e;if(n<32){let t=e.hi,r=e.lo,i=t,a=r;return{hi:i<<n|a>>>(32-n|0)|0,lo:a<<n}}else return{hi:e.lo<<(n-32|0),lo:0}}function un(e,t){let n=t&63;return n===0?e:n<32?{hi:e.hi>>>n|0,lo:e.lo>>>n|e.hi<<(32-n|0)}:{hi:0,lo:e.hi>>>(n-32|0)|0}}function dn(e,t){return sn(e,t)}function fn(e,t){return ln(e,t)}function pn(e){return Ne(e)}function mn(e){return pn(e)}function hn(e){return je(e)}function gn(e){return Me(e)}function _n(e,t){let n=e,r=t;return n.hi===r.hi&&n.lo===r.lo}function j(e,t){return on(e,t)}function M(e,t){return sn(e,t)}function N(e,t){return cn(e,t)}function P(e,t){return ln(e,t)}function F(e,t){return un(e,t)}function vn(e){return Pe(e)}function yn(e,t){if(e<=0)return Fe;let n=Te(e,t(0)),r=1;for(;;){let i=r;if(i<e){p(n,i),n[i]=t(i),r=i+1|0;continue}else break}return n}function bn(e){console.log(e)}function xn(e,t,n,r,i){let a=(t+i|0)-1|0,o=(r+i|0)-1|0,s=e.length,c=n.length;if(i>=0&&t>=0&&a<s&&r>=0&&o<c){jt(e,t,n,r,i);return}else{d();return}}function Sn(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.buf,r=e.start+t|0;return p(n,r),n[r]}else return pt(`index out of bounds: the len is from 0 to ${E(e.end-e.start|0)} but the index is ${E(t)}`)}function Cn(e){let t=e.length,n=Array(t),r=0;for(;;){let i=r;if(i<t){n[i]=e[(t-i|0)-1|0],r=i+1|0;continue}else break}return n}function wn(e,t){let n=e.data.length<=0?1:e.data.length,r,i=n;for(;;){let e=i;if(e>=t){r=e;break}i=Math.imul(e,2)|0}if(r!==e.data.length){let t=Te(r,0);jt(t,0,e.data,0,e.len),e.data=t;return}else return}function I(e,t){wn(e,e.len+1|0);let n=e.data,r=e.len;p(n,r),n[r]=t,e.len=e.len+1|0}function L(e){return C(Zt(e.data,0,e.len))}function R(e){return{data:Te(e<1?1:e,0),len:0}}function Tn(e,t){let n=t.length;wn(e,e.len+n|0),xn(e.data,e.len,t,0,n),e.len=e.len+n|0}function En(e){switch(e){case 0:return`40`;case 1:return`41`;case 2:return`42`;case 3:return`43`;case 4:return`44`;case 5:return`45`;case 6:return`46`;case 7:return`47`;default:return`49`}}function Dn(e){switch(e){case 0:return`30`;case 1:return`31`;case 2:return`32`;case 3:return`33`;case 4:return`34`;case 5:return`35`;case 6:return`36`;case 7:return`37`;default:return`39`}}function On(e){let t=[],n=e.color;n===void 0||k(t,Dn(n));let r=e.bg_color;r===void 0||k(t,En(r));let i=e.formats,a=i.length,o=0;for(;;){let e=o;if(e<a){switch(i[e]){case 0:k(t,`1`);break;case 1:k(t,`4`);break;case 2:k(t,`5`);break;case 3:k(t,`7`);break;case 4:k(t,`8`);break;case 5:k(t,`9`);break;default:k(t,`3`)}o=e+1|0;continue}else break}return t.length>0?`[${vt(t,{str:`;`,start:0,end:1})}m${e.str}[0m`:e.str}function kn(e){return{str:e,bg_color:void 0,color:void 0,formats:[]}}function An(e){return{str:e.str,bg_color:e.bg_color,color:1,formats:e.formats}}function jn(e){return{str:e.str,bg_color:e.bg_color,color:3,formats:e.formats}}function Mn(e){return{str:e.str,bg_color:e.bg_color,color:4,formats:e.formats}}function Nn(e){let t=e.str,n=e.bg_color,r=e.color,i=[];return Wt(i,0),_t(i,Xt(e.formats)),{str:t,bg_color:n,color:r,formats:i}}function Pn(e,t){let n=`${On(An(Nn(kn(`Panic: `))))}${On(jn(kn(e)))} at ${On(Mn(kn(t)))}`;bn(n),y(n)}function Fn(e){let t=Vt(0),n=0;for(;n<e.length;){let r=n;p(e,r);let i=e.charCodeAt(r);if(i>=55296&&i<=56319&&(n+1|0)<e.length){let r=n+1|0;p(e,r);let a=e.charCodeAt(r);if(a>=56320&&a<=57343){let e=(65536+(i-55296<<10)|0)+(a-56320|0)|0;O(t,(240|e>>18)&255),O(t,(128|e>>12&63)&255),O(t,(128|e>>6&63)&255),O(t,(128|e&63)&255),n=n+1|0}else O(t,(224|i>>12)&255),O(t,(128|i>>6&63)&255),O(t,(128|i&63)&255)}else i<128?O(t,i&255):i<2048?(O(t,(192|i>>6)&255),O(t,(128|i&63)&255)):(O(t,(224|i>>12)&255),O(t,(128|i>>6&63)&255),O(t,(128|i&63)&255));n=n+1|0}return C({buf:t,start:0,end:t.length})}function In(e){return{bytes:Fn(e)}}function Ln(e){let t=0;for(;t<(e.end-e.start|0);){let n=b(e,t);if(!(n&128))t=t+1|0;else if((n&224)==192){if((t+1|0)>=(e.end-e.start|0)||(b(e,t+1|0)&192)!=128)return!1;t=t+2|0}else if((n&240)==224){if((t+2|0)>=(e.end-e.start|0))return!1;let n=b(e,t+1|0),r=b(e,t+2|0),i;if(i=(n&192)==128?(r&192)!=128:!0,i)return!1;t=t+3|0}else if((n&248)==240){if((t+3|0)>=(e.end-e.start|0))return!1;let n=b(e,t+1|0),r=b(e,t+2|0),i=b(e,t+3|0),a;if((n&192)!=128)a=!0;else{let e;e=(r&192)==128?(i&192)!=128:!0,a=e}if(a)return!1;t=t+4|0}else return!1}return!0}function Rn(e){if(Ln(S(e,0,void 0)))return{bytes:At(Ot(e))}}function zn(e){let t=0,n=``;for(;t<e.length;){let r=t;p(e,r);let i=e[r],a;if(!(i&128))a=i;else if((i&224)==192){if((t+1|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n];if((r&192)!=128)return;t=t+1|0,a=(i&31)<<6|r&63}else if((i&240)==224){if((t+2|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c;if(c=(r&192)==128?(s&192)!=128:!0,c)return;t=t+2|0,a=(i&15)<<12|(r&63)<<6|s&63}else if((i&248)==240){if((t+3|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c=t+3|0;p(e,c);let l=e[c],u;if((r&192)!=128)u=!0;else{let e;e=(s&192)==128?(l&192)!=128:!0,u=e}if(u)return;t=t+3|0,a=(i&7)<<18|(r&63)<<12|(s&63)<<6|l&63}else return;n=`${n}${Gt(a)}`,t=t+1|0}return n}function Bn(e){let t=zn(e.bytes);return t===void 0?d():t}function Vn(e){return gn(e)}function Hn(e){return hn(e)}function Un(e){let t=Vt(0);return O(t,A(j(F(e,56),h))),O(t,A(j(F(e,48),h))),O(t,A(j(F(e,40),h))),O(t,A(j(F(e,32),h))),O(t,A(j(F(e,24),h))),O(t,A(j(F(e,16),h))),O(t,A(j(F(e,8),h))),O(t,A(j(e,h))),C({buf:t,start:0,end:t.length})}function Wn(e){e.length!==8&&Pn(`Invalid byte array length`,`/Users/zxch3n/Code/flock/moon/memcomparable/utils.mbt:28:5-28:54`);let t=Ie,n=t;p(e,0),t=M(n,P(w(e[0]),56));let r=t;p(e,1),t=M(r,P(w(e[1]),48));let i=t;p(e,2),t=M(i,P(w(e[2]),40));let a=t;p(e,3),t=M(a,P(w(e[3]),32));let o=t;p(e,4),t=M(o,P(w(e[4]),24));let s=t;p(e,5),t=M(s,P(w(e[5]),16));let c=t;p(e,6),t=M(c,P(w(e[6]),8));let l=t;return p(e,7),t=M(l,w(e[7])),t}function Gn(){return{parts:Bt(0)}}function z(e,t){Ht(e.parts,t)}function Kn(e){return e===e?e:e<0?-ut:ut}function qn(e,t){I(t,1);let n=kt(e);for(;;){let e=Jt(n);if(e===-1)break;{let n=e;I(t,n),n===0&&I(t,255);continue}}I(t,0)}function Jn(e,t){I(t,2);let n=e.bytes,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];I(t,r),r===0&&I(t,255),i=e+1|0;continue}else break}I(t,0)}function Yn(e,t){I(t,33);let n=Kn(e),r=Un(n<0?N(Vn(n),Le):N(Vn(n),Re)),i=r.length,a=0;for(;;){let e=a;if(e<i){let n=r[e];I(t,n),a=e+1|0;continue}else return}}function Xn(e){let t=[],n=e;for(;Ft(n,0n);)O(t,Ce(Tt(n,256n))&255),n=wt(n,256n);let r=Cn(t);return C({buf:r,start:0,end:r.length})}function Zn(e,t){if(bt(e,0n)){I(t,20);return}let n=Ft(e,0n),r=Xn(n?e:xt(e)),i=r.length;if(n===!1){i<=8?I(t,(20-(i&255)|0)&255):(I(t,11),i>255&&y(`n is too large`),I(t,(i&255^255)&255));let e=R(0),n=0;for(;;){let t=n;if(t<r.length){p(r,t);let i=r[t];I(e,(i^255)&255),n=t+1|0;continue}else break}Tn(t,L(e));return}else{i<=8?I(t,(20+(i&255)|0)&255):(I(t,29),i>255&&y(`n is too large`),I(t,i&255)),Tn(t,r);return}}function Qn(e,t){switch(e.$tag){case 0:{let n=e._0;qn(x(n,0,n.length),t);return}case 1:{let n=e._0;Jn(n,t);return}case 2:{let n=e._0;Zn(n,t);return}case 3:{let n=e._0;Yn(n,t);return}case 4:I(t,38);return;default:I(t,39);return}}function $n(e){let t=R(0),n=e.parts,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];Qn(r,t),i=e+1|0;continue}else break}return L(t)}function er(e,t){let n=R(0),r=t;for(;r<(e.end-e.start|0);){let t=b(e,r);if(r=r+1|0,t===0){let t;if(t=r<(e.end-e.start|0)?b(e,r)===255:!1,t){I(n,0),r=r+1|0;continue}else{let e=L(n);return new Be({_0:x(e,0,e.length),_1:r})}}I(n,t)}return new ze(g)}function B(e){let t=f(Ie),n=f(Ue),r=(e.end-e.start|0)-1|0;for(;;){let i=r;if(i>=0){let a=f(rn(b(e,i)));t=St(t,Ct(n,a)),n=Ct(n,f(We)),r=i-1|0;continue}else break}return t}function tr(e,t){let n;if(n=20<=t?t<=28:!1,n){let n=(t-20|0)&255;if((e.end-e.start|0)<n)return new _(g);let r=S(e,0,n);return new v({_0:S(e,n,void 0),_1:B(r)})}else{let n;if(n=12<=t?t<20:!1,n){let n=(20-t|0)&255;if((e.end-e.start|0)<n)return new _(g);let r=S(e,0,n),i=S(e,n,void 0),a=R(0),o=0;for(;;){let e=o;if(e<(r.end-r.start|0)){I(a,(b(r,e)^255)&255),o=e+1|0;continue}else break}let s=L(a);return new v({_0:i,_1:xt(B(x(s,0,s.length)))})}else if(t===11){if((e.end-e.start|0)<1)return new _(g);let t=(b(e,0)^255)&255;if((e.end-e.start|0)<(t+1|0))return new _(g);let n=S(e,1,t+1|0),r=S(e,t+1|0,void 0),i=R(0),a=0;for(;;){let e=a;if(e<(n.end-n.start|0)){I(i,(b(n,e)^255)&255),a=e+1|0;continue}else break}let o=L(i);return new v({_0:r,_1:xt(B(x(o,0,o.length)))})}else if(t===29){if((e.end-e.start|0)<1)return new _(g);let t=b(e,0);if((e.end-e.start|0)<(t+1|0))return new _(g);let n=S(e,1,t+1|0);return new v({_0:S(e,t+1|0,void 0),_1:B(n)})}else return new _(new Ve(t))}}function nr(e,t){if((t+8|0)>(e.end-e.start|0))return new Ge(g);let n=Vt(0),r=0;for(;;){let i=r;if(i<8){O(n,b(e,t+i|0)),r=i+1|0;continue}else break}let i=Wn(C({buf:n,start:0,end:n.length}));return new Ke({_0:_n(j(i,Re),Ie)?Hn(N(i,Le)):Hn(N(i,Re)),_1:t+8|0})}function rr(e){let t=Gn(),n=0;for(;n<(e.end-e.start|0);){let r=b(e,n);if(n=n+1|0,r===2){let r=er(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1,s=Rn(a);if(s===void 0)return new $e(He);z(t,new Je(s)),n=o}else if(r===1){let r=er(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;z(t,new qe(At(Ot(a)))),n=o}else if(r>=11&&r<=29){let i=tr(S(e,n,void 0),r),a;if(i.$tag===1)a=i._0;else return i;let o=a._0,s=a._1;z(t,new Ye(s)),n=(e.end-e.start|0)-(o.end-o.start|0)|0}else if(r===33){let r=nr(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;z(t,new Xe(a)),n=o}else if(r===38)z(t,Ze);else if(r===39)z(t,Qe);else return new $e(new Ve(r))}return new et(t)}function ir(e){switch(e.$tag){case 0:{let t=e._0;return new rt(t)}case 1:{let t=e._0;return new nt(Bn(t))}case 2:{let t=e._0;return new tt(mn(Dt(t)))}case 3:{let t=e._0;return new tt(t)}case 4:return at;default:return it}}function ar(e){switch(e.$tag){case 2:{let t=e._0;return new qe(t)}case 1:{let t=e._0;return new Je(In(t))}case 0:{let t=e._0;return mn(vn(t))===t?new Ye(f(vn(t))):new Xe(t)}case 3:return Qe;default:return Ze}}function or(e){let t=Gn(),n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];Ht(t.parts,ar(n)),r=i+1|0;continue}else break}return $n(t)}function sr(e){let t;_L:{_L$2:{let n=rr(x(e,0,e.length));if(n.$tag===1)t=n._0;else{n._0;break _L$2}break _L}t=dt(`Failed to decode key`)}let n=zt(0),r=t.parts,i=r.length,a=0;for(;;){let e=a;if(e<i){let t=r[e];Ut(n,ir(t)),a=e+1|0;continue}else break}return n}function cr(e){if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Key parts must be finite numbers`);return{$tag:0,_0:e}}if(typeof e==`string`)return{$tag:1,_0:e};if(e===!0)return{$tag:3};if(e===!1)return{$tag:4};throw TypeError(`Key parts must be strings, numbers, or booleans`)}function lr(e){if(e instanceof Uint8Array)return e;if(e&&typeof e==`object`){let t=e.buf;if(t instanceof Uint8Array){let n=e.start??0,r=e.end??t.length;return t.subarray(n,r)}}throw TypeError(`Invalid bytes payload in memcomparable decode`)}function ur(e){switch(e?.$tag){case 0:return e._0;case 1:return e._0;case 3:return!0;case 4:return!1;case 2:return lr(e._0);default:throw TypeError(`Unsupported memcomparable key part`)}}function V(e){return or(e.map(cr))}function dr(e){return sr(e).map(e=>ur(e))}function fr(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return e.length===t.length?0:e.length<t.length?-1:1}function pr(e){if(e.length===0)return;let t=Array.from(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n<255)return t[e]=n+1,new Uint8Array(t.slice(0,e+1))}}function mr(e){return JSON.stringify(e)}function hr(){return{now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),randomUUID:()=>{try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return`${Date.now()}_${Math.random().toString(16).slice(2)}`}}}function gr(e){if(!(typeof BroadcastChannel>`u`))try{let t=new BroadcastChannel(e);return{postMessage:e=>{try{t.postMessage(e)}catch{}},subscribe:e=>{let n=t=>{e(t.data)};return t.addEventListener(`message`,n),()=>{t.removeEventListener(`message`,n)}},close:()=>{try{t.close()}catch{}}}}catch{return}}function _r(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.t===`req`||t.t===`res`||t.t===`commit`}function vr(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{name:`Error`,message:String(e)}}const yr=3e3,br=1024;function xr(e){return e instanceof Error?!!(e.name===`HostLost`||e.message.includes(`Timed out waiting for host response`)):!1}function Sr(e){return e<=0?25:Math.min(500,25*2**(e-1))}function H(e,t){return e.origin===t&&e.source===`local`}function Cr(e,t){return`${e}|${t}`}function wr(e){let t=Error(e.message);return t.name=e.name,e.stack&&(t.stack=e.stack),t}var Tr=class{runtime;tabId;roleValue;roleListeners;roleUnsubscribe;closed;constructor(e,t,n){this.runtime=e,this.tabId=t,this.roleValue=n.getRole(),this.roleListeners=new Set,this.roleUnsubscribe=n.subscribeRoleChange?.(e=>{this.setRole(e)}),this.closed=!1}getRole(){return this.roleValue}isHost(){return this.roleValue===`host`}subscribeRoleChange(e){this.roleListeners.add(e);try{e(this.roleValue)}catch{}return()=>{this.roleListeners.delete(e)}}setRole(e){if(e!==this.roleValue){this.roleValue=e;for(let t of this.roleListeners)try{t(e)}catch{}}}closeRole(){this.roleUnsubscribe?.(),this.roleUnsubscribe=void 0,this.setRole(`unknown`)}},Er=class extends Tr{writeQueue;ingestCommit;executeWriteRequest;constructor(e){super(e.runtime,e.tabId,e.roleProvider),this.ingestCommit=e.ingestCommit,this.executeWriteRequest=e.executeWriteRequest,this.writeQueue=Promise.resolve()}enqueueWrite(e){let t=this.writeQueue.then(e,e);return this.writeQueue=t.then(()=>void 0,()=>void 0),t}async dispatchWriteRequest(e){if(this.closed)throw Error(`FlockSQLite is closed`);let t=this.runtime.randomUUID(),{commit:n,result:r}=await this.enqueueWrite(()=>this.executeWriteRequest(e,this.tabId,t));return this.ingestCommit(n,H(n,this.tabId)),{commit:n,result:r}}close(){this.closed=!0,this.closeRole()}},Dr=class extends Tr{transport;transportUnsubscribe;pendingRequests;hostResponseCache;hostInFlight;writeQueue;ingestCommit;executeWriteRequest;constructor(e){super(e.runtime,e.tabId,e.roleProvider),this.transport=e.transport,this.transportUnsubscribe=this.transport.subscribe(e=>{try{this.handleTransportMessage(e)}catch{}}),this.pendingRequests=new Map,this.hostResponseCache=new ue(1024),this.hostInFlight=new Map,this.writeQueue=Promise.resolve(),this.ingestCommit=e.ingestCommit,this.executeWriteRequest=e.executeWriteRequest}enqueueWrite(e){let t=this.writeQueue.then(e,e);return this.writeQueue=t.then(()=>void 0,()=>void 0),t}shouldForwardWrites(){return this.roleValue!==`host`}handleTransportMessage(e){if(_r(e)){if(e.t===`res`){if(e.to!==this.tabId)return;let t=this.pendingRequests.get(e.id);if(!t)return;this.runtime.clearTimeout(t.timeoutId),this.pendingRequests.delete(e.id),t.resolve(e);return}if(e.t===`commit`){let t=e.commit;this.ingestCommit(t,H(t,this.tabId));return}if(e.t===`req`){if(e.from===this.tabId||this.roleValue!==`host`||this.closed)return;this.processHostRequest(e)}}}broadcastCommit(e){this.closed||this.roleValue===`host`&&this.transport.postMessage({t:`commit`,commit:e})}async forwardWriteRequest(e,t,n=3e3){if(this.closed)throw Error(`FlockSQLite is closed`);let r={t:`req`,from:this.tabId,id:t,payload:e},i=await new Promise((e,i)=>{let a=this.runtime.setTimeout(()=>{this.pendingRequests.delete(t),i(Error(`Timed out waiting for host response`))},n);this.pendingRequests.set(t,{resolve:e,reject:i,timeoutId:a}),this.transport.postMessage(r)});if(!i.ok)throw i.error?wr(i.error):Error(`Host rejected request`);let a=i.commit;return a&&this.ingestCommit(a,H(a,this.tabId)),{commit:a,result:i.result}}async dispatchWriteRequest(e){if(this.closed)throw Error(`FlockSQLite is closed`);let t=this.runtime.randomUUID(),n;for(let r=1;r<=5;r+=1){if(!this.shouldForwardWrites()){let{commit:n,result:r}=await this.enqueueWrite(()=>this.executeWriteRequest(e,this.tabId,t));return this.ingestCommit(n,H(n,this.tabId)),this.broadcastCommit(n),{commit:n,result:r}}try{let n=await this.forwardWriteRequest(e,t);if(!n.commit)throw Error(`Host did not return commit`);return{commit:n.commit,result:n.result}}catch(e){if(n=e,r>=5||!xr(e))throw e;await new Promise(e=>{this.runtime.setTimeout(()=>e(),Sr(r))})}}throw n??Error(`Failed to dispatch write request`)}async processHostRequest(e){let t=Cr(e.from,e.id),n=this.hostResponseCache.get(t);if(n){n.ok&&n.commit&&this.broadcastCommit(n.commit),this.transport.postMessage(n);return}let r=this.hostInFlight.get(t);r||(r=this.enqueueWrite(async()=>{if(this.roleValue!==`host`||this.closed)return{t:`res`,to:e.from,id:e.id,ok:!1,error:{name:`HostLost`,message:`Host role was lost`}};try{let{commit:t,result:n}=await this.executeWriteRequest(e.payload,e.from,e.id);return this.ingestCommit(t,H(t,this.tabId)),this.broadcastCommit(t),{t:`res`,to:e.from,id:e.id,ok:!0,commit:t,result:n}}catch(t){return{t:`res`,to:e.from,id:e.id,ok:!1,error:vr(t)}}}),this.hostInFlight.set(t,r),r.finally(()=>{this.hostInFlight.delete(t)}));let i=await r;this.hostResponseCache.set(t,i),this.transport.postMessage(i)}close(){if(!this.closed){this.closed=!0,this.transportUnsubscribe?.(),this.transportUnsubscribe=void 0,this.transport.close?.();for(let{reject:e,timeoutId:t}of this.pendingRequests.values()){this.runtime.clearTimeout(t);try{e(Error(`FlockSQLite closed`))}catch{}}this.pendingRequests.clear(),this.closeRole()}}};function Or(e){return e.transport?new Dr({...e,transport:e.transport}):new Er(e)}const kr=new TextEncoder,Ar=new TextDecoder,jr=globalThis.structuredClone;function Mr(e){return kr.encode(e).length}function U(e){return typeof e==`string`&&Mr(e)<128}function Nr(){let e=new Uint8Array(32),t=typeof crypto<`u`?crypto:void 0;if(t?.getRandomValues)t.getRandomValues(e);else if(t?.randomBytes){let n=t.randomBytes(32);e.set(n)}else for(let t=0;t<32;t+=1)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function W(e){if(e===void 0)return Nr();if(!U(e))throw TypeError(`peerId must be a UTF-8 string under 128 bytes`);return e}function G(e){return e===void 0?e:jr?jr(e):JSON.parse(JSON.stringify(e))}function K(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return G(e)}function Pr(e){return K(e)??{}}function Fr(e,t){if(!(!t||typeof t!=`object`)){if(`data`in t){let n=t.data;e.data=n===void 0?void 0:G(n)}`metadata`in t&&(e.metadata=K(t.metadata))}}function q(e){let t={};return Fr(t,e),t}function J(e,t){let n=q(e);return Fr(n,t),n}function Ir(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r]-t[r];if(n!==0)return n}return e.length-t.length}function Lr(e){if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r||!U(n))continue;let{physicalTime:e,logicalCounter:i}=r;if(typeof e!=`number`||!Number.isFinite(e)||typeof i!=`number`||!Number.isFinite(i))continue;let a=kr.encode(n);t.push({peer:n,peerBytes:a,timestamp:Math.trunc(e),counter:Math.max(0,Math.trunc(i))})}return t.sort((e,t)=>{if(e.timestamp!==t.timestamp)return e.timestamp-t.timestamp;let n=Ir(e.peerBytes,t.peerBytes);return n===0?e.counter-t.counter:n}),t}function Y(e,t){if(!Number.isFinite(e)||e<0)throw TypeError(`leb128 values must be finite and non-negative`);let n=Math.trunc(e);if(n===0){t.push(0);return}for(;n>0;){let e=n%128;n=Math.floor(n/128),t.push(n>0?e|128:e)}}function Rr(e,t){Y(e.length,t);for(let n=0;n<e.length;n+=1)t.push(e[n])}const X=new Uint8Array([86,69,86,69]);function zr(e){let t=Lr(e),n=Array.from(X);if(t.length===0)return Uint8Array.from(n);let r=0;for(let e=0;e<t.length;e+=1){let i=t[e];if(i.timestamp<0)throw TypeError(`timestamp must be non-negative`);if(e===0)Y(i.timestamp,n),r=i.timestamp;else{let e=i.timestamp-r;if(e<0)throw TypeError(`version vector timestamps must be non-decreasing`);Y(e,n),r=i.timestamp}Y(i.counter,n),Rr(i.peerBytes,n)}return Uint8Array.from(n)}function Z(e,t){let n=0,r=1,i=0;for(;t+i<e.length;){let a=e[t+i];if(i+=1,n+=(a&127)*r,!(a&128))break;r*=128}return[n,i]}function Br(e,t){let[n,r]=Z(e,t),i=t+r,a=i+n;if(a>e.length)throw TypeError(`varString length exceeds buffer`);let o=e.subarray(i,a);return[Ar.decode(o),r+n]}function Vr(e){return e.length>=4&&e[0]===X[0]&&e[1]===X[1]&&e[2]===X[2]&&e[3]===X[3]}function Hr(e){let t=0,[n,r]=Z(e,t);t+=r;let[i,a]=Z(e,t);t+=a;let o={};for(let r=0;r<n;r+=1){let[n,r]=Br(e,t);if(t+=r,!U(n))throw TypeError(`invalid peer id in encoded version vector`);let[a,s]=Z(e,t);t+=s;let[c,l]=Z(e,t);t+=l,o[n]={physicalTime:i+a,logicalCounter:c}}return o}function Ur(e){let t=4,n={};if(t===e.length)return n;let[r,i]=Z(e,t);t+=i;let[a,o]=Z(e,t);t+=o;let[s,c]=Br(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);n[s]={physicalTime:r,logicalCounter:a};let l=r;for(;t<e.length;){let[r,i]=Z(e,t);t+=i;let[a,o]=Z(e,t);t+=o;let[s,c]=Br(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);let u=l+r;if(u<l)throw TypeError(`version vector timestamps must be non-decreasing`);n[s]={physicalTime:u,logicalCounter:a},l=u}return n}function Wr(e){return Vr(e)?Ur(e):Hr(e)}function Gr(e){return zr(e)}function Kr(e){return Wr(e)}function Q(e,t){let n={c:$r(e)};t.data!==void 0&&(n.d=G(t.data));let r=K(t.metadata);return r!==void 0&&(n.m=r),n}function qr(e){return!e||typeof e!=`object`?{accept:!0}:`accept`in e?e.accept?{accept:!0}:{accept:!1,reason:e.reason??`rejected`}:{accept:!0}}function Jr(e){return typeof e==`object`&&!!e&&(Object.prototype.hasOwnProperty.call(e,`hooks`)||Object.prototype.hasOwnProperty.call(e,`from`)||Object.prototype.hasOwnProperty.call(e,`pruneTombstonesBefore`)||Object.prototype.hasOwnProperty.call(e,`peerId`))}function Yr(e){return typeof e==`object`&&!!e&&Object.prototype.hasOwnProperty.call(e,`bundle`)}function Xr(e){if(e)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function $(e){if(e!=null)return JSON.parse(e)}function Zr(e){let t=e.split(`,`);if(t.length<3)return{physicalTime:0,logicalCounter:0,peerId:``};let n=Number(t[0]),r=Number(t[1]),i=t.slice(2).join(`,`);return{physicalTime:Number.isFinite(n)?n:0,logicalCounter:Number.isFinite(r)?Math.trunc(r):0,peerId:U(i)?i:``}}function Qr(e,t,n){if(!(typeof e!=`number`||typeof t!=`number`||typeof n!=`string`)&&U(n)&&!(!Number.isFinite(e)||!Number.isFinite(t)))return{physicalTime:e,logicalCounter:Math.trunc(t),peerId:n}}function $r(e){return`${e.physicalTime},${e.logicalCounter},${e.peerId}`}function ei(e,t){return e.physicalTime===t.physicalTime?e.logicalCounter===t.logicalCounter?e.peerId===t.peerId?0:e.peerId>t.peerId?1:-1:e.logicalCounter>t.logicalCounter?1:-1:e.physicalTime>t.physicalTime?1:-1}function ti(e){if(!e)return;let{physicalTime:t,logicalCounter:n}=e;if(!(!Number.isFinite(t)||!Number.isFinite(n)))return{physicalTime:t,logicalCounter:Math.trunc(n)}}function ni(e,t){if(t.length===0)return!0;if(e.length<t.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}async function ri(e){return e.map(e=>({key:e.key,data:e.data,metadata:e.metadata,physical:e.physical,logical:e.logical,peer:e.peer}))}function ii(e){if(!e)return``;if(typeof e!=`string`)throw TypeError(`tablePrefix must be a string`);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw TypeError(`tablePrefix must start with a letter/underscore and use only letters, digits, or underscores`);return e}function ai(e){return{kv:`${e}kv`,overridden:`${e}overridden`,meta:`${e}meta`,idxKvPeerClock:`${e}idx_kv_peer_clock_key`,idxOverriddenKey:`${e}idx_overridden_key`,idxOverriddenSupersededAt:`${e}idx_overridden_superseded_at`}}function oi(e){if(e===`host`||e===`participant`||e===`unknown`)return e}function si(e){let t=e.getRole?.(),n=oi(t);if(n)return n;let r=e.getSQLiteInfo?.();if(r&&typeof r==`object`){let{isHost:e,isReady:t}=r;if(e===!0&&t===!0)return`host`;if(t===!1)return`unknown`;if(t===!0)return`participant`}return`host`}function ci(e){let t=e.subscribeRoleChange;return{getRole:()=>si(e),subscribeRoleChange:typeof t==`function`?n=>t.call(e,e=>{let t=oi(e);t&&n(t)}):void 0}}const li=2048;function ui(e,t){return t?`flock:rpc:${e}:${t}`:`flock:rpc:${e}`}function di(e,t,n){if(typeof n==`string`&&n.length>0)return n;let r=e.getSQLiteInfo?.();if(r&&typeof r==`object`){let e=r.tabId;if(typeof e==`string`&&e.length>0)return e}return t.randomUUID()}var fi=class t{db;peerIdValue;vv;maxHlc;listeners;tables;runtime;eventBatcher;coordinator;seenCommitIds;closed;constructor(e,t,n,r,i,a,o,s,c){this.db=e,this.peerIdValue=t,this.vv=n,this.maxHlc=r,this.listeners=new Set,this.tables=i,this.runtime=o,this.eventBatcher=new le({runtime:o,emit:(e,t)=>this.emitEvents(e,t)}),this.seenCommitIds=new de(2048),this.coordinator=Or({runtime:o,tabId:a,transport:s,roleProvider:c,ingestCommit:(e,t)=>this.applyCommit(e,t),executeWriteRequest:(e,t,n)=>this.executeWriteRequest(e,t,n)}),this.closed=!1}static async open(n){let r=n.connection??await(0,e.openStore)({path:n.path}),i=ii(n.tablePrefix),a=ai(i);await t.ensureSchema(r,a);let o=await t.resolvePeerId(r,a,n.peerId),{vv:s,maxHlc:c}=await t.loadVersionState(r,a),l=n.multiTab?.runtime??hr(),u=n.multiTab?.roleProvider??ci(r),ee=ui(n.path,i),te=(n.multiTab?.transportFactory??gr)(ee);return new t(r,o,s,c,a,di(r,l,n.multiTab?.tabId),l,te,u)}static async fromJson(e){let n=await t.open(e);return await n.importJson(e.bundle),n}async close(){this.closed||(this.closed=!0,this.coordinator.close(),this.eventBatcher.close(),await this.db.close())}getRole(){return this.coordinator.getRole()}isHost(){return this.coordinator.isHost()}subscribeRoleChange(e){return this.coordinator.subscribeRoleChange(e)}dispatchWriteRequest(e){return this.coordinator.dispatchWriteRequest(e)}applyCommit(e,t){if(this.seenCommitIds.has(e.commitId))return;if(this.seenCommitIds.add(e.commitId),e.meta?.peerId)try{this.peerIdValue=W(e.meta.peerId)}catch{}let n=e.events.map(t=>({key:G(t.key),payload:q(t.payload),source:e.source,clock:{...t.clock}}));for(let e of n)this.bumpVersion(e.clock);n.length!==0&&this.eventBatcher.handleCommitEvents(e.source,n,t)}async executeWriteRequest(e,t,n){let r=[],i,a;if(e.kind===`apply`)await this.applyOperation({key:e.key,payload:e.payload,now:e.now,skipSameValue:e.skipSameValue,source:e.source,eventSink:r});else if(e.kind===`putMvr`)await this.putMvrInternal(e.key,e.value,e.now,r);else if(e.kind===`import`)i=await this.importBundleInternal(e.bundle,r);else if(e.kind===`setPeerId`)await this.setPeerIdInternal(e.peerId),a={peerId:this.peerIdValue};else{let t=e;throw Error(`Unsupported write payload ${String(t)}`)}return{commit:{commitId:`c:${t}:${n}`,origin:t,source:e.source,events:r.map(e=>({key:e.key.slice(),clock:{...e.clock},payload:q(e.payload)})),...a?{meta:a}:{}},result:i}}static async ensureSchema(e,t){await e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS ${t.kv} (
3
3
  key BLOB PRIMARY KEY,
4
4
  data TEXT NULL,
@@ -23,7 +23,7 @@ let e=require(`@loro-dev/unisqlite`);const t=16,n=17,r=18,i=32,a=33,o=34,s=35,c=
23
23
  metadata=excluded.metadata,
24
24
  physical=excluded.physical,
25
25
  logical=excluded.logical,
26
- peer=excluded.peer`,[t,r,i,c.physicalTime,c.logicalCounter,c.peerId]),a=!0}),o&&this.bumpVersion(o),a&&o){let t={key:e.key.slice(),payload:n,source:e.source,clock:o};e.eventSink.push(t)}return a}emitEvents(e,t){if(this.listeners.size===0||t.length===0)return;let n={source:e,events:t.map(e=>({key:G(e.key),clock:{...e.clock},value:e.payload.data===void 0?void 0:G(e.payload.data),metadata:K(e.payload.metadata),payload:q(e.payload)}))};this.listeners.forEach(e=>{e(n)})}async put(e,t,n){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{data:G(t)},now:n,skipSameValue:!0})}async putWithMeta(e,t,n={}){let r={data:G(t)};n.metadata&&(r.metadata=K(n.metadata));let i=n.hooks?.transform;if(i){let t=q(r),a=J(r,await i({key:e.slice(),now:n.now},t)??t);if(a.data===void 0)throw TypeError(`putWithMeta requires a data value`);await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:a,now:n.now,skipSameValue:!0});return}await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:r,now:n.now,skipSameValue:!0})}async delete(e,t){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{},now:t,skipSameValue:!0})}async forcePut(e,t,n){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{data:G(t)},now:n,skipSameValue:!1})}async forcePutWithMeta(e,t,n={}){let r={data:G(t)};n.metadata&&(r.metadata=K(n.metadata));let i=n.hooks?.transform;if(i){let t=q(r),a=J(r,await i({key:e.slice(),now:n.now},t)??t);if(a.data===void 0)throw TypeError(`forcePutWithMeta requires a data value`);await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:a,now:n.now,skipSameValue:!1});return}await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:r,now:n.now,skipSameValue:!1})}async forceDelete(e,t){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{},now:t,skipSameValue:!1})}async set(e,t,n){await this.put(e,t,n)}async setPeerId(e){let t=W(e);await this.dispatchWriteRequest({kind:`setPeerId`,source:`meta`,peerId:t})}async setPeerIdInternal(e){let t=W(e);await this.db.exec(`DELETE FROM ${this.tables.meta}`),await this.db.run(`INSERT INTO ${this.tables.meta}(peer_id) VALUES (?)`,[t]),this.peerIdValue=t}async get(e){let t=V(e),n=(await this.db.query(`SELECT data FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]))[0];if(n)return $(n.data)}async getEntry(e){let t;try{t=V(e)}catch{return}let n=(await this.db.query(`SELECT data, metadata, physical, logical, peer FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]))[0];if(!n)return;let r=Qr(n.physical,n.logical,n.peer);if(!r)return;let i=Pr(Xr(n.metadata)),a=$(n.data),o={metadata:i,clock:r};return a!==void 0&&(o.data=a),o}async getMvr(e){let t=await this.scan({prefix:e}),n=[];for(let r of t)r.raw.d===!0&&r.key.length===e.length+1&&n.push(r.key[r.key.length-1]);return n}async putMvr(e,t,n){if(t===null||typeof t==`object`)throw TypeError(`putMvr only accepts scalar values`);await this.dispatchWriteRequest({kind:`putMvr`,source:`local`,key:e,value:t,now:n})}async putMvrInternal(e,t,n,r){if(t===null||typeof t==`object`)throw TypeError(`putMvr only accepts scalar values`);let i=await this.scan({prefix:e});for(let e of i)e.raw.d===!0&&await this.applyOperation({key:e.key,payload:{},now:n,skipSameValue:!0,source:`local`,eventSink:r});let a=e.slice();a.push(t),await this.applyOperation({key:a,payload:{data:!0},now:n,skipSameValue:!0,source:`local`,eventSink:r})}buildScanBounds(e){let t,n,r,i=e=>{if(!t){t=e;return}let n=fr(e.value,t.value);n>0?t=e:n===0&&(t={value:t.value,inclusive:t.inclusive&&e.inclusive})},a=e=>{if(!n){n=e;return}let t=fr(e.value,n.value);t<0?n=e:t===0&&(n={value:n.value,inclusive:n.inclusive&&e.inclusive})};try{if(e.prefix){let t=V(e.prefix);r=t,i({value:t,inclusive:!0});let n=pr(t);n&&a({value:n,inclusive:!1})}e.start&&e.start.kind!==`unbounded`&&i({value:V(e.start.key),inclusive:e.start.kind===`inclusive`}),e.end&&e.end.kind!==`unbounded`&&a({value:V(e.end.key),inclusive:e.end.kind===`inclusive`})}catch{return{where:[],params:[],empty:!0}}let o=[],s=[];return t&&(o.push(`key ${t.inclusive?`>=`:`>`} ?`),s.push(t.value)),n&&(o.push(`key ${n.inclusive?`<=`:`<`} ?`),s.push(n.value)),{where:o,params:s,postFilter:r?(e=>t=>ni(t,e))(r):void 0}}async scan(e={}){let t=this.buildScanBounds(e);if(t.empty)return[];let n=t.where.length>0?`WHERE ${t.where.join(` AND `)}`:``,r=await this.db.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} ${n} ORDER BY key ASC`,t.params),i=[];for(let e of r){let n=e.key;if(t.postFilter&&!t.postFilter(n))continue;let r=dr(n),a={physicalTime:Number(e.physical??0),logicalCounter:Number(e.logical??0),peerId:String(e.peer??``)},o={},s=$(e.data);s!==void 0&&(o.data=s);let c=Xr(e.metadata);c!==void 0&&(o.metadata=c);let l=Q(a,o);i.push({key:r,raw:l,value:o.data})}return i}async version(){let e=await this.db.query(`SELECT peer, physical, logical FROM (
26
+ peer=excluded.peer`,[t,r,i,c.physicalTime,c.logicalCounter,c.peerId]),a=!0}),o&&this.bumpVersion(o),a&&o){let t={key:e.key.slice(),payload:n,source:e.source,clock:o};e.eventSink.push(t)}return a}emitEvents(e,t){if(this.listeners.size===0||t.length===0)return;let n={source:e,events:t.map(e=>({key:G(e.key),clock:{...e.clock},value:e.payload.data===void 0?void 0:G(e.payload.data),metadata:K(e.payload.metadata),payload:q(e.payload)}))},r=Array.from(this.listeners);for(let e of r)try{e(n)}catch(e){console.error(e)}}async put(e,t,n){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{data:G(t)},now:n,skipSameValue:!0})}async putWithMeta(e,t,n={}){let r={data:G(t)};n.metadata&&(r.metadata=K(n.metadata));let i=n.hooks?.transform;if(i){let t=q(r),a=J(r,await i({key:e.slice(),now:n.now},t)??t);if(a.data===void 0)throw TypeError(`putWithMeta requires a data value`);await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:a,now:n.now,skipSameValue:!0});return}await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:r,now:n.now,skipSameValue:!0})}async delete(e,t){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{},now:t,skipSameValue:!0})}async forcePut(e,t,n){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{data:G(t)},now:n,skipSameValue:!1})}async forcePutWithMeta(e,t,n={}){let r={data:G(t)};n.metadata&&(r.metadata=K(n.metadata));let i=n.hooks?.transform;if(i){let t=q(r),a=J(r,await i({key:e.slice(),now:n.now},t)??t);if(a.data===void 0)throw TypeError(`forcePutWithMeta requires a data value`);await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:a,now:n.now,skipSameValue:!1});return}await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:r,now:n.now,skipSameValue:!1})}async forceDelete(e,t){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{},now:t,skipSameValue:!1})}async set(e,t,n){await this.put(e,t,n)}async setPeerId(e){let t=W(e);await this.dispatchWriteRequest({kind:`setPeerId`,source:`meta`,peerId:t})}async setPeerIdInternal(e){let t=W(e);await this.db.exec(`DELETE FROM ${this.tables.meta}`),await this.db.run(`INSERT INTO ${this.tables.meta}(peer_id) VALUES (?)`,[t]),this.peerIdValue=t}async get(e){let t=V(e),n=(await this.db.query(`SELECT data FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]))[0];if(n)return $(n.data)}async getEntry(e){let t;try{t=V(e)}catch{return}let n=(await this.db.query(`SELECT data, metadata, physical, logical, peer FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]))[0];if(!n)return;let r=Qr(n.physical,n.logical,n.peer);if(!r)return;let i=Pr(Xr(n.metadata)),a=$(n.data),o={metadata:i,clock:r};return a!==void 0&&(o.data=a),o}async getMvr(e){let t=await this.scan({prefix:e}),n=[];for(let r of t)r.raw.d===!0&&r.key.length===e.length+1&&n.push(r.key[r.key.length-1]);return n}async putMvr(e,t,n){if(t===null||typeof t==`object`)throw TypeError(`putMvr only accepts scalar values`);await this.dispatchWriteRequest({kind:`putMvr`,source:`local`,key:e,value:t,now:n})}async putMvrInternal(e,t,n,r){if(t===null||typeof t==`object`)throw TypeError(`putMvr only accepts scalar values`);let i=await this.scan({prefix:e});for(let e of i)e.raw.d===!0&&await this.applyOperation({key:e.key,payload:{},now:n,skipSameValue:!0,source:`local`,eventSink:r});let a=e.slice();a.push(t),await this.applyOperation({key:a,payload:{data:!0},now:n,skipSameValue:!0,source:`local`,eventSink:r})}buildScanBounds(e){let t,n,r,i=e=>{if(!t){t=e;return}let n=fr(e.value,t.value);n>0?t=e:n===0&&(t={value:t.value,inclusive:t.inclusive&&e.inclusive})},a=e=>{if(!n){n=e;return}let t=fr(e.value,n.value);t<0?n=e:t===0&&(n={value:n.value,inclusive:n.inclusive&&e.inclusive})};try{if(e.prefix){let t=V(e.prefix);r=t,i({value:t,inclusive:!0});let n=pr(t);n&&a({value:n,inclusive:!1})}e.start&&e.start.kind!==`unbounded`&&i({value:V(e.start.key),inclusive:e.start.kind===`inclusive`}),e.end&&e.end.kind!==`unbounded`&&a({value:V(e.end.key),inclusive:e.end.kind===`inclusive`})}catch{return{where:[],params:[],empty:!0}}let o=[],s=[];return t&&(o.push(`key ${t.inclusive?`>=`:`>`} ?`),s.push(t.value)),n&&(o.push(`key ${n.inclusive?`<=`:`<`} ?`),s.push(n.value)),{where:o,params:s,postFilter:r?(e=>t=>ni(t,e))(r):void 0}}async scan(e={}){let t=this.buildScanBounds(e);if(t.empty)return[];let n=t.where.length>0?`WHERE ${t.where.join(` AND `)}`:``,r=await this.db.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} ${n} ORDER BY key ASC`,t.params),i=[];for(let e of r){let n=e.key;if(t.postFilter&&!t.postFilter(n))continue;let r=dr(n),a={physicalTime:Number(e.physical??0),logicalCounter:Number(e.logical??0),peerId:String(e.peer??``)},o={},s=$(e.data);s!==void 0&&(o.data=s);let c=Xr(e.metadata);c!==void 0&&(o.metadata=c);let l=Q(a,o);i.push({key:r,raw:l,value:o.data})}return i}async version(){let e=await this.db.query(`SELECT peer, physical, logical FROM (
27
27
  SELECT peer, physical, logical,
28
28
  ROW_NUMBER() OVER (PARTITION BY peer ORDER BY physical DESC, logical DESC) as rn
29
29
  FROM ${this.tables.kv}