@loro-dev/flock-sqlite 0.1.0

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.
@@ -0,0 +1,175 @@
1
+ import { UniStoreConnection } from "@loro-dev/unisqlite";
2
+
3
+ //#region src/types.d.ts
4
+ type Value = string | number | boolean | null | Array<Value> | {
5
+ [key: string]: Value;
6
+ };
7
+ type KeyPart = Value;
8
+ type MetadataMap = Record<string, unknown>;
9
+ type ExportRecord = {
10
+ c: string;
11
+ d?: Value;
12
+ m?: MetadataMap;
13
+ };
14
+ type ExportBundle = {
15
+ version: number;
16
+ entries: Record<string, ExportRecord>;
17
+ };
18
+ type EntryClock = {
19
+ physicalTime: number;
20
+ logicalCounter: number;
21
+ peerId: string;
22
+ };
23
+ type ExportPayload = {
24
+ data?: Value;
25
+ metadata?: MetadataMap;
26
+ };
27
+ type ExportHookContext = {
28
+ key: KeyPart[];
29
+ clock: EntryClock;
30
+ raw: ExportRecord;
31
+ };
32
+ type MaybePromise<T> = T | Promise<T>;
33
+ type ExportHooks = {
34
+ transform?: (context: ExportHookContext, payload: ExportPayload) => MaybePromise<ExportPayload | void>;
35
+ };
36
+ type ImportPayload = ExportPayload;
37
+ type ImportHookContext = ExportHookContext;
38
+ type ImportAccept = {
39
+ accept: true;
40
+ };
41
+ type ImportSkip = {
42
+ accept: false;
43
+ reason: string;
44
+ };
45
+ type ImportDecision = ImportAccept | ImportSkip | ImportPayload | void;
46
+ type ImportHooks = {
47
+ preprocess?: (context: ImportHookContext, payload: ImportPayload) => MaybePromise<ImportDecision>;
48
+ };
49
+ type ImportReport = {
50
+ accepted: number;
51
+ skipped: Array<{
52
+ key: KeyPart[];
53
+ reason: string;
54
+ }>;
55
+ };
56
+ type VersionVectorEntry = {
57
+ physicalTime: number;
58
+ logicalCounter: number;
59
+ };
60
+ type VersionVector = Record<string, VersionVectorEntry>;
61
+ type ScanBound = {
62
+ kind: "inclusive";
63
+ key: KeyPart[];
64
+ } | {
65
+ kind: "exclusive";
66
+ key: KeyPart[];
67
+ } | {
68
+ kind: "unbounded";
69
+ };
70
+ type ScanOptions = {
71
+ start?: ScanBound;
72
+ end?: ScanBound;
73
+ prefix?: KeyPart[];
74
+ };
75
+ type ScanRow = {
76
+ key: KeyPart[];
77
+ raw: ExportRecord;
78
+ value?: Value;
79
+ };
80
+ type EventPayload = ExportPayload;
81
+ type Event = {
82
+ key: KeyPart[];
83
+ value?: Value;
84
+ metadata?: MetadataMap;
85
+ payload: EventPayload;
86
+ };
87
+ type EventBatch = {
88
+ source: string;
89
+ events: Event[];
90
+ };
91
+ type ExportOptions = {
92
+ from?: VersionVector;
93
+ hooks?: ExportHooks;
94
+ pruneTombstonesBefore?: number;
95
+ peerId?: string;
96
+ };
97
+ type ImportOptions = {
98
+ bundle: ExportBundle;
99
+ hooks?: ImportHooks;
100
+ };
101
+ type PutPayload = ExportPayload;
102
+ type PutHookContext = {
103
+ key: KeyPart[];
104
+ now?: number;
105
+ };
106
+ type PutHooks = {
107
+ transform?: (context: PutHookContext, payload: PutPayload) => MaybePromise<PutPayload | void>;
108
+ };
109
+ type PutWithMetaOptions = {
110
+ metadata?: MetadataMap;
111
+ now?: number;
112
+ hooks?: PutHooks;
113
+ };
114
+ type EventListener = (batch: EventBatch) => void;
115
+ //#endregion
116
+ //#region src/index.d.ts
117
+ type FlockSQLiteOptions = {
118
+ path: string;
119
+ peerId?: string;
120
+ connection?: UniStoreConnection;
121
+ tablePrefix?: string;
122
+ };
123
+ declare class FlockSQLite {
124
+ private db;
125
+ private peerIdValue;
126
+ private vv;
127
+ private maxHlc;
128
+ private listeners;
129
+ private tables;
130
+ private constructor();
131
+ static open(options: FlockSQLiteOptions): Promise<FlockSQLite>;
132
+ static fromJson(options: FlockSQLiteOptions & {
133
+ bundle: ExportBundle;
134
+ }): Promise<FlockSQLite>;
135
+ close(): Promise<void>;
136
+ private static ensureSchema;
137
+ private static resolvePeerId;
138
+ private static loadVersionState;
139
+ private bumpVersion;
140
+ private allocateClock;
141
+ private applyOperation;
142
+ private emitEvents;
143
+ put(key: KeyPart[], value: Value, now?: number): Promise<void>;
144
+ putWithMeta(key: KeyPart[], value: Value, options?: PutWithMetaOptions): Promise<void>;
145
+ delete(key: KeyPart[], now?: number): Promise<void>;
146
+ set(key: KeyPart[], value: Value, now?: number): Promise<void>;
147
+ setPeerId(peerId: string): Promise<void>;
148
+ get(key: KeyPart[]): Promise<Value | undefined>;
149
+ getMvr(key: KeyPart[]): Promise<Value[]>;
150
+ putMvr(key: KeyPart[], value: Value, now?: number): Promise<void>;
151
+ private buildScanBounds;
152
+ scan(options?: ScanOptions): Promise<ScanRow[]>;
153
+ version(): VersionVector;
154
+ peerId(): string;
155
+ getMaxPhysicalTime(): number;
156
+ private exportInternal;
157
+ private exportWithHooks;
158
+ exportJson(): Promise<ExportBundle>;
159
+ exportJson(from: VersionVector): Promise<ExportBundle>;
160
+ exportJson(from: VersionVector, pruneTombstonesBefore: number): Promise<ExportBundle>;
161
+ exportJson(options: ExportOptions): Promise<ExportBundle>;
162
+ private importInternal;
163
+ importJson(bundle: ExportBundle): Promise<ImportReport>;
164
+ importJson(options: ImportOptions): Promise<ImportReport>;
165
+ importJsonStr(json: string): Promise<ImportReport>;
166
+ digest(): Promise<string>;
167
+ kvToJson(): Promise<ExportBundle>;
168
+ merge(other: FlockSQLite): Promise<void>;
169
+ static checkConsistency(a: FlockSQLite, b: FlockSQLite): Promise<boolean>;
170
+ checkInvariants(): void;
171
+ subscribe(listener: (batch: EventBatch) => void): () => void;
172
+ }
173
+ //#endregion
174
+ export { type Event, type EventBatch, type EventListener, type ExportBundle, type ExportHooks, type ExportOptions, type ExportPayload, type ExportRecord, FlockSQLite as Flock, FlockSQLite, FlockSQLiteOptions, type ImportHooks, type ImportOptions, type ImportReport, type KeyPart, type MetadataMap, type PutHooks, type PutWithMetaOptions, type ScanBound, type ScanOptions, type ScanRow, type Value, type VersionVector, type VersionVectorEntry };
175
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1,175 @@
1
+ import { UniStoreConnection } from "@loro-dev/unisqlite";
2
+
3
+ //#region src/types.d.ts
4
+ type Value = string | number | boolean | null | Array<Value> | {
5
+ [key: string]: Value;
6
+ };
7
+ type KeyPart = Value;
8
+ type MetadataMap = Record<string, unknown>;
9
+ type ExportRecord = {
10
+ c: string;
11
+ d?: Value;
12
+ m?: MetadataMap;
13
+ };
14
+ type ExportBundle = {
15
+ version: number;
16
+ entries: Record<string, ExportRecord>;
17
+ };
18
+ type EntryClock = {
19
+ physicalTime: number;
20
+ logicalCounter: number;
21
+ peerId: string;
22
+ };
23
+ type ExportPayload = {
24
+ data?: Value;
25
+ metadata?: MetadataMap;
26
+ };
27
+ type ExportHookContext = {
28
+ key: KeyPart[];
29
+ clock: EntryClock;
30
+ raw: ExportRecord;
31
+ };
32
+ type MaybePromise<T> = T | Promise<T>;
33
+ type ExportHooks = {
34
+ transform?: (context: ExportHookContext, payload: ExportPayload) => MaybePromise<ExportPayload | void>;
35
+ };
36
+ type ImportPayload = ExportPayload;
37
+ type ImportHookContext = ExportHookContext;
38
+ type ImportAccept = {
39
+ accept: true;
40
+ };
41
+ type ImportSkip = {
42
+ accept: false;
43
+ reason: string;
44
+ };
45
+ type ImportDecision = ImportAccept | ImportSkip | ImportPayload | void;
46
+ type ImportHooks = {
47
+ preprocess?: (context: ImportHookContext, payload: ImportPayload) => MaybePromise<ImportDecision>;
48
+ };
49
+ type ImportReport = {
50
+ accepted: number;
51
+ skipped: Array<{
52
+ key: KeyPart[];
53
+ reason: string;
54
+ }>;
55
+ };
56
+ type VersionVectorEntry = {
57
+ physicalTime: number;
58
+ logicalCounter: number;
59
+ };
60
+ type VersionVector = Record<string, VersionVectorEntry>;
61
+ type ScanBound = {
62
+ kind: "inclusive";
63
+ key: KeyPart[];
64
+ } | {
65
+ kind: "exclusive";
66
+ key: KeyPart[];
67
+ } | {
68
+ kind: "unbounded";
69
+ };
70
+ type ScanOptions = {
71
+ start?: ScanBound;
72
+ end?: ScanBound;
73
+ prefix?: KeyPart[];
74
+ };
75
+ type ScanRow = {
76
+ key: KeyPart[];
77
+ raw: ExportRecord;
78
+ value?: Value;
79
+ };
80
+ type EventPayload = ExportPayload;
81
+ type Event = {
82
+ key: KeyPart[];
83
+ value?: Value;
84
+ metadata?: MetadataMap;
85
+ payload: EventPayload;
86
+ };
87
+ type EventBatch = {
88
+ source: string;
89
+ events: Event[];
90
+ };
91
+ type ExportOptions = {
92
+ from?: VersionVector;
93
+ hooks?: ExportHooks;
94
+ pruneTombstonesBefore?: number;
95
+ peerId?: string;
96
+ };
97
+ type ImportOptions = {
98
+ bundle: ExportBundle;
99
+ hooks?: ImportHooks;
100
+ };
101
+ type PutPayload = ExportPayload;
102
+ type PutHookContext = {
103
+ key: KeyPart[];
104
+ now?: number;
105
+ };
106
+ type PutHooks = {
107
+ transform?: (context: PutHookContext, payload: PutPayload) => MaybePromise<PutPayload | void>;
108
+ };
109
+ type PutWithMetaOptions = {
110
+ metadata?: MetadataMap;
111
+ now?: number;
112
+ hooks?: PutHooks;
113
+ };
114
+ type EventListener = (batch: EventBatch) => void;
115
+ //#endregion
116
+ //#region src/index.d.ts
117
+ type FlockSQLiteOptions = {
118
+ path: string;
119
+ peerId?: string;
120
+ connection?: UniStoreConnection;
121
+ tablePrefix?: string;
122
+ };
123
+ declare class FlockSQLite {
124
+ private db;
125
+ private peerIdValue;
126
+ private vv;
127
+ private maxHlc;
128
+ private listeners;
129
+ private tables;
130
+ private constructor();
131
+ static open(options: FlockSQLiteOptions): Promise<FlockSQLite>;
132
+ static fromJson(options: FlockSQLiteOptions & {
133
+ bundle: ExportBundle;
134
+ }): Promise<FlockSQLite>;
135
+ close(): Promise<void>;
136
+ private static ensureSchema;
137
+ private static resolvePeerId;
138
+ private static loadVersionState;
139
+ private bumpVersion;
140
+ private allocateClock;
141
+ private applyOperation;
142
+ private emitEvents;
143
+ put(key: KeyPart[], value: Value, now?: number): Promise<void>;
144
+ putWithMeta(key: KeyPart[], value: Value, options?: PutWithMetaOptions): Promise<void>;
145
+ delete(key: KeyPart[], now?: number): Promise<void>;
146
+ set(key: KeyPart[], value: Value, now?: number): Promise<void>;
147
+ setPeerId(peerId: string): Promise<void>;
148
+ get(key: KeyPart[]): Promise<Value | undefined>;
149
+ getMvr(key: KeyPart[]): Promise<Value[]>;
150
+ putMvr(key: KeyPart[], value: Value, now?: number): Promise<void>;
151
+ private buildScanBounds;
152
+ scan(options?: ScanOptions): Promise<ScanRow[]>;
153
+ version(): VersionVector;
154
+ peerId(): string;
155
+ getMaxPhysicalTime(): number;
156
+ private exportInternal;
157
+ private exportWithHooks;
158
+ exportJson(): Promise<ExportBundle>;
159
+ exportJson(from: VersionVector): Promise<ExportBundle>;
160
+ exportJson(from: VersionVector, pruneTombstonesBefore: number): Promise<ExportBundle>;
161
+ exportJson(options: ExportOptions): Promise<ExportBundle>;
162
+ private importInternal;
163
+ importJson(bundle: ExportBundle): Promise<ImportReport>;
164
+ importJson(options: ImportOptions): Promise<ImportReport>;
165
+ importJsonStr(json: string): Promise<ImportReport>;
166
+ digest(): Promise<string>;
167
+ kvToJson(): Promise<ExportBundle>;
168
+ merge(other: FlockSQLite): Promise<void>;
169
+ static checkConsistency(a: FlockSQLite, b: FlockSQLite): Promise<boolean>;
170
+ checkInvariants(): void;
171
+ subscribe(listener: (batch: EventBatch) => void): () => void;
172
+ }
173
+ //#endregion
174
+ export { type Event, type EventBatch, type EventListener, type ExportBundle, type ExportHooks, type ExportOptions, type ExportPayload, type ExportRecord, FlockSQLite as Flock, FlockSQLite, FlockSQLiteOptions, type ImportHooks, type ImportOptions, type ImportReport, type KeyPart, type MetadataMap, type PutHooks, type PutWithMetaOptions, type ScanBound, type ScanOptions, type ScanRow, type Value, type VersionVector, type VersionVectorEntry };
175
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,27 @@
1
+ import{openStore as e}from"@loro-dev/unisqlite";const t=new TextEncoder;function n(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function r(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 i(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 a(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 o=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(r(e))}writeI64(e){this.writeRawBytes(i(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(t.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(t.encode(e.clock.peerId))}async finish(){return a(new Uint8Array(this.chunks))}};function s(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch{return}}function c(e){if(e!=null)return JSON.parse(e)}async function l(e){let t=c(e.data);if(t===void 0)return null;let n=s(e.metadata),r=new o;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 u(e){let t=new Uint8Array(32);for(let n of e){let e=await l(n);if(e)for(let n=0;n<t.length;n+=1)t[n]^=e[n]}return n(t)}const ee={hi:2146959360,lo:1};var te=class extends Error{};function d(){throw new te}const ne=(e,t)=>e<t?-1:e>t?1:0,re=(e,t)=>e===t,f=e=>BigInt(e.hi)*4294967296n+BigInt(e.lo>>>0),ie=e=>-e,ae=(e,t)=>e+t,oe=(e,t)=>e*t,se=(e,t)=>e/t,ce=(e,t)=>e%t,le=(e,t)=>e>>BigInt(t),ue=e=>Number(BigInt.asUintN(32,e))|0,de=e=>Number(BigInt.asIntN(32,e));function p(e,t){if(t<0||t>=e.length)throw Error(`Index out of bounds`)}const fe=(e,t)=>e.toString(t);function m(e,t){let n=new Uint8Array(e);return t!==0&&n.fill(t),n}const h=(e,t)=>{e.push(t)},pe={$tag:0};function me(e){this._0=e}me.prototype.$tag=1;function he(e){this._0=e}he.prototype.$tag=2;function ge(e){this._0=e}ge.prototype.$tag=3;function _e(e){this._0=e}_e.prototype.$tag=4;const ve=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)},ye=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)}},be=e=>e.hi*4294967296+(e.lo>>>0),xe=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}},Se=new Uint8Array,g={hi:0,lo:255},_={hi:0,lo:0},Ce={hi:-1,lo:-1},we={hi:-2147483648,lo:0};function Te(e){this._0=e}Te.prototype.$tag=0;function Ee(e){this._0=e}Ee.prototype.$tag=1;function v(e){this._0=e}v.prototype.$tag=2;const y={$tag:1},De={$tag:0},Oe={hi:0,lo:1},ke={hi:0,lo:256};function b(e){this._0=e}b.prototype.$tag=0;function x(e){this._0=e}x.prototype.$tag=1;function Ae(e){this._0=e}Ae.prototype.$tag=0;function je(e){this._0=e}je.prototype.$tag=1;function S(e){this._0=e}S.prototype.$tag=0;function C(e){this._0=e}C.prototype.$tag=1;function w(e){this._0=e}w.prototype.$tag=2;function T(e){this._0=e}T.prototype.$tag=3;const Me={$tag:4},Ne={$tag:5};function Pe(e){this._0=e}Pe.prototype.$tag=0;function Fe(e){this._0=e}Fe.prototype.$tag=1;function Ie(e){this._0=e}Ie.prototype.$tag=0;function Le(e){this._0=e}Le.prototype.$tag=1;function Re(e){this._0=e}Re.prototype.$tag=2;const ze={$tag:3},Be={$tag:4},Ve=jt(ee);function He(e){return d()}function Ue(e){return d()}function We(e){return d()}function E(e){d()}function Ge(e){return d()}function Ke(e){return At(e)}function qe(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=M(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=M(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=lt(s);if(P(u,o.str,o.start,o.end-o.start|0),mt(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=M(e);P(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=M(e);P(u,t.str,t.start,t.end-t.start|0),P(u,o.str,o.start,o.end-o.start|0),n=a+1|0;continue}else break}}return u.val}else return``}function Je(e,t){t(t=>(bt(e,t),1))}function Ye(e,t){return qe({buf:e,start:0,end:e.length},t)}function Xe(e,t){return ne(e,t)}function Ze(e,t){return re(e,t)}function Qe(e){return ie(e)}function $e(e,t){return ae(e,t)}function et(e,t){return oe(e,t)}function tt(e,t){return se(e,t)}function nt(e,t){return ce(e,t)}function rt(e,t){return t<0&&E(`negative shift count`),le(e,t)}function it(e){let t=ue(rt(e,32)),n=ue(e);return Bt(Vt(Ke(t),32),Ke(n))}function D(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 We(`index out of bounds: the len is from 0 to ${N(e.end-e.start|0)} but the index is ${N(t)}`)}function O(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}:Ue(`Invalid index for View`)}function k(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}:Ue(`Invalid index for View`)}function at(e){return t=>{let n=e.end-e.start|0,r=0;for(;;){let i=r;if(i<n){if(t(D(e,i))!==1)return 0;r=i+1|0;continue}else return 1}}}function ot(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 A(e){return Jt(e.end-e.start|0,t=>Zt(e,t))}function st(e){let t=Ct(e);return A({buf:t,start:0,end:t.length})}function j(e){return At(e)}function M(e){return{str:e,start:0,end:e.length}}function ct(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 lt(e){return{val:``}}function ut(e,t){let n=e;n.val=`${n.val}${String.fromCodePoint(t)}`}function dt(e,t){let n=e;n.val=`${n.val}${t}`}function ft(e,t){return Xe(e,t)>0}function N(e){let t=lt(0);return Tt(e,{self:t,method_0:dt,method_1:P,method_2:ut}),t.val}function pt(e,t){return fe(e,t)}function mt(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 E(`invalid surrogate pair`)}a=n+1|0,o=r+1|0;continue}else return r===t&&n===i}}function ht(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 P(e,t,n,r){let i=e;i.val=`${i.val}${ht(t,n,n+r|0)}`}function gt(e){return[]}function _t(e){return[]}function F(e){return[]}function vt(e,t){h(e,t)}function yt(e,t){h(e,t)}function I(e,t){h(e,t)}function L(e,t){h(e,t)}function bt(e,t){h(e,t)}function xt(e){return String.fromCodePoint(e)}function St(e,t){let n={val:pe};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 Ct(e){let t=[];return St(e,e=>{I(t,e)}),t}function wt(e){return e()}function Tt(e,t){t.method_0(t.self,pt(e,10))}function Et(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 Dt(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}:Ge(`View index out of bounds`)}function Ot(e){return{hi:0,lo:e}}function kt(e){return Ot(e)}function At(e){return kt(e)}function jt(e){return ve(e)}function Mt(e){return{hi:e>>31&-1,lo:e|0}}function Nt(e){return Mt(e)}function Pt(e){return e.lo}function R(e){return Pt(e)&255}function Ft(e,t){return{hi:e.hi&t.hi,lo:e.lo&t.lo}}function It(e,t){return{hi:e.hi|t.hi,lo:e.lo|t.lo}}function Lt(e,t){return{hi:e.hi^t.hi,lo:e.lo^t.lo}}function Rt(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 zt(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 Bt(e,t){return It(e,t)}function Vt(e,t){return Rt(e,t)}function Ht(e){return be(e)}function Ut(e){return Ht(e)}function Wt(e){return ve(e)}function Gt(e){return ye(e)}function Kt(e,t){let n=e,r=t;return n.hi===r.hi&&n.lo===r.lo}function z(e,t){return Ft(e,t)}function B(e,t){return It(e,t)}function V(e,t){return Lt(e,t)}function H(e,t){return Rt(e,t)}function U(e,t){return zt(e,t)}function qt(e){return xe(e)}function Jt(e,t){if(e<=0)return Se;let n=m(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 Yt(e){console.log(e)}function Xt(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){ct(e,t,n,r,i);return}else{d();return}}function Zt(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 We(`index out of bounds: the len is from 0 to ${N(e.end-e.start|0)} but the index is ${N(t)}`)}function Qt(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 $t(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=m(r,0);ct(t,0,e.data,0,e.len),e.data=t;return}else return}function W(e,t){$t(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 G(e){return A(Dt(e.data,0,e.len))}function K(e){return{data:m(e<1?1:e,0),len:0}}function en(e,t){let n=t.length;$t(e,e.len+n|0),Xt(e.data,e.len,t,0,n),e.len=e.len+n|0}function tn(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 nn(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 rn(e){let t=[],n=e.color;n===void 0||L(t,nn(n));let r=e.bg_color;r===void 0||L(t,tn(r));let i=e.formats,a=i.length,o=0;for(;;){let e=o;if(e<a){switch(i[e]){case 0:L(t,`1`);break;case 1:L(t,`4`);break;case 2:L(t,`5`);break;case 3:L(t,`7`);break;case 4:L(t,`8`);break;case 5:L(t,`9`);break;default:L(t,`3`)}o=e+1|0;continue}else break}return t.length>0?`[${Ye(t,{str:`;`,start:0,end:1})}m${e.str}[0m`:e.str}function an(e){return{str:e,bg_color:void 0,color:void 0,formats:[]}}function on(e){return{str:e.str,bg_color:e.bg_color,color:1,formats:e.formats}}function sn(e){return{str:e.str,bg_color:e.bg_color,color:3,formats:e.formats}}function cn(e){return{str:e.str,bg_color:e.bg_color,color:4,formats:e.formats}}function ln(e){let t=e.str,n=e.bg_color,r=e.color,i=[];return bt(i,0),Je(i,Et(e.formats)),{str:t,bg_color:n,color:r,formats:i}}function un(e,t){let n=`${rn(on(ln(an(`Panic: `))))}${rn(sn(an(e)))} at ${rn(cn(an(t)))}`;Yt(n),E(n)}function dn(e){let t=F(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;I(t,(240|e>>18)&255),I(t,(128|e>>12&63)&255),I(t,(128|e>>6&63)&255),I(t,(128|e&63)&255),n=n+1|0}else I(t,(224|i>>12)&255),I(t,(128|i>>6&63)&255),I(t,(128|i&63)&255)}else i<128?I(t,i&255):i<2048?(I(t,(192|i>>6)&255),I(t,(128|i&63)&255)):(I(t,(224|i>>12)&255),I(t,(128|i>>6&63)&255),I(t,(128|i&63)&255));n=n+1|0}return A({buf:t,start:0,end:t.length})}function fn(e){return{bytes:dn(e)}}function pn(e){let t=0;for(;t<(e.end-e.start|0);){let n=D(e,t);if(!(n&128))t=t+1|0;else if((n&224)==192){if((t+1|0)>=(e.end-e.start|0)||(D(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=D(e,t+1|0),r=D(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=D(e,t+1|0),r=D(e,t+2|0),i=D(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 mn(e){if(pn(k(e,0,void 0)))return{bytes:st(at(e))}}function hn(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}${xt(a)}`,t=t+1|0}return n}function gn(e){let t=hn(e.bytes);return t===void 0?d():t}function _n(e){return Gt(e)}function vn(e){return Wt(e)}function yn(e){let t=F(0);return I(t,R(z(U(e,56),g))),I(t,R(z(U(e,48),g))),I(t,R(z(U(e,40),g))),I(t,R(z(U(e,32),g))),I(t,R(z(U(e,24),g))),I(t,R(z(U(e,16),g))),I(t,R(z(U(e,8),g))),I(t,R(z(e,g))),A({buf:t,start:0,end:t.length})}function bn(e){e.length!==8&&un(`Invalid byte array length`,`/Users/zxch3n/Code/flock/moon/memcomparable/utils.mbt:28:5-28:54`);let t=_,n=t;p(e,0),t=B(n,H(j(e[0]),56));let r=t;p(e,1),t=B(r,H(j(e[1]),48));let i=t;p(e,2),t=B(i,H(j(e[2]),40));let a=t;p(e,3),t=B(a,H(j(e[3]),32));let o=t;p(e,4),t=B(o,H(j(e[4]),24));let s=t;p(e,5),t=B(s,H(j(e[5]),16));let c=t;p(e,6),t=B(c,H(j(e[6]),8));let l=t;return p(e,7),t=B(l,j(e[7])),t}function xn(){return{parts:_t(0)}}function q(e,t){vt(e.parts,t)}function Sn(e){return e===e?e:e<0?-Ve:Ve}function Cn(e,t){W(t,1);let n=ot(e);for(;;){let e=wt(n);if(e===-1)break;{let n=e;W(t,n),n===0&&W(t,255);continue}}W(t,0)}function wn(e,t){W(t,2);let n=e.bytes,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];W(t,r),r===0&&W(t,255),i=e+1|0;continue}else break}W(t,0)}function Tn(e,t){W(t,33);let n=Sn(e),r=yn(n<0?V(_n(n),Ce):V(_n(n),we)),i=r.length,a=0;for(;;){let e=a;if(e<i){let n=r[e];W(t,n),a=e+1|0;continue}else return}}function En(e){let t=[],n=e;for(;ft(n,0n);)I(t,de(nt(n,256n))&255),n=tt(n,256n);let r=Qt(t);return A({buf:r,start:0,end:r.length})}function Dn(e,t){if(Ze(e,0n)){W(t,20);return}let n=ft(e,0n),r=En(n?e:Qe(e)),i=r.length;if(n===!1){i<=8?W(t,(20-(i&255)|0)&255):(W(t,11),i>255&&E(`n is too large`),W(t,(i&255^255)&255));let e=K(0),n=0;for(;;){let t=n;if(t<r.length){p(r,t);let i=r[t];W(e,(i^255)&255),n=t+1|0;continue}else break}en(t,G(e));return}else{i<=8?W(t,(20+(i&255)|0)&255):(W(t,29),i>255&&E(`n is too large`),W(t,i&255)),en(t,r);return}}function On(e,t){switch(e.$tag){case 0:{let n=e._0;Cn(O(n,0,n.length),t);return}case 1:{let n=e._0;wn(n,t);return}case 2:{let n=e._0;Dn(n,t);return}case 3:{let n=e._0;Tn(n,t);return}case 4:W(t,38);return;default:W(t,39);return}}function kn(e){let t=K(0),n=e.parts,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];On(r,t),i=e+1|0;continue}else break}return G(t)}function An(e,t){let n=K(0),r=t;for(;r<(e.end-e.start|0);){let t=D(e,r);if(r=r+1|0,t===0){let t;if(t=r<(e.end-e.start|0)?D(e,r)===255:!1,t){W(n,0),r=r+1|0;continue}else{let e=G(n);return new Ee({_0:O(e,0,e.length),_1:r})}}W(n,t)}return new Te(y)}function J(e){let t=f(_),n=f(Oe),r=(e.end-e.start|0)-1|0;for(;;){let i=r;if(i>=0){let a=f(Nt(D(e,i)));t=$e(t,et(n,a)),n=et(n,f(ke)),r=i-1|0;continue}else break}return t}function jn(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 b(y);let r=k(e,0,n);return new x({_0:k(e,n,void 0),_1:J(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 b(y);let r=k(e,0,n),i=k(e,n,void 0),a=K(0),o=0;for(;;){let e=o;if(e<(r.end-r.start|0)){W(a,(D(r,e)^255)&255),o=e+1|0;continue}else break}let s=G(a);return new x({_0:i,_1:Qe(J(O(s,0,s.length)))})}else if(t===11){if((e.end-e.start|0)<1)return new b(y);let t=(D(e,0)^255)&255;if((e.end-e.start|0)<(t+1|0))return new b(y);let n=k(e,1,t+1|0),r=k(e,t+1|0,void 0),i=K(0),a=0;for(;;){let e=a;if(e<(n.end-n.start|0)){W(i,(D(n,e)^255)&255),a=e+1|0;continue}else break}let o=G(i);return new x({_0:r,_1:Qe(J(O(o,0,o.length)))})}else if(t===29){if((e.end-e.start|0)<1)return new b(y);let t=D(e,0);if((e.end-e.start|0)<(t+1|0))return new b(y);let n=k(e,1,t+1|0);return new x({_0:k(e,t+1|0,void 0),_1:J(n)})}else return new b(new v(t))}}function Mn(e,t){if((t+8|0)>(e.end-e.start|0))return new Ae(y);let n=F(0),r=0;for(;;){let i=r;if(i<8){I(n,D(e,t+i|0)),r=i+1|0;continue}else break}let i=bn(A({buf:n,start:0,end:n.length}));return new je({_0:Kt(z(i,we),_)?vn(V(i,Ce)):vn(V(i,we)),_1:t+8|0})}function Nn(e){let t=xn(),n=0;for(;n<(e.end-e.start|0);){let r=D(e,n);if(n=n+1|0,r===2){let r=An(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1,s=mn(a);if(s===void 0)return new Pe(De);q(t,new C(s)),n=o}else if(r===1){let r=An(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;q(t,new S(st(at(a)))),n=o}else if(r>=11&&r<=29){let i=jn(k(e,n,void 0),r),a;if(i.$tag===1)a=i._0;else return i;let o=a._0,s=a._1;q(t,new w(s)),n=(e.end-e.start|0)-(o.end-o.start|0)|0}else if(r===33){let r=Mn(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;q(t,new T(a)),n=o}else if(r===38)q(t,Me);else if(r===39)q(t,Ne);else return new Pe(new v(r))}return new Fe(t)}function Pn(e){switch(e.$tag){case 0:{let t=e._0;return new Re(t)}case 1:{let t=e._0;return new Le(gn(t))}case 2:{let t=e._0;return new Ie(Ut(it(t)))}case 3:{let t=e._0;return new Ie(t)}case 4:return Be;default:return ze}}function Fn(e){switch(e.$tag){case 2:{let t=e._0;return new S(t)}case 1:{let t=e._0;return new C(fn(t))}case 0:{let t=e._0;return Ut(qt(t))===t?new w(f(qt(t))):new T(t)}case 3:return Ne;default:return Me}}function In(e){let t=xn(),n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];vt(t.parts,Fn(n)),r=i+1|0;continue}else break}return kn(t)}function Ln(e){let t;_L:{_L$2:{let n=Nn(O(e,0,e.length));if(n.$tag===1)t=n._0;else{n._0;break _L$2}break _L}t=He(`Failed to decode key`)}let n=gt(0),r=t.parts,i=r.length,a=0;for(;;){let e=a;if(e<i){let t=r[e];yt(n,Pn(t)),a=e+1|0;continue}else break}return n}function Rn(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 zn(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 Bn(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 zn(e._0);default:throw TypeError(`Unsupported memcomparable key part`)}}function Y(e){return In(e.map(Rn))}function Vn(e){return Ln(e).map(e=>Bn(e))}function Hn(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 Un(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 Wn(e){return JSON.stringify(e)}const Gn=new TextEncoder,Kn=globalThis.structuredClone;function qn(e){return Gn.encode(e).length}function Jn(e){return typeof e==`string`&&qn(e)<128}function Yn(){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 Xn(e){if(e===void 0)return Yn();if(!Jn(e))throw TypeError(`peerId must be a UTF-8 string under 128 bytes`);return e}function X(e){return e===void 0?e:Kn?Kn(e):JSON.parse(JSON.stringify(e))}function Z(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return X(e)}function Zn(e,t){if(!(!t||typeof t!=`object`)){if(`data`in t){let n=t.data;e.data=n===void 0?void 0:X(n)}`metadata`in t&&(e.metadata=Z(t.metadata))}}function Q(e){let t={};return Zn(t,e),t}function Qn(e,t){let n=Q(e);return Zn(n,t),n}function $(e,t){let n={c:ar(e)};t.data!==void 0&&(n.d=X(t.data));let r=Z(t.metadata);return r!==void 0&&(n.m=r),n}function $n(e){return!e||typeof e!=`object`?{accept:!0}:`accept`in e?e.accept?{accept:!0}:{accept:!1,reason:e.reason??`rejected`}:{accept:!0}}function er(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 tr(e){return typeof e==`object`&&!!e&&Object.prototype.hasOwnProperty.call(e,`bundle`)}function nr(e){if(e)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function rr(e){if(e!=null)return JSON.parse(e)}function ir(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:Jn(i)?i:``}}function ar(e){return`${e.physicalTime},${e.logicalCounter},${e.peerId}`}function or(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 sr(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 cr(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 lr(e){return e.map(e=>({key:e.key,data:e.data,metadata:e.metadata,physical:e.physical,logical:e.logical,peer:e.peer}))}function ur(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 dr(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`}}var fr=class t{db;peerIdValue;vv;maxHlc;listeners;tables;constructor(e,t,n,r,i){this.db=e,this.peerIdValue=t,this.vv=n,this.maxHlc=r,this.listeners=new Set,this.tables=i}static async open(n){let r=n.connection??await e({path:n.path}),i=dr(ur(n.tablePrefix));await t.ensureSchema(r,i);let a=await t.resolvePeerId(r,i,n.peerId),{vv:o,maxHlc:s}=await t.loadVersionState(r,i);return new t(r,a,o,s,i)}static async fromJson(e){let n=await t.open(e);return await n.importJson(e.bundle),n}async close(){await this.db.close()}static async ensureSchema(e,t){await e.exec(`
2
+ CREATE TABLE IF NOT EXISTS ${t.kv} (
3
+ key BLOB PRIMARY KEY,
4
+ data TEXT NULL,
5
+ metadata TEXT NULL,
6
+ physical REAL NOT NULL,
7
+ logical INTEGER NOT NULL,
8
+ peer TEXT NOT NULL
9
+ )`),await e.exec(`
10
+ CREATE TABLE IF NOT EXISTS ${t.overridden} (
11
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
12
+ key BLOB,
13
+ data TEXT NULL,
14
+ metadata TEXT NULL,
15
+ physical REAL NOT NULL,
16
+ logical INTEGER NOT NULL,
17
+ peer TEXT NOT NULL,
18
+ superseded_at INTEGER DEFAULT (unixepoch())
19
+ )`),await e.exec(`CREATE TABLE IF NOT EXISTS ${t.meta} (peer_id TEXT)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxKvPeerClock} ON ${t.kv}(peer, physical, logical, key)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxOverriddenKey} ON ${t.overridden}(key)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxOverriddenSupersededAt} ON ${t.overridden}(superseded_at)`)}static async resolvePeerId(e,t,n){let r=Xn(n),i=await e.query(`SELECT peer_id FROM ${t.meta} LIMIT 1`);if(i.length>0&&typeof i[0]?.peer_id==`string`){let a=i[0].peer_id;return n&&a!==r?(await e.run(`UPDATE ${t.meta} SET peer_id = ?`,[r]),r):Xn(a)}return await e.exec(`DELETE FROM ${t.meta}`),await e.run(`INSERT INTO ${t.meta}(peer_id) VALUES (?)`,[r]),r}static async loadVersionState(e,t){let n=new Map,r=await e.query(`SELECT peer, MAX(physical) AS physical, MAX(logical) AS logical FROM ${t.kv} GROUP BY peer`);for(let e of r){if(!e||typeof e.peer!=`string`)continue;let t=sr({physicalTime:Number(e.physical??0),logicalCounter:Number(e.logical??0)});t&&n.set(e.peer,t)}let i=(await e.query(`SELECT physical, logical FROM ${t.kv} ORDER BY physical DESC, logical DESC LIMIT 1`))[0];return{vv:n,maxHlc:i&&Number.isFinite(i.physical)&&Number.isFinite(i.logical)?{physicalTime:Number(i.physical),logicalCounter:Number(i.logical)}:{physicalTime:0,logicalCounter:0}}}bumpVersion(e){let t=this.vv.get(e.peerId);(!t||or(e,{...t,peerId:e.peerId})>0)&&this.vv.set(e.peerId,{physicalTime:e.physicalTime,logicalCounter:e.logicalCounter}),(this.maxHlc.physicalTime<e.physicalTime||this.maxHlc.physicalTime===e.physicalTime&&this.maxHlc.logicalCounter<e.logicalCounter)&&(this.maxHlc={physicalTime:e.physicalTime,logicalCounter:e.logicalCounter})}allocateClock(e){let t=e??Date.now(),n=this.maxHlc.physicalTime,r=this.maxHlc.logicalCounter;return t>n?(n=t,r=0):r+=1,{physicalTime:n,logicalCounter:r,peerId:this.peerIdValue}}async applyOperation(e){let t=Y(e.key),n=e.clock??this.allocateClock(e.now),r=Qn(e.payload,{}),i=r.data===void 0?null:JSON.stringify(r.data),a=r.metadata===void 0?null:JSON.stringify(r.metadata),o=!1;if(await this.db.asyncTransaction(async r=>{let s=await r.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]);if(s.length>0){let o=s[0],c=or(n,{physicalTime:Number(o.physical??0),logicalCounter:Number(o.logical??0),peerId:String(o.peer??``)}),l=o.data??null,u=o.metadata??null;if(e.skipSameValue&&i===l&&a===u)return;if(c<0){await r.run(`INSERT INTO ${this.tables.overridden}(key, data, metadata, physical, logical, peer) VALUES (?, ?, ?, ?, ?, ?)`,[t,i,a,n.physicalTime,n.logicalCounter,n.peerId]);return}if(c>0)await r.run(`INSERT INTO ${this.tables.overridden}(key, data, metadata, physical, logical, peer) VALUES (?, ?, ?, ?, ?, ?)`,[t,o.data??null,o.metadata??null,o.physical??0,o.logical??0,o.peer??``]);else return}await r.run(`INSERT INTO ${this.tables.kv}(key, data, metadata, physical, logical, peer)
20
+ VALUES (?, ?, ?, ?, ?, ?)
21
+ ON CONFLICT(key) DO UPDATE SET
22
+ data=excluded.data,
23
+ metadata=excluded.metadata,
24
+ physical=excluded.physical,
25
+ logical=excluded.logical,
26
+ peer=excluded.peer`,[t,i,a,n.physicalTime,n.logicalCounter,n.peerId]),o=!0}),this.bumpVersion(n),o){let t={key:e.key.slice(),payload:r,source:e.source};e.eventSink?e.eventSink.push(t):this.emitEvents(e.source,[t])}return o}emitEvents(e,t){if(this.listeners.size===0||t.length===0)return;let n={source:e,events:t.map(e=>({key:X(e.key),value:e.payload.data===void 0?void 0:X(e.payload.data),metadata:Z(e.payload.metadata),payload:Q(e.payload)}))};this.listeners.forEach(e=>{e(n)})}async put(e,t,n){await this.applyOperation({key:e,payload:{data:X(t)},now:n,skipSameValue:!0,source:`local`})}async putWithMeta(e,t,n={}){let r={data:X(t)};n.metadata&&(r.metadata=Z(n.metadata));let i=n.hooks?.transform;if(i){let t=Q(r),a=Qn(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.applyOperation({key:e,payload:a,now:n.now,skipSameValue:!0,source:`local`});return}await this.applyOperation({key:e,payload:r,now:n.now,skipSameValue:!0,source:`local`})}async delete(e,t){await this.applyOperation({key:e,payload:{},now:t,skipSameValue:!0,source:`local`})}async set(e,t,n){await this.put(e,t,n)}async setPeerId(e){let t=Xn(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=Y(e),n=(await this.db.query(`SELECT data FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]))[0];if(n)return rr(n.data)}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`);let r=await this.scan({prefix:e});for(let e of r)e.raw.d===!0&&await this.delete(e.key,n);let i=e.slice();i.push(t),await this.put(i,!0,n)}buildScanBounds(e){let t,n,r,i=e=>{if(!t){t=e;return}let n=Hn(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=Hn(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=Y(e.prefix);r=t,i({value:t,inclusive:!0});let n=Un(t);n&&a({value:n,inclusive:!1})}e.start&&e.start.kind!==`unbounded`&&i({value:Y(e.start.key),inclusive:e.start.kind===`inclusive`}),e.end&&e.end.kind!==`unbounded`&&a({value:Y(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=>cr(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=Vn(n),a={physicalTime:Number(e.physical??0),logicalCounter:Number(e.logical??0),peerId:String(e.peer??``)},o={},s=rr(e.data);s!==void 0&&(o.data=s);let c=nr(e.metadata);c!==void 0&&(o.metadata=c);let l=$(a,o);i.push({key:r,raw:l,value:o.data})}return i}version(){let e={};for(let[t,n]of this.vv.entries())e[t]={...n};return e}peerId(){return this.peerIdValue}getMaxPhysicalTime(){return this.maxHlc.physicalTime}async exportInternal(e,t,n){let r=new Map;if(e)for(let[t,n]of Object.entries(e)){let e=sr(n);e&&r.set(t,e)}let i={},a=n?[n]:Array.from(this.vv.keys()),o=[];for(let e of a){let t=this.vv.get(e),n=r.get(e);t&&n&&(t.physicalTime<n.physicalTime||t.physicalTime===n.physicalTime&&t.logicalCounter<=n.logicalCounter)||o.push({peer:e,fromEntry:n})}if(n&&o.every(e=>e.peer!==n)&&o.push({peer:n,fromEntry:r.get(n)}),o.length===0)return{version:0,entries:i};for(let e of o){let n=[e.peer],r=`WHERE peer = ?`;e.fromEntry&&(r+=` AND physical >= ?`,n.push(e.fromEntry.physicalTime));let a=await this.db.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} ${r} ORDER BY physical, logical, key`,n);for(let n of a){let r={physicalTime:Number(n.physical??0),logicalCounter:Number(n.logical??0),peerId:String(n.peer??``)},a=e.fromEntry;if(a&&(r.physicalTime<a.physicalTime||r.physicalTime===a.physicalTime&&r.logicalCounter<=a.logicalCounter)||t!==void 0&&Number.isFinite(t)&&n.data===null&&r.physicalTime<t)continue;let o={},s=rr(n.data);s!==void 0&&(o.data=s);let c=nr(n.metadata);c!==void 0&&(o.metadata=c);let l=Vn(n.key);i[Wn(l)]=$(r,o)}}return{version:0,entries:i}}async exportWithHooks(e){let t=await this.exportInternal(e.from,e.pruneTombstonesBefore,e.peerId),n=e.hooks?.transform;if(!n)return t;let r={version:t.version,entries:{}};for(let[e,i]of Object.entries(t.entries)){let t=ir(i.c),a={key:JSON.parse(e),clock:t,raw:{...i}},o={};i.d!==void 0&&(o.data=X(i.d));let s=Z(i.m);s!==void 0&&(o.metadata=s);let c=Q(o),l=Qn(o,await n(a,c)??c);r.entries[e]=$(t,l)}return r}exportJson(e,t){return er(e)?this.exportWithHooks(e):this.exportInternal(e,t)}async importInternal(e){if(e.version!==0)throw TypeError(`Unsupported bundle version`);let t=0,n=[],r=[];for(let[i,a]of Object.entries(e.entries)){let e;try{let t=JSON.parse(i);e=Array.isArray(t)?t:[]}catch{n.push({key:[],reason:`invalid key`});continue}let o=ir(a.c),s={};a.d!==void 0&&(s.data=X(a.d));let c=Z(a.m);c!==void 0&&(s.metadata=c),t+=1,await this.applyOperation({key:e,payload:s,clock:o,skipSameValue:!1,source:`import`,eventSink:r})}return r.length>0&&this.emitEvents(`import`,r),{accepted:t,skipped:n}}async importJson(e){if(tr(e)){let t=e.hooks?.preprocess,n=t?{version:e.bundle.version,entries:{...e.bundle.entries}}:e.bundle,r=[];if(t)for(let[e,i]of Object.entries(n.entries)){let a=JSON.parse(e),o=ir(i.c),s={};i.d!==void 0&&(s.data=X(i.d));let c=Z(i.m);c!==void 0&&(s.metadata=c);let l=$n(await t({key:a,clock:o,raw:i},Q(s)));l.accept?n.entries[e]=$(o,s):(r.push({key:a,reason:l.reason??`rejected`}),delete n.entries[e])}let i=await this.importInternal(n);return{accepted:i.accepted,skipped:r.concat(i.skipped)}}return this.importInternal(e)}async importJsonStr(e){let t=JSON.parse(e);return this.importJson(t)}async digest(){return u(await lr(await this.db.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} ORDER BY key ASC`)))}async kvToJson(){return this.exportInternal()}async merge(e){let t=await e.exportJson();await this.importJson(t)}static async checkConsistency(e,t){let[n,r]=await Promise.all([e.digest(),t.digest()]);return n===r}checkInvariants(){}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};export{fr as Flock,fr as FlockSQLite};
27
+ //# sourceMappingURL=index.mjs.map