github-stars-organizer 0.0.0-stage → 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.
- package/LICENSE +662 -0
- package/README.md +32 -2
- package/dist/THIRD-PARTY-LICENSES.txt +79 -0
- package/dist/app/THIRD-PARTY-LICENSES.txt +1964 -0
- package/dist/app/assets/backups-DxRMQO9O.js +1 -0
- package/dist/app/assets/badge-Ba4FNylI.js +1 -0
- package/dist/app/assets/button-ZbiqMfUE.js +14 -0
- package/dist/app/assets/coerce-B4B_TTls.js +1 -0
- package/dist/app/assets/download-CzXogqy0.js +1 -0
- package/dist/app/assets/esm-hHQKpih6.js +393 -0
- package/dist/app/assets/explore-CrybvCPL.js +33 -0
- package/dist/app/assets/history-C-bdlEYN.js +1 -0
- package/dist/app/assets/index-B6vy4QhK.css +2 -0
- package/dist/app/assets/index-C_V67CMR.js +10 -0
- package/dist/app/assets/list._listId-BHMtNFq8.js +1 -0
- package/dist/app/assets/list._listId-tfkSZzxB.js +2 -0
- package/dist/app/assets/local-sync-DQzF1V9q.js +1 -0
- package/dist/app/assets/opfs-worker-accoEoax-B2IN8tCs.js +5890 -0
- package/dist/app/assets/registry-BKuxwL5K.js +4 -0
- package/dist/app/assets/routes-C_O77OAA.js +1 -0
- package/dist/app/assets/routes-lhdAnl7w.js +2 -0
- package/dist/app/assets/schemas-D_ddKDHk.js +39 -0
- package/dist/app/assets/space-grotesk-latin-ext-wght-normal-D9tNdqV9.woff2 +0 -0
- package/dist/app/assets/space-grotesk-latin-wght-normal-BhU9QXUp.woff2 +0 -0
- package/dist/app/assets/space-grotesk-vietnamese-wght-normal-D0rl6rjA.woff2 +0 -0
- package/dist/app/assets/star-DgcTDj5Y.js +7 -0
- package/dist/app/assets/sync-persistence-f8LlQoHO.js +2 -0
- package/dist/app/favicon.svg +1 -0
- package/dist/app/icons.svg +24 -0
- package/dist/app/index.html +33 -0
- package/dist/app/og.jpg +0 -0
- package/dist/cli.js +7111 -0
- package/package.json +25 -4
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import{A as e,C as t,F as n,I as r,L as i,N as a,O as o,P as s,R as c,S as l,T as u,f as d,j as f,k as p,r as m,t as ee,u as h,v as g,x as _,y as te}from"./sync-persistence-f8LlQoHO.js";var v=class extends f{constructor(e){super(e),this.name=`PersistedCollectionCoreError`}},y=class extends v{constructor(e){super(e),this.name=`InvalidPersistedCollectionConfigError`}},ne=class extends y{constructor(e){super(e?`Invalid sync config: ${e}`:`Invalid sync config: expected an object with a callable sync function`),this.name=`InvalidSyncConfigError`}},b=class extends y{constructor(e){super(`Invalid persisted collection coordinator: missing required "${e}" method`),this.name=`InvalidPersistedCollectionCoordinatorError`}},x=class extends y{constructor(e){super(`Invalid persistence adapter: missing required "${e}" method`),this.name=`InvalidPersistenceAdapterError`}},S=class extends v{constructor(e,t={}){super(e),this.name=`PersistedCollectionDurabilityError`,this.cause=t.cause,this.code=t.code,this.path=t.path}};function re(e,t){if(t instanceof S)return t;let n=typeof t==`object`&&t?t:void 0;return new S(`Failed to durably persist collection "${e}": ${t instanceof Error?t.message:String(t)}`,{cause:t,code:n?.code,path:n?.path})}var C=class extends v{constructor(e){super(`Commit outcome is indeterminate for collection "${e.collectionId}": ${e.requestType} crossed leadership from ${ie(e.previousLeaderId,e.previousTerm)} to ${ie(e.currentLeaderId,e.currentTerm)}`),this.code=`INDETERMINATE_COMMIT`,this.name=`IndeterminateCommitError`,this.collectionId=e.collectionId,this.requestType=e.requestType,this.previousLeaderId=e.previousLeaderId,this.previousTerm=e.previousTerm,this.currentLeaderId=e.currentLeaderId,this.currentTerm=e.currentTerm,this.cause=e.cause}};function ie(e,t){return`${e??`unknown leader`} (term ${t??`unknown`})`}var w=class extends v{constructor(e){super(`A remote subset owner is already registered for collection "${e}"`),this.name=`DuplicateRemoteSubsetOwnerError`,this.collectionId=e}},T=class extends v{constructor(e,t){super(e),this.name=`RetryableRemoteSubsetAcquisitionError`,this.cause=t}},E=class extends y{constructor(e){super(`Invalid persisted storage key "${String(e)}": numeric keys must be finite`),this.name=`InvalidPersistedStorageKeyError`}},ae=class extends y{constructor(e){super(`Invalid persisted storage key encoding "${e}": expected prefix "n:" or "s:"`),this.name=`InvalidPersistedStorageKeyEncodingError`}},oe=class extends v{constructor(e,t,n){super(`SQLite BigInt value ${e} is outside the signed 64-bit range [${t}, ${n}]`),this.name=`SQLiteBigIntOutOfRangeError`}},D=class extends v{constructor(e){super(e?`Persistence unavailable: ${e}`:`Persistence unavailable in this runtime`),this.name=`PersistenceUnavailableError`}},se=-9223372036854775808n,ce=9223372036854775807n,O=`__tanstack_db_persisted_type__`,k=`value`;function A(e){if(e<-9223372036854775808n||e>9223372036854775807n)throw new oe(e,se,ce);return e}function le(e){return A(e),{[O]:`bigint`,[k]:e.toString()}}function j(e){if(typeof e!=`object`||!e)return;let t=e[Symbol.toStringTag];if(t===`Temporal.Instant`||t===`Temporal.PlainDate`)return t}function M(e){let t=e.slice(9),n=globalThis.Temporal?.[t];if(typeof n?.from!=`function`||typeof n.prototype.toString!=`function`)throw new y(`Missing global ${e} constructor for SQLite persistence`);return n}function ue(e,t){return M(e).from(t)}function N(e){if(typeof e!=`object`||!e)return;let t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return;let n=e[Symbol.toStringTag];if(typeof n!=`string`||!n.startsWith(`Temporal.`))return;let r=j(e);if(!r)throw new y(`Unsupported ${n} value for SQLite persistence`);let i=M(r),a;try{a=i.prototype.toString.call(e)}catch{throw new y(`Invalid ${r} value for the registered global constructor`)}let o=i.from(a),s=r===`Temporal.PlainDate`?o.withCalendar(`iso8601`):void 0,c=s?`${String(s.year+1e6).padStart(7,`0`)}${String(s.month).padStart(2,`0`)}${String(s.day).padStart(2,`0`)}`:(o.epochNanoseconds+10000000000000000000000n).toString().padStart(23,`0`);return{[O]:r,[k]:a,order:c}}function de(e){return`${e[O]}:${e[k]}`}var P=class extends TypeError{constructor(e,t){super(`Unsupported remote subset wire value at ${e}: ${t}`),this.path=e,this.name=`RemoteSubsetWireValueError`}},fe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],pe=Date,me=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function he(e){return _e(e,!1)}function ge(e){_e(e,!0)}function _e(e,t){Ae(e,`options`),R(e,`options`,[`where`,`orderBy`,`limit`,`cursor`,`offset`,`refetch`,`signal`,`subscription`]);let n={validateOnly:t,expressions:new WeakMap,expressionArrays:new WeakMap,stringArrays:new WeakMap,orderByArrays:new WeakMap,orderByClauses:new WeakMap,compareOptions:new WeakMap,cursors:new WeakMap,wireValues:new WeakMap},r=t?e:{},i=L(e,`where`,`options.where`),a=L(e,`orderBy`,`options.orderBy`),o=L(e,`limit`,`options.limit`),s=L(e,`cursor`,`options.cursor`),c=L(e,`offset`,`options.offset`),l=L(e,`refetch`,`options.refetch`);if(i.present&&i.value!==void 0){let e=ye(i.value,`options.where`,n);n.validateOnly||(r.where=e)}if(a.present&&a.value!==void 0){let e=Se(a.value,`options.orderBy`,n);n.validateOnly||(r.orderBy=e)}if(o.present&&o.value!==void 0){let e=ke(o.value,`options.limit`);n.validateOnly||(r.limit=e)}if(s.present&&s.value!==void 0){let e=we(s.value,`options.cursor`,n);n.validateOnly||(r.cursor=e)}if(c.present&&c.value!==void 0){let e=ke(c.value,`options.offset`);n.validateOnly||(r.offset=e)}if(l.present&&l.value!==void 0){if(typeof l.value!=`boolean`)throw new P(`options.refetch`,`expected boolean`);n.validateOnly||(r.refetch=l.value)}return r}function ve(e,t=he(e)){let n={...t},r=L(e,`signal`,`options.signal`),i=L(e,`subscription`,`options.subscription`);return r.present&&(n.signal=r.value),i.present&&(n.subscription=i.value),n}function ye(e,t,a){let o=Be(e,t),s=a.expressions.get(o);if(s)return s;let c=L(o,`type`,`${t}.type`);if(!c.present||typeof c.value!=`string`)throw new P(`${t}.type`,H(c.value));switch(c.value){case`ref`:{je(o,t,r.prototype),R(o,t,[`type`,`path`,`sourceAlias`]);let e=a.validateOnly?o:{type:`ref`,path:[]};a.expressions.set(o,e);let n=xe(I(o,`path`,`${t}.path`),`${t}.path`,a);a.validateOnly||(e.path=n);let i=L(o,`sourceAlias`,`${t}.sourceAlias`);if(i.present){if(typeof i.value!=`string`||n[0]!==i.value)throw new P(`${t}.sourceAlias`,`source alias must match the first path segment`);a.validateOnly||(e.sourceAlias=i.value)}return e}case`val`:{je(o,t,i.prototype),R(o,t,[`type`,`value`]);let e=a.validateOnly?o:{type:`val`,value:void 0};a.expressions.set(o,e);let n=F(I(o,`value`,`${t}.value`),`${t}.value`,a);return a.validateOnly||(e.value=n),e}case`func`:{je(o,t,n.prototype),R(o,t,[`type`,`name`,`args`]);let e=a.validateOnly?o:{type:`func`,name:``,args:[]};a.expressions.set(o,e);let r=I(o,`name`,`${t}.name`);if(typeof r!=`string`)throw new P(`${t}.name`,H(r));a.validateOnly||(e.name=r);let i=be(I(o,`args`,`${t}.args`),`${t}.args`,a);return a.validateOnly||(e.args=i),e}default:throw new P(`${t}.type`,String(c.value))}}function be(e,t,n){let r=ze(e,t),i=n.expressionArrays.get(r);if(i)return i;Ie(r,t);let a=n.validateOnly?r:Array(r.length);n.expressionArrays.set(r,a);for(let e=0;e<r.length;e++){if(!(e in r))throw new P(`${t}[${e}]`,`missing expression`);let i=ye(r[e],`${t}[${e}]`,n);n.validateOnly||(a[e]=i)}return a}function xe(e,t,n){let r=ze(e,t),i=n.stringArrays.get(r);if(i)return i;Ie(r,t);let a=n.validateOnly?r:Array(r.length);n.stringArrays.set(r,a);for(let e=0;e<r.length;e++){let i=r[e];if(!(e in r)||typeof i!=`string`)throw new P(`${t}[${e}]`,H(i));n.validateOnly||(a[e]=i)}return a}function Se(e,t,n){let r=ze(e,t),i=n.orderByArrays.get(r);if(i)return i;Ie(r,t);let a=n.validateOnly?r:Array(r.length);n.orderByArrays.set(r,a);for(let e=0;e<r.length;e++){let i=`${t}[${e}]`,o=Ve(r[e],i),s=n.orderByClauses.get(o);if(s){n.validateOnly||(a[e]=s);continue}R(o,i,[`expression`,`compareOptions`]);let c=n.validateOnly?o:{expression:void 0,compareOptions:void 0};n.validateOnly||(a[e]=c),n.orderByClauses.set(o,c);let l=ye(I(o,`expression`,`${i}.expression`),`${i}.expression`,n),u=Ce(I(o,`compareOptions`,`${i}.compareOptions`),`${i}.compareOptions`,n);n.validateOnly||(c.expression=l,c.compareOptions=u)}return a}function Ce(e,t,n){let r=Ve(e,t),i=n.compareOptions.get(r);if(i)return i;R(r,t,[`direction`,`nulls`,`stringSort`,`locale`,`localeOptions`]);let a=n.validateOnly?r:{},o=I(r,`direction`,`${t}.direction`);if(o!==`asc`&&o!==`desc`)throw new P(`${t}.direction`,H(o));n.validateOnly||(a.direction=o);let s=I(r,`nulls`,`${t}.nulls`);if(s!==`first`&&s!==`last`)throw new P(`${t}.nulls`,H(s));n.validateOnly||(a.nulls=s);let c=L(r,`stringSort`,`${t}.stringSort`);if(c.present&&c.value!==void 0){if(c.value!==`lexical`&&c.value!==`locale`)throw new P(`${t}.stringSort`,H(c.value));n.validateOnly||(a.stringSort=c.value)}if(a.stringSort!==`lexical`){let e=L(r,`locale`,`${t}.locale`);if(e.present&&e.value!==void 0){if(typeof e.value!=`string`)throw new P(`${t}.locale`,H(e.value));n.validateOnly||(a.locale=e.value)}let i=L(r,`localeOptions`,`${t}.localeOptions`);if(i.present&&i.value!==void 0){let e=Oe(i.value,`${t}.localeOptions`,n);n.validateOnly||(a.localeOptions=e)}}let l=a;return n.compareOptions.set(r,l),l}function we(e,t,n){let r=Ve(e,t),i=n.cursors.get(r);if(i)return i;R(r,t,[`whereFrom`,`whereCurrent`,`lastKey`]);let a=n.validateOnly?r:{whereFrom:void 0,whereCurrent:void 0};n.cursors.set(r,a);let o=ye(I(r,`whereFrom`,`${t}.whereFrom`),`${t}.whereFrom`,n),s=ye(I(r,`whereCurrent`,`${t}.whereCurrent`),`${t}.whereCurrent`,n);n.validateOnly||(a.whereFrom=o,a.whereCurrent=s);let c=L(r,`lastKey`,`${t}.lastKey`);if(c.present&&c.value!==void 0){if(typeof c.value!=`string`&&typeof c.value!=`number`)throw new P(`${t}.lastKey`,H(c.value));n.validateOnly||(a.lastKey=c.value)}return a}function F(e,t,n){if(e==null||typeof e==`boolean`||typeof e==`string`||typeof e==`number`||typeof e==`bigint`)return e;if(typeof e!=`object`)throw new P(t,H(e));let r=n.wireValues.get(e);if(r)return r;if(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)throw new P(t,`SharedArrayBuffer`);if(e instanceof pe){z(e,pe.prototype,t),Me(e,t);let r=e.getTime(),i=n.validateOnly?e:new pe(r);return n.wireValues.set(e,i),i}if(e instanceof RegExp){z(e,RegExp.prototype,t),Pe(e,t);let{source:r,flags:i}=e,a=n.validateOnly?e:new RegExp(r,i);return n.wireValues.set(e,a),a}if(e instanceof ArrayBuffer){z(e,ArrayBuffer.prototype,t),Me(e,t),Ne(e,t);let r;try{n.validateOnly?(new Uint8Array(e,0,0),r=e):r=e.slice(0)}catch{throw new P(t,`detached ArrayBuffer`)}return n.wireValues.set(e,r),r}if(e instanceof DataView){z(e,DataView.prototype,t),Me(e,t);let r,i,a;try{r=e.byteOffset,i=e.byteLength,a=e.buffer}catch{throw new P(t,`detached DataView`)}let o=F(a,t,n);if(!(o instanceof ArrayBuffer))throw new P(t,`shared DataView buffer`);let s=n.validateOnly?e:new DataView(o,r,i);return n.wireValues.set(e,s),s}let i=Re(e);if(i){let r=e;Fe(r,t);let a,o,s;try{a=r.byteOffset,o=r.length,s=r.buffer}catch{throw new P(t,`detached typed array`)}if(!(s instanceof ArrayBuffer))throw new P(t,`shared typed-array buffer`);let c=F(s,t,n);if(!(c instanceof ArrayBuffer))throw new P(t,`shared typed-array buffer`);let l;try{l=n.validateOnly?r:new i(c,a,o)}catch{throw new P(t,`detached typed array`)}return n.wireValues.set(e,l),l}if(ArrayBuffer.isView(e))throw new P(t,H(e));return Array.isArray(e)?Te(e,t,n):e instanceof Map?Ee(e,t,n):e instanceof Set?De(e,t,n):Oe(e,t,n)}function Te(e,t,n){Ie(e,t);let r=n.validateOnly?e:Array(e.length);n.wireValues.set(e,r);for(let i=0;i<e.length;i++)if(i in e){let a=F(e[i],`${t}[${i}]`,n);n.validateOnly||(r[i]=a)}return r}function Ee(e,t,n){z(e,Map.prototype,t),Me(e,t);let r=n.validateOnly?e:new Map;n.wireValues.set(e,r);let i=0;for(let[a,o]of e){let e=F(a,`${t}.entries[${i}].key`,n),s=F(o,`${t}.entries[${i}].value`,n);n.validateOnly||r.set(e,s),i++}return r}function De(e,t,n){z(e,Set.prototype,t),Me(e,t);let r=n.validateOnly?e:new Set;n.wireValues.set(e,r);let i=0;for(let a of e){let e=F(a,`${t}.values[${i}]`,n);n.validateOnly||r.add(e),i++}return r}function Oe(e,t,n){let r=Ve(e,t),i=n.wireValues.get(r);if(i)return i;let a=n.validateOnly?r:{};n.wireValues.set(r,a);for(let e of B(r,t)){let i=V(t,e);if(typeof e==`symbol`)throw new P(i,`symbol property key`);let o=Object.getOwnPropertyDescriptor(r,e);if(!o||!o.enumerable||!(`value`in o))throw new P(i,`non-data property`);let s=F(o.value,i,n);n.validateOnly||Object.defineProperty(a,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}return a}function ke(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new P(t,`non-negative safe integer`);return e}function I(e,t,n){let r=L(e,t,n);if(!r.present)throw new P(n,`missing property`);return r.value}function L(e,t,n){let r;try{r=Object.getOwnPropertyDescriptor(e,t)}catch{throw new P(n,`unreadable property`)}if(!r)return{present:!1};if(!r.enumerable||!(`value`in r))throw new P(n,`non-data property`);return{present:!0,value:r.value}}function R(e,t,n){let r=new Set(n);for(let n of B(e,t)){if(typeof n==`symbol`||!r.has(n))throw new P(V(t,n),`property`);L(e,n,V(t,n))}}function Ae(e,t){z(e,Object.prototype,t)}function je(e,t,n){let r;try{r=Object.getPrototypeOf(e)}catch{throw new P(t,`unreadable prototype`)}if(r!==Object.prototype&&r!==n)throw new P(t,H(e))}function z(e,t,n){let r;try{r=Object.getPrototypeOf(e)}catch{throw new P(n,`unreadable prototype`)}if(r!==t)throw new P(n,H(e))}function Me(e,t){let n=B(e,t);if(n.length>0)throw new P(V(t,n[0]),`property`)}function Ne(e,t){if(e.resizable)throw new P(t,`resizable ArrayBuffer`)}function Pe(e,t){let n=B(e,t);for(let e of n)if(e!==`lastIndex`)throw new P(V(t,e),`property`);let r=Object.getOwnPropertyDescriptor(e,`lastIndex`);if(!r||!(`value`in r)||r.value!==0)throw new P(`${t}.lastIndex`,`RegExp lastIndex must be 0`)}function Fe(e,t){let n=B(e,t);for(let r of n)if(typeof r!=`string`||!Le(r,e.length))throw new P(V(t,r),`property`)}function Ie(e,t){z(e,Array.prototype,t);let n=B(e,t);for(let r of n){if(r!==`length`&&(typeof r!=`string`||!Le(r,e.length)))throw new P(V(t,r),`property`);r!==`length`&&L(e,r,V(t,r))}}function Le(e,t){if(!/^(0|[1-9][0-9]*)$/.test(e))return!1;let n=Number(e);return Number.isSafeInteger(n)&&n>=0&&n<t}function Re(e){let t;try{t=Object.getPrototypeOf(e)}catch{return}return fe.find(e=>t===e.prototype)}function ze(e,t){if(!Array.isArray(e))throw new P(t,H(e));return e}function Be(e,t){if(typeof e!=`object`||!e)throw new P(t,H(e));return e}function Ve(e,t){let n=Be(e,t);return z(n,Object.prototype,t),n}function B(e,t){try{return Reflect.ownKeys(e)}catch{throw new P(t,`unreadable properties`)}}function V(e,t){return typeof t==`symbol`?`${e}[${String(t)}]`:me.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function H(e){return e===null?`null`:typeof e==`object`?`object`:typeof e}function He(e,t){try{e.onError(t)}catch{}}async function Ue(e,t){try{let n=e.unloadSubset(t);await Promise.resolve(n)}catch(t){throw He(e,t),t}}function U(e){return{kind:`eager`,collectionId:e}}function W(e,t){return{kind:`managed`,storageCollectionId:e,claimId:t}}function G(e,t){let n=e;if(typeof n!=`object`||!n)throw new y(`SQLite persistence requires an explicit eager or managed storage target`);let r=n;if(r.kind===`eager`){if(typeof r.collectionId!=`string`||r.collectionId.trim().length===0)throw new y(`An eager storage target requires a nonempty collectionId`);if(t!==void 0||`claimId`in r||`storageCollectionId`in r)throw new y(`An eager storage target cannot carry a persisted cache claim`);return{collectionId:r.collectionId}}if(r.kind!==`managed`)throw new y(`Unknown SQLite persistence storage target kind`);if(typeof r.storageCollectionId!=`string`||r.storageCollectionId.trim().length===0||typeof r.claimId!=`string`||r.claimId.trim().length===0)throw new y(`A managed storage target requires a storageCollectionId and persisted cache claim`);if(`collectionId`in r)throw new y(`A managed storage target cannot carry an eager collectionId`);if(t!==void 0&&t!==r.claimId)throw new y(`The persisted cache claim does not match its storage target`);return{collectionId:r.storageCollectionId,claimId:r.claimId}}var We=Symbol.for(`tanstack-db.sqlite-driver-supports-shared-logical-scheduling`),Ge=class{constructor(e){this.networkTimeoutMs=e,this.snapshot={status:`loading`},this.listeners=new Set,this.getSnapshot=()=>this.snapshot,this.getOrStartNetworkDeadline=()=>this.networkDeadlineAt??=Date.now()+this.networkTimeoutMs,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}set(e){let t=e.status===`loading`&&this.networkDeadlineAt!==void 0;if(t&&(this.networkDeadlineAt=Date.now()+this.networkTimeoutMs),!(this.snapshot.status===e.status&&this.snapshot.error===e.error&&!t)){this.snapshot=e;for(let e of this.listeners)e()}}},Ke=3e3,qe=6e4,Je=2147483647;function Ye(e){if(e===void 0)return;if(e.strategy!==`network-first`)throw new y(`initialRender.strategy must be "network-first"`);let t=e.networkTimeoutMs??Ke;if(!Number.isFinite(t)||t<0||t>Je)throw new y(`initialRender.networkTimeoutMs must be between 0 and ${Je}`);return t}var Xe=[`getNodeId`,`subscribe`,`publish`,`isLeader`,`ensureLeadership`,`requestEnsureRemoteSubset`,`requestReleaseRemoteSubset`,`registerRemoteSubsetOwner`,`requestEnsurePersistedIndex`,`requestApplyCommittedTx`],Ze=[`loadSubset`,`loadResumeSnapshot`,`applyCommittedTx`,`ensureIndex`],Qe=128,$e=`tanstack-db`,et=50,tt=class{constructor(e=s()){this.collectionAdapters=new Map,this.remoteSubsetOwners=new Map,this.remoteSubsetAcquisitions=new Map,this.nodeId=e}getNodeId(){return this.nodeId}subscribe(){return()=>{}}publish(){}isLeader(){return!0}async ensureLeadership(){}async requestEnsureRemoteSubset(e,t){let n=ve(t,he(t)),r=this.remoteSubsetOwners.get(e);if(!r)throw new y(`SingleProcessCoordinator has no remote subset owner configured for collection "${e}"`);let i=this.remoteSubsetAcquisitions.get(e);i||(i=new Map,this.remoteSubsetAcquisitions.set(e,i));let a=i.get(t);if(a){await a.load;return}let o,s,c=new Promise((e,t)=>{o=e,s=t});i.set(t,{owner:r,options:n,load:c});try{let e=r(n);Promise.resolve(e).then(o,e=>{He(r,e),s(e)})}catch(e){He(r,e),s(e)}await c}async requestReleaseRemoteSubset(e,t){let n=this.remoteSubsetAcquisitions.get(e),r=n?.get(t);r&&(n.delete(t),n.size===0&&this.remoteSubsetAcquisitions.delete(e),await Ue(r.owner,r.options))}registerRemoteSubsetOwner(e,t){if(this.remoteSubsetOwners.has(e))throw new w(e);return this.remoteSubsetOwners.set(e,t),()=>{if(this.remoteSubsetOwners.get(e)!==t)return;let n=this.remoteSubsetAcquisitions.get(e);this.remoteSubsetAcquisitions.delete(e),this.remoteSubsetOwners.delete(e);for(let e of n?.values()??[])Ue(t,e.options).catch(()=>void 0)}}async requestEnsurePersistedIndex(){}setAdapterForCollection(e,t){this.collectionAdapters.set(e,t)}async requestApplyCommittedTx(e,t,n){let r=n??this.collectionAdapters.get(e);if(!r)throw new y(`SingleProcessCoordinator has no persistence adapter configured for collection "${e}"`);try{await r.applyCommittedTx(t.cacheGenerationClaimId?W(e,t.cacheGenerationClaimId):U(e),t)}catch(t){throw re(e,t)}return{type:`rpc:applyCommittedTx:res`,rpcId:s(),ok:!0,term:t.term,seq:t.seq,latestRowVersion:t.rowVersion}}pullSince(){return Promise.resolve({type:`rpc:pullSince:res`,rpcId:s(),ok:!0,latestTerm:1,latestSeq:0,latestRowVersion:0,requiresFullReload:!1,changedKeys:[],deletedKeys:[],deltas:[]})}};function nt(e){for(let t of Xe)if(typeof e[t]!=`function`)throw new b(t)}function rt(e){for(let t of Ze)if(typeof e[t]!=`function`)throw new x(t)}function it(e,t){rt(e.adapter);let n=e.coordinator??new tt;return n instanceof tt&&n.setAdapterForCollection(t,e.adapter),nt(n),{...e,coordinator:n}}function at(e,t,n){let r=e.resolvePersistenceForMode?.(t);return it(r??e,n)}function ot(e,t){let n=e.resolvePersistenceForCollection?.(t);return n?it(n,t.collectionId):at(e,t.mode,t.collectionId)}function st(e){return Object.prototype.hasOwnProperty.call(e,`sync`)}function ct(e){return typeof e==`object`&&!!e}function lt(e){return ct(e)?typeof e.sync==`function`:!1}var ut=class{constructor(){this.queue=Promise.resolve(),this.pending=0}reserve(){let e=this.pending===0,t=this.queue;this.pending++;let n,r=new Promise(e=>{n=e});this.queue=e?r:t.then(()=>r);let i=!1;return{run:r=>{if(i)return Promise.reject(Error(`an apply-mutex reservation can only run once`));i=!0;let a;if(e)try{a=Promise.resolve(r())}catch(e){a=Promise.reject(e)}else a=t.then(()=>r());let o=()=>{this.pending--,n()};return a.then(o,o),a}}}run(e){return this.reserve().run(e)}};function dt(e,t){return t.some(t=>!t||l(t(e)))}function K(e){if(e==null)return e;switch(typeof e){case`string`:case`number`:case`boolean`:return e;case`bigint`:return le(e);case`function`:case`symbol`:case`undefined`:return}let t=N(e);if(t)return t;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>K(e)).filter(e=>e!==void 0);if(e instanceof Set)return Array.from(e).map(e=>K(e)).filter(e=>e!==void 0).sort((e,t)=>{let n=JSON.stringify(e),r=JSON.stringify(t);return n<r?-1:+(n>r)});if(e instanceof Map)return Array.from(e.entries()).map(([e,t])=>({key:K(e),value:K(t)})).filter(e=>e.key!==void 0&&e.value!==void 0).sort((e,t)=>{let n=JSON.stringify(e.key),r=JSON.stringify(t.key);return n<r?-1:+(n>r)});let n=e,r=Object.keys(n).sort((e,t)=>e<t?-1:+(e>t)),i={};for(let e of r){let t=K(n[e]);t!==void 0&&(i[e]=t)}return i}function ft(e){return JSON.stringify(K(e)??null)}function pt(e){return typeof e==`function`?{cleanup:e}:e===void 0?{}:e}function mt(e){return!ct(e)||e.type!==`tx:committed`||typeof e.term!=`number`||typeof e.seq!=`number`||typeof e.txId!=`string`||typeof e.latestRowVersion!=`number`||typeof e.requiresFullReload!=`boolean`?!1:e.requiresFullReload?e.reconciliationReload===void 0||e.reconciliationReload===!0:Array.isArray(e.changedRows)&&Array.isArray(e.deletedKeys)&&(e.rowMetadataMutations===void 0||Array.isArray(e.rowMetadataMutations))&&(e.collectionMetadataMutations===void 0||Array.isArray(e.collectionMetadataMutations))}function ht(e){return ct(e)&&e.type===`collection:reset`&&typeof e.schemaVersion==`number`&&typeof e.resetEpoch==`number`}function gt(e){let t=e.key,n=e.type===`delete`?e.original:e.modified;return{mutationId:e.mutationId,type:e.type,key:t,value:n}}var _t=class{constructor(e,t,n,r,i,a,o){this.mode=e,this.collectionId=t,this.persistence=n,this.syncMode=r,this.dbName=i,this.persistedReadiness=a,this.optionsClaim=o,this.applyMutex=new ut,this.activeSubsets=new Map,this.hydrationSequence=0,this.resetSequence=0,this.pendingRemoteSubsetEnsures=new Map,this.scopedRefreshes=new Map,this.rotatedAcquisitions=new Map,this.rotatedEnsures=new WeakMap,this.queuedHydrationTransactions=[],this.queuedTxCommitted=[],this.requestIds=new WeakMap,this.hydratedDemands=new Set,this.collection=null,this.boundCollection=null,this.syncControls={begin:null,write:null,commit:null,truncate:null,metadata:null,markError:null},this.startupMetadataPromise=null,this.startPromise=null,this.hasAttemptedStartup=!1,this.resumeBaselinePromise=null,this.resumeCertificationPromise=null,this.resumeGenerationOwner=Symbol(`persisted resume generation owner`),this.lifecycleGeneration=0,this.internalApplyDepth=0,this.appliedReceiptSequence=0,this.syncErrorReported=!1,this.pendingAppliedReceipts=new Map,this.hydratingGeneration=null,this.coordinatorUnsubscribe=null,this.remoteSubsetOwnerUnsubscribe=null,this.indexAddedUnsubscribe=null,this.indexRemovedUnsubscribe=null,this.remoteEnsureRetryTimer=null,this.cacheClaimRenewTimer=null,this.cacheClaimRecovery=null,this.nextRequestId=0,this.startupSettled=!1,this.sourceTruncateGeneration=0,this.scopedRecovery=!1,this.scopedRecoveryPending=!1,this.scopedRecoverySequence=0,this.recoverQueuedAfterLocalLoadFailure=!1,this.startupCacheGenerationRotated=!1,this.latestTerm=0,this.latestSeq=0,this.latestRowVersion=0,this.publicRowVersion=0,this.localTerm=1,this.localSeq=0,this.localRowVersion=0}get storageCollectionId(){return this.cacheGenerationClaim?.storageCollectionId??this.collectionId}storageTargetFor(e=this.storageCollectionId,t=this.cacheGenerationClaim?.claimId){if(this.mode===`sync-present`&&this.syncMode===`on-demand`&&this.persistence.adapter.claimCacheGeneration){if(!t)throw new y(`A managed on-demand cache operation requires a persisted cache claim`);return{kind:`managed`,storageCollectionId:e,claimId:t}}return{kind:`eager`,collectionId:e}}cacheGenerationNow(){return this.persistence.adapter.getCacheGenerationNow?.()??Date.now()}hasExpiredCacheClaim(){let e=this.cacheGenerationClaim?.expiresAtMs;return e!==void 0&&this.cacheGenerationNow()>=e}async claimCacheGeneration(e){if(this.mode!==`sync-present`||this.syncMode!==`on-demand`)return;let t=this.persistence.adapter,n=[t.claimCacheGeneration,t.rotateCacheGeneration,t.renewCacheGenerationClaim,t.releaseCacheGenerationClaim];if(n.some(Boolean)&&!n.every(Boolean))throw new y(`An on-demand managed cache generation adapter must implement claimCacheGeneration, rotateCacheGeneration, renewCacheGenerationClaim, and releaseCacheGenerationClaim together`);if(!t.claimCacheGeneration)return;let r=await t.claimCacheGeneration(this.collectionId);if(e!==this.lifecycleGeneration){await t.releaseCacheGenerationClaim?.(r.claimId);return}this.cacheGenerationClaim=r,this.scheduleCacheClaimRenewal(r),this.attachCoordinatorSubscription()}clearCacheClaimRenewal(){this.cacheClaimRenewTimer!==null&&(clearTimeout(this.cacheClaimRenewTimer),this.cacheClaimRenewTimer=null)}scheduleCacheClaimRenewal(e){if(this.clearCacheClaimRenewal(),e.expiresAtMs===void 0||!this.persistence.adapter.renewCacheGenerationClaim)return;let t=e.expiresAtMs-this.cacheGenerationNow(),n=t<=0?1e3:Math.max(1,Math.min(qe,Math.floor(t/2))),r=this.lifecycleGeneration;this.cacheClaimRenewTimer=setTimeout(()=>{this.cacheClaimRenewTimer=null,this.ensureCacheClaimActive().catch(()=>{r===this.lifecycleGeneration&&this.cacheGenerationClaim===e&&this.scheduleCacheClaimRenewal(e)})},n)}async ensureCacheClaimActive(){if(this.cacheClaimRecovery){await this.cacheClaimRecovery;return}if(!await this.renewCacheClaim(this.persistence.adapter)){if(!this.cacheClaimRecovery){let e=this.restartSourceAfterScopedRecovery===void 0?this.reclaimStartupCacheGeneration():this.startScopedRecovery();this.cacheClaimRecovery=e,e.finally(()=>{this.cacheClaimRecovery===e&&(this.cacheClaimRecovery=null)}).catch(()=>void 0)}await this.cacheClaimRecovery}}scheduleCacheClaimRecovery(e){queueMicrotask(()=>{e===this.lifecycleGeneration&&this.ensureCacheClaimActive().then(()=>this.applyMutex.run(()=>this.flushQueuedTxCommittedUnsafe())).catch(t=>{this.markTerminalFailure(t,e)})})}async reclaimStartupCacheGeneration(){let e=this.lifecycleGeneration,t=this.cacheGenerationClaim;if(!t)return;if(!this.persistence.adapter.rotateCacheGeneration)throw new y(`A managed on-demand cache adapter must rotate expired startup claims`);this.clearCacheClaimRenewal(),this.coordinatorUnsubscribe?.(),this.coordinatorUnsubscribe=null;let n=await this.persistence.adapter.rotateCacheGeneration(this.collectionId,t.claimId,void 0,t.storageCollectionId);if(e!==this.lifecycleGeneration){await this.persistence.adapter.releaseCacheGenerationClaim?.(n.claimId);return}this.cacheGenerationClaim=n,this.startupCacheGenerationRotated=!0,this.resetSequence++,this.latestTerm=0,this.latestSeq=0,this.latestRowVersion=0,this.localTerm=1,this.localSeq=0,this.localRowVersion=0,this.persistedResumeGeneration=void 0,this.persistedKeySetEvidence={status:`incompatible`},this.scheduleCacheClaimRenewal(n),this.attachCoordinatorSubscription()}async renewCacheClaim(e){let t=this.cacheGenerationClaim;if(!t||!e.renewCacheGenerationClaim||this.scopedRecoveryPending)return!0;if(t.expiresAtMs!==void 0&&t.expiresAtMs-this.cacheGenerationNow()>qe)return this.cacheClaimRenewTimer===null&&this.scheduleCacheClaimRenewal(t),!0;let n=this.lifecycleGeneration,r=await e.renewCacheGenerationClaim(t.storageCollectionId,t.claimId);return n!==this.lifecycleGeneration||this.cacheGenerationClaim?.claimId!==t.claimId||this.cacheGenerationClaim.storageCollectionId!==t.storageCollectionId?!0:r===void 0?!1:(this.cacheGenerationClaim={...t,expiresAtMs:r},this.scheduleCacheClaimRenewal(this.cacheGenerationClaim),!0)}setSyncControls(e){this.advanceLifecycle(),this.syncErrorReported=!1,this.reportedSyncError=void 0;let t=e.commit;this.syncControls={...e,commit:t?e=>this.trackAppliedReceipt(t(e)):null}}setSourceRestartAfterScopedRecovery(e){this.restartSourceAfterScopedRecovery=e??null}clearSourceRestartAfterScopedRecovery(){this.restartSourceAfterScopedRecovery=void 0}reportSyncError(e){let t=this.syncControls.markError;if(this.syncErrorReported)return this.reportedSyncError;if(!t)return e;this.syncErrorReported=!0,this.reportedSyncError=e;try{t(e)}catch{}return e}registerRemoteSubsetOwner(e){this.remoteSubsetOwnerUnsubscribe?.(),this.remoteSubsetOwner=e,this.remoteSubsetOwnerUnsubscribe=this.persistence.coordinator.registerRemoteSubsetOwner(this.storageCollectionId,e)}trackAppliedReceipt(e){let t=++this.appliedReceiptSequence;if(e===!0)return!0;this.pendingAppliedReceipts.set(t,e);let n=()=>this.pendingAppliedReceipts.delete(t);return e.then(n,n),e}async waitForAppliedReceiptsAfter(e,t=`visible`){await Promise.all(Array.from(this.pendingAppliedReceipts,([n,r])=>n<=e?void 0:t===`accepted`?g(r):r))}async applyLeaderCommitsBeforeReply(e){try{(this.hasExpiredCacheClaim()||this.cacheClaimRecovery)&&await this.ensureCacheClaimActive(),await this.applyMutex.run(()=>this.flushQueuedTxCommittedUnsafe()),this.throwIfTerminal()}catch(t){throw this.getCurrentTerminalFailure()?this.unloadSubset(e):this.queueRemoteSubsetEnsure(e),t}}clearSyncControls(){this.syncControls={begin:null,write:null,commit:null,truncate:null,metadata:null,markError:null}}isHydratingNow(){return this.hydratingGeneration===this.lifecycleGeneration}getActiveHydrationContext(){return this.activeHydrationContext}getHydrationSequence(){return this.hydrationSequence}getCurrentTerminalFailure(){let e=this.terminalFailure;return e?.lifecycleGeneration===this.lifecycleGeneration?e:void 0}getLifecycleGeneration(){return this.lifecycleGeneration}throwIfLifecycleReplaced(t){if(t!==this.lifecycleGeneration)throw new e}throwIfTerminal(){let e=this.getCurrentTerminalFailure();if(e)throw e.error}markTerminalFailure(e,t=this.lifecycleGeneration){if(t!==this.lifecycleGeneration)return e;let n=this.getCurrentTerminalFailure();return n?n.error:(this.terminalFailure={lifecycleGeneration:t,error:e},this.persistedReadiness?.set({status:`error`,error:e}),this.pendingRemoteSubsetEnsures.clear(),this.queuedTxCommitted.length=0,this.remoteEnsureRetryTimer!==null&&(clearTimeout(this.remoteEnsureRetryTimer),this.remoteEnsureRetryTimer=null),this.rejectQueuedHydrationTransactions(e),this.reportSyncError(e),e)}isApplyingInternally(){return this.internalApplyDepth>0}isScopedRecoveryPending(){return this.scopedRecoveryPending}hasBoundCollection(){return this.boundCollection!==null}setCollection(e,t){if(e.config[a]!==this.optionsClaim)throw new y(`Persisted sync belongs to its options Collection`);if(this.boundCollection&&this.boundCollection!==e)throw new y(`Persisted options cannot own more than one Collection`);let n=this.collection,r=this.syncControls;if(this.setSyncControls(t),this.collection===e){this.boundCollection??=e;return}this.collection=e;try{(!this.persistence.adapter.claimCacheGeneration||this.mode!==`sync-present`||this.syncMode!==`on-demand`)&&this.attachCoordinatorSubscription()}catch(e){throw this.collection=n,this.syncControls=r,e}this.boundCollection??=e}getLeadershipState(){return{nodeId:this.persistence.coordinator.getNodeId(),isLeader:this.persistence.coordinator.isLeader(this.storageCollectionId)}}runInHydrationScope(e,t=this.persistence.adapter){return t.runInHydrationScope?t.runInHydrationScope(e):Promise.resolve().then(()=>e(t))}async ensureStarted(){if(this.throwIfTerminal(),this.startPromise)return this.startPromise;let e=this.lifecycleGeneration;this.startupCacheGenerationRotated=!1;let t=this.hasAttemptedStartup;this.hasAttemptedStartup=!0;let n,r;return this.startupMetadataPromise=new Promise((e,t)=>{n=e,r=t}),this.startupMetadataPromise.catch(()=>void 0),this.startPromise=(async()=>{if(await this.claimCacheGeneration(e),e!==this.lifecycleGeneration){n();return}let i=!1,a=async t=>{if(e!==this.lifecycleGeneration)return n(),!1;try{return await this.loadStartupMetadataInternal(e,t)?e===this.lifecycleGeneration:(i=!0,!1)}catch(e){if(this.cacheGenerationClaim&&this.hasExpiredCacheClaim())return i=!0,!1;throw r(e),e}},o,s=this.persistence.adapter.runInHydrationScope!==void 0&&(!t||(this.persistence.adapter.isHydrationScopeScheduled?.()??!0));for(;;){i=!1;let t=this.storageCollectionId;if(s?o=await this.applyMutex.run(async()=>{let t=await this.runInHydrationScope(async t=>{if(await a(t))return this.startInternal(e,t,n)});return e===this.lifecycleGeneration&&await this.flushQueuedTxCommittedUnsafe(),t}):await a(this.persistence.adapter)&&(this.persistence.adapter.isHydrationScopeScheduled?.()?o=await this.applyMutex.run(async()=>{let t=await this.runInHydrationScope(t=>this.startInternal(e,t,n));return e===this.lifecycleGeneration&&await this.flushQueuedTxCommittedUnsafe(),t}):(o=await this.startInternal(e,this.persistence.adapter,n),e===this.lifecycleGeneration&&await this.flushQueuedTxCommittedUnsafe())),this.cacheGenerationClaim&&this.syncMode===`on-demand`&&!i&&(await this.ensureCacheClaimActive(),i=t!==this.storageCollectionId),!i)break;if(await this.ensureCacheClaimActive(),e!==this.lifecycleGeneration){n();return}}this.cacheGenerationClaim&&this.syncMode===`on-demand`&&e===this.lifecycleGeneration&&n(),o!==void 0&&e===this.lifecycleGeneration&&(await this.requestCoordinatorPersistedIndexes(o.indexBootstrapSnapshot,o.completedLocalIndexSignatures),o.appliedCursor!==void 0&&e===this.lifecycleGeneration&&await this.waitForAppliedReceiptsAfter(o.appliedCursor,`accepted`)),e===this.lifecycleGeneration&&(this.startupSettled=!0,this.persistedReadiness?.set({status:`ready`})),n()})().catch(t=>{throw r(t),this.markTerminalFailure(t,e)}),this.startPromise.catch(()=>void 0),this.startPromise}ensureResumeBaselineHydrated(){if(this.throwIfTerminal(),this.resumeBaselinePromise)return this.resumeBaselinePromise;let e=this.lifecycleGeneration;return this.resumeBaselinePromise=(async()=>{if(await this.ensureStarted(),e!==this.lifecycleGeneration||this.syncMode!==`on-demand`||this.scopedRecovery)return;let t=await this.applyMutex.run(async()=>{let t=await this.runInHydrationScope(t=>this.hydrateBaseline(e,t));return e===this.lifecycleGeneration&&await this.flushQueuedTxCommittedUnsafe(),t});if(t===!1){await this.ensureCacheClaimActive();return}t!==void 0&&e===this.lifecycleGeneration&&await this.waitForAppliedReceiptsAfter(t,`accepted`)})().catch(t=>{throw this.markTerminalFailure(t,e)}),this.resumeBaselinePromise}ensureResumeBaselineCertified(){if(this.resumeCertificationPromise)return this.resumeCertificationPromise;let e=this.lifecycleGeneration;return this.resumeCertificationPromise=(async()=>{if(await this.ensureStarted(),e!==this.lifecycleGeneration||this.scopedRecovery)return;let t=this.storageCollectionId,n=this.cacheGenerationClaim?.claimId,r=()=>e===this.lifecycleGeneration&&!this.scopedRecovery&&t===this.storageCollectionId&&n===this.cacheGenerationClaim?.claimId,i;try{i=await this.persistence.adapter.loadResumeSnapshot(this.storageTargetFor(t,n),{requiredIndexSignatures:this.getRequiredIndexSignatures(),includeRows:!1,cacheGenerationClaimId:n})}catch(e){if(!r())return;if(!n||!this.hasExpiredCacheClaim())throw e;await this.ensureCacheClaimActive();return}if(r()){if(n&&!await this.renewCacheClaim(this.persistence.adapter)){await this.ensureCacheClaimActive();return}r()&&this.bindResumeSnapshotEvidence(i)}})(),this.resumeCertificationPromise}getKeySetEvidence(){return this.persistedKeySetEvidence}hasManagedCacheGeneration(){return this.cacheGenerationClaim!==void 0}hasRotatedStartupCacheGeneration(){return this.startupCacheGenerationRotated}async startScopedRecovery(t){this.throwIfTerminal(),this.clearCacheClaimRenewal();let n=this.lifecycleGeneration,r=this.restartSourceAfterScopedRecovery;this.scopedRecovery=!0,this.scopedRecoveryPending=!0;let i=++this.scopedRecoverySequence;this.hydratedDemands.clear(),this.resetSequence++;let a,o,s;try{if(r){let e=new Promise((e,t)=>{a=e,o=t});e.catch(()=>void 0),s=Promise.resolve(r(e)),s.catch(()=>void 0)}if(await this.applyMutex.run(async()=>{this.throwIfLifecycleReplaced(n);let r=this.cacheGenerationClaim;if(r&&this.persistence.adapter.rotateCacheGeneration){let i=r.storageCollectionId,a=await this.persistence.adapter.rotateCacheGeneration(this.collectionId,r.claimId,t,i);if(n!==this.lifecycleGeneration)throw await this.persistence.adapter.releaseCacheGenerationClaim?.(a.claimId),new e;for(let e of this.activeSubsets.values()){if(this.persistence.coordinator.requestReleaseRemoteSubset(i,this.rotatedAcquisitions.get(e)??e).catch(()=>void 0),e.signal?.aborted){this.rotatedAcquisitions.delete(e);continue}this.rotatedAcquisitions.set(e,{...e,refetch:!0})}this.remoteSubsetOwnerUnsubscribe?.(),this.remoteSubsetOwnerUnsubscribe=null,this.coordinatorUnsubscribe?.(),this.coordinatorUnsubscribe=null,this.cacheGenerationClaim=a,this.latestTerm=0,this.latestSeq=0,this.latestRowVersion=0,this.publicRowVersion=0,this.resetTermFence=void 0,this.localTerm=1,this.localSeq=0,this.localRowVersion=0,this.queuedTxCommitted.length=0,this.persistedResumeGeneration=void 0,this.persistedKeySetEvidence={status:`incompatible`},this.resumeCertificationPromise=null,this.resumeGenerationOwner=Symbol(`persisted resume generation owner`),this.attachCoordinatorSubscription(),this.remoteSubsetOwner&&this.registerRemoteSubsetOwner(this.remoteSubsetOwner)}if(this.syncControls.begin&&this.syncControls.commit&&(await g(this.withInternalApply(()=>(this.syncControls.begin?.(),this.syncControls.truncate?.({markReady:!1}),t&&this.syncControls.metadata?.collection.set(t.key,t.value),this.syncControls.commit?.()??!0))),!this.cacheGenerationClaim&&i===this.scopedRecoverySequence&&(this.scopedRecoveryPending=!1),await this.runInHydrationScope(async e=>{this.recoverQueuedAfterLocalLoadFailure?(this.recoverQueuedAfterLocalLoadFailure=!1,await this.recoverBufferedTransactionsAfterLocalLoadFailureUnsafe(n,e)):await this.flushQueuedHydrationTransactionsUnsafe(e)}),await this.flushQueuedTxCommittedUnsafe()),i===this.scopedRecoverySequence&&(this.scopedRecoveryPending=!1,this.cacheGenerationClaim)){let e=this.collection?.getIndexMetadata()??[],t=await this.bootstrapPersistedIndexes(e,this.persistence.adapter);await this.requestCoordinatorPersistedIndexes(e,t)}}),this.throwIfLifecycleReplaced(n),a?.(),await s,i===this.scopedRecoverySequence&&this.cacheGenerationClaim&&this.scheduleCacheClaimRenewal(this.cacheGenerationClaim),i!==this.scopedRecoverySequence)return;for(let e of this.activeSubsets.values()){if(e.signal?.aborted)continue;let t=this.rotatedAcquisitions.get(e);if(t){let n=this.persistence.coordinator.requestEnsureRemoteSubset(this.storageCollectionId,t);this.rotatedEnsures.set(e,n),n.catch(e=>this.reportSyncError(e))}else{this.refreshScopedSubsets();break}}}catch(e){throw o?.(e),this.markTerminalFailure(e,n)}}getResumeGenerationOwner(){return this.resumeGenerationOwner}async hydrateBaseline(e,t){if(e!==this.lifecycleGeneration)return;let n={};this.activeSubsets.set(this.getSubsetKey(n),n);let r=this.appliedReceiptSequence;return await this.hydrateSubsetUnsafe(n,{lifecycleGeneration:e,bindKeySetEvidence:!0},t)?e===this.lifecycleGeneration?r:void 0:!1}async ensureStartupMetadataLoaded(){return this.throwIfTerminal(),this.startupMetadataPromise||this.ensureStarted(),this.startupMetadataPromise}async startInternal(e,t,n){if(e!==this.lifecycleGeneration)return;let r=this.collection?.getIndexMetadata()??[];this.attachIndexLifecycleListeners();let i=await this.bootstrapPersistedIndexes(r,t);if(e!==this.lifecycleGeneration)return;(!this.cacheGenerationClaim||this.syncMode!==`on-demand`)&&n();let a=this.syncMode===`on-demand`?void 0:await this.hydrateBaseline(e,t);return e===this.lifecycleGeneration?{appliedCursor:a===!1?void 0:a,indexBootstrapSnapshot:r,completedLocalIndexSignatures:i}:void 0}async loadStartupMetadataInternal(e,t){let n=this.cacheGenerationClaim?.claimId,r=this.storageCollectionId,i=await t.loadResumeSnapshot(this.storageTargetFor(r,n),{includeRows:!1,cacheGenerationClaimId:n});return e!==this.lifecycleGeneration||n!==this.cacheGenerationClaim?.claimId||r!==this.storageCollectionId||n&&!await this.renewCacheClaim(t)||e!==this.lifecycleGeneration||n!==this.cacheGenerationClaim?.claimId||r!==this.storageCollectionId?!1:(this.persistedResumeGeneration=this.getResumeSnapshotGeneration(i),this.persistedKeySetEvidence=i.keySet,this.observeStreamPosition(i.latestTerm,i.latestSeq,i.latestRowVersion),await g(this.replaceCollectionMetadataSnapshot(i.collectionMetadata)),!0)}async loadCollectionMetadataSnapshot(e){return e.loadCollectionMetadata?e.loadCollectionMetadata(this.storageTargetFor(),{cacheGenerationClaimId:this.cacheGenerationClaim?.claimId}):[]}replaceCollectionMetadataSnapshot(e){return!this.syncControls.begin||!this.syncControls.commit||!this.syncControls.metadata?!0:this.withInternalApply(()=>(this.syncControls.begin?.(),this.applyCollectionMetadataSnapshot(e),this.syncControls.commit?.()??!0))}applyCollectionMetadataSnapshot(e){let t=this.syncControls.metadata;if(!t)return;let n=new Map(e.map(({key:e,value:t})=>[e,t]));for(let{key:e}of t.collection.list())n.has(e)||t.collection.delete(e);for(let[e,r]of n)t.collection.set(e,r)}async loadSubset(e,t,n,r){if(this.throwIfTerminal(),await this.ensureCacheClaimActive(),e.signal?.aborted||r&&!r())return;let i=this.lifecycleGeneration,a=this.getSubsetKey(e),o=this.sourceTruncateGeneration,s=this.canRouteRemoteDemandThroughCoordinator();s&&ge(e),this.activeSubsets.set(a,e);let c=this.appliedReceiptSequence;try{let t=await this.applyMutex.run(async()=>{if(e.signal?.aborted)return`aborted`;try{return await this.runInHydrationScope(t=>e.signal?.aborted?Promise.resolve(`aborted`):(n?.(),this.hydrateSubsetUnsafe(e,{lifecycleGeneration:i,requestLocalLoadFailure:!0,rejectBufferedReplayFailure:!0},t)))}finally{i===this.lifecycleGeneration&&!this.getCurrentTerminalFailure()&&await this.flushQueuedTxCommittedUnsafe()}});if(t===`aborted`){this.activeSubsets.get(a)===e&&this.activeSubsets.delete(a);return}if(!t){await this.ensureCacheClaimActive();let t=this.rotatedAcquisitions.get(e);t&&this.activeSubsets.get(a)===e&&!e.signal?.aborted&&(await(this.rotatedEnsures.get(e)??this.persistence.coordinator.requestEnsureRemoteSubset(this.storageCollectionId,t)),await this.applyLeaderCommitsBeforeReply(e));return}if(i!==this.lifecycleGeneration)return;await this.waitForAppliedReceiptsAfter(c),!s&&this.canRouteRemoteDemandThroughCoordinator()&&ge(e)}catch(t){throw this.activeSubsets.get(a)===e&&this.activeSubsets.delete(a),t}if(e.signal?.aborted||this.activeSubsets.get(this.getSubsetKey(e))!==e){e.signal?.aborted&&this.activeSubsets.get(a)===e&&this.activeSubsets.delete(a);return}if(this.canRouteRemoteDemandThroughCoordinator()){try{await this.persistence.coordinator.requestEnsureRemoteSubset(this.storageCollectionId,this.rotatedAcquisitions.get(e)??e)}catch(t){throw e.signal?.aborted||typeof t==`object`&&t&&`name`in t&&t.name===`AbortError`?(this.pendingRemoteSubsetEnsures.delete(this.getSubsetKey(e)),t):(this.queueRemoteSubsetEnsure(e),t)}await this.applyLeaderCommitsBeforeReply(e);return}if(o===this.sourceTruncateGeneration&&this.activeSubsets.get(a)===e&&this.hydratedDemands.add(d(e)),t)try{await t(e)}catch(t){throw this.noteUpstreamLoadFailure(e,t),t}}loadHydratedSubset(e,t){let n=this.getCurrentTerminalFailure();if(n)return Promise.reject(n.error);if(this.hasExpiredCacheClaim()||!this.startupSettled||this.isHydratingNow()||this.canRouteRemoteDemandThroughCoordinator()||e.refetch===!0||!this.hydratedDemands.has(d(e)))return;this.activeSubsets.set(this.getSubsetKey(e),e);let r;try{r=t?.(e)??!0}catch(t){return this.noteUpstreamLoadFailure(e,t),Promise.reject(t)}return r===!0?!0:r.then(()=>{this.queueRemoteSubsetEnsure(e)},t=>{throw this.noteUpstreamLoadFailure(e,t),t})}noteUpstreamLoadFailure(e,t){if(e.signal?.aborted||typeof t==`object`&&t&&`name`in t&&t.name===`AbortError`){this.pendingRemoteSubsetEnsures.delete(this.getSubsetKey(e));return}console.warn(`Failed to trigger remote subset load:`,t),this.queueRemoteSubsetEnsure(e)}noteSourceTruncate(){this.sourceTruncateGeneration++,this.hydratedDemands.clear()}unloadSubset(e,t){let n=this.getSubsetKey(e);this.activeSubsets.delete(n),this.pendingRemoteSubsetEnsures.delete(n);let r=this.rotatedAcquisitions.get(e)??e;this.rotatedAcquisitions.delete(e);let i=d(e);if(Array.from(this.activeSubsets.values()).some(e=>d(e)===i)||this.hydratedDemands.delete(i),this.mode===`sync-present`&&this.persistence.coordinator.requestReleaseRemoteSubset(this.storageCollectionId,r).catch(e=>{this.reportSyncError(e)}),t)try{let n=t(e);Promise.resolve(n).catch(e=>{this.reportSyncError(e)})}catch(e){this.reportSyncError(e)}}async forceReloadSubset(e){this.throwIfTerminal(),await this.ensureCacheClaimActive();let t=this.lifecycleGeneration;await this.applyMutex.run(async()=>{let n=await this.runInHydrationScope(n=>this.hydrateSubsetUnsafe(e,{lifecycleGeneration:t,rejectBufferedReplayFailure:!0},n));return t===this.lifecycleGeneration&&await this.flushQueuedTxCommittedUnsafe(),n})||await this.ensureCacheClaimActive()}queueHydrationBufferedTransaction(e){let t=this.getCurrentTerminalFailure();if(t){e.rejectApplied?.(t.error);return}e.admittedStorageCollectionId=this.storageCollectionId,this.queuedHydrationTransactions.push(e)}applyHydrationBufferedTransaction(e){let t=this.getCurrentTerminalFailure();return t?Promise.reject(t.error):(e.admittedStorageCollectionId=this.storageCollectionId,this.applyMutex.run(async()=>{await this.applyBufferedSyncTransactionUnsafe(e)}))}normalizeSyncWriteMessage(e){if(!this.collection)throw new y(`collection must be attached before sync writes are processed`);if(`key`in e){let t=e.key;return{operation:{type:`delete`,key:t,value:this.collection.get(t)??{}}}}if(e.type===`delete`){let t=this.collection.getKeyFromItem(e.value);return{operation:{type:`delete`,key:t,value:this.collection.get(t)??e.value}}}return{operation:{type:`update`,key:this.collection.getKeyFromItem(e.value),value:e.value,metadata:e.metadata}}}async persistAndConfirmCollectionMutations(e,t=this.lifecycleGeneration){if(this.throwIfTerminal(),this.throwIfLifecycleReplaced(t),e.length!==0)try{await this.applyMutex.run(async()=>{await this.ensureStartupMetadataLoaded(),this.throwIfLifecycleReplaced(t);let n=await this.persistCollectionMutationsUnsafe(e,t);this.throwIfLifecycleReplaced(t);let r=new Set(n),i=e.filter(e=>r.has(e.mutationId));if(i.length!==e.length)throw Error(`persistence coordinator accepted ${i.length} of ${e.length} mutations; partial acceptance is not supported`);try{await this.confirmMutationsSyncUnsafe(i)}catch(e){throw this.markTerminalFailure(e,t)}})}catch(e){throw e instanceof S?this.markTerminalFailure(e,t):e}}async acceptTransactionMutations(e){this.throwIfTerminal();let t=this.filterMutationsForCollection(e.mutations);t.length!==0&&await this.persistAndConfirmCollectionMutations(t)}cleanup(){this.advanceLifecycle();let t=[],n=[],r=e=>{try{e()}catch(e){n.push(e)}};if(this.mode===`sync-present`)for(let e of this.activeSubsets.values())r(()=>{t.push(this.persistence.coordinator.requestReleaseRemoteSubset(this.storageCollectionId,this.rotatedAcquisitions.get(e)??e).catch(e=>{this.reportSyncError(e)}))});r(()=>this.coordinatorUnsubscribe?.()),this.coordinatorUnsubscribe=null,r(()=>this.remoteSubsetOwnerUnsubscribe?.()),this.remoteSubsetOwnerUnsubscribe=null,this.remoteSubsetOwner=void 0,r(()=>this.indexAddedUnsubscribe?.()),this.indexAddedUnsubscribe=null,r(()=>this.indexRemovedUnsubscribe?.()),this.indexRemovedUnsubscribe=null,this.remoteEnsureRetryTimer!==null&&(clearTimeout(this.remoteEnsureRetryTimer),this.remoteEnsureRetryTimer=null),this.pendingRemoteSubsetEnsures.clear(),this.rotatedAcquisitions.clear();for(let[e,n]of this.scopedRefreshes)t.push(this.persistence.coordinator.requestReleaseRemoteSubset(n,e));this.scopedRefreshes.clear(),this.activeSubsets.clear(),this.hydratedDemands.clear();for(let t of this.queuedHydrationTransactions)t.rejectApplied?.(new e);this.queuedHydrationTransactions.length=0,this.queuedTxCommitted.length=0,this.clearSyncControls(),this.collection=null;let i=this.cacheGenerationClaim;return this.cacheGenerationClaim=void 0,this.clearCacheClaimRenewal(),this.cacheClaimRecovery=null,i&&this.persistence.adapter.releaseCacheGenerationClaim&&t.push(this.persistence.adapter.releaseCacheGenerationClaim(i.claimId)),Promise.all(t).then(()=>{if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,`Persistence cleanup failed`,{cause:n[0]})})}advanceLifecycle(){this.lifecycleGeneration++,this.clearCacheClaimRenewal(),this.cacheClaimRecovery=null,this.scopedRecovery=!1,this.scopedRecoveryPending=!1,this.scopedRecoverySequence++,this.recoverQueuedAfterLocalLoadFailure=!1,this.persistedReadiness?.set({status:`loading`}),this.startupSettled=!1,this.publicRowVersion=0,this.resetTermFence=void 0,this.hydratedDemands.clear(),this.startupMetadataPromise=null,this.startPromise=null,this.resumeBaselinePromise=null,this.terminalFailure=void 0,this.resumeCertificationPromise=null,this.persistedKeySetEvidence=void 0,this.persistedResumeGeneration=void 0,this.resumeGenerationOwner=Symbol(`persisted resume generation owner`)}withInternalApply(e){this.internalApplyDepth++;try{return e()}finally{this.internalApplyDepth--}}getRequiredIndexSignatures(){return this.collection?this.collection.getIndexMetadata().map(e=>e.signature):[]}loadSubsetRowsUnsafe(e,t){return this.scopedRecovery?Promise.resolve([]):t.loadSubset(this.storageTargetFor(),e,{requiredIndexSignatures:this.getRequiredIndexSignatures(),cacheGenerationClaimId:this.cacheGenerationClaim?.claimId})}async scanPersistedRowsUnsafe(e){return this.persistence.adapter.scanRows?this.persistence.adapter.scanRows(this.storageTargetFor(),e,{cacheGenerationClaimId:this.cacheGenerationClaim?.claimId}):[]}async scanPersistedRows(t){for(;;){this.throwIfTerminal(),await this.ensureCacheClaimActive();let n=this.cacheGenerationClaim?.claimId,r=this.storageCollectionId,i=await this.applyMutex.run(()=>this.scanPersistedRowsUnsafe(t));if(this.scopedRecoveryPending)throw new e;if(!(n!==this.cacheGenerationClaim?.claimId||r!==this.storageCollectionId)&&!(n&&!await this.renewCacheClaim(this.persistence.adapter)))return i}}async hydrateSubsetUnsafe(e,t,n){let r=!1,i,a,o=this.resetSequence;this.hydrationSequence++;let s={suppliedRowKeys:new Set};this.activeHydrationContext=s;try{this.throwIfTerminal(),this.hydratingGeneration=t.lifecycleGeneration;try{let a,c;if(t.bindKeySetEvidence&&!this.scopedRecovery){let e=await n.loadResumeSnapshot(this.storageTargetFor(),{requiredIndexSignatures:this.getRequiredIndexSignatures(),includeRows:!0,cacheGenerationClaimId:this.cacheGenerationClaim?.claimId});if(a=e.rows,t.lifecycleGeneration!==this.lifecycleGeneration||o!==this.resetSequence)return!0;c=()=>this.bindResumeSnapshotEvidence(e),i=e.latestRowVersion}else a=await this.loadSubsetRowsUnsafe(e,n);let l=this.syncMode===`on-demand`&&!this.scopedRecovery&&e.where===void 0&&e.limit===void 0&&e.offset===void 0&&e.cursor===void 0?a:void 0;if(r=!0,t.lifecycleGeneration!==this.lifecycleGeneration||o!==this.resetSequence)return!0;if(this.cacheGenerationClaim&&!await this.renewCacheClaim(n))return!1;if(t.lifecycleGeneration!==this.lifecycleGeneration||o!==this.resetSequence)return!0;if(c?.(),!t.bindKeySetEvidence||this.persistedKeySetEvidence?.status!==`incompatible`){for(let e of a)s.suppliedRowKeys.add(e.key);await g(this.applyRowsToCollection(a,l)),i!==void 0&&(this.publicRowVersion=Math.max(this.publicRowVersion,i))}}finally{this.activeHydrationContext===s&&this.hydratingGeneration===t.lifecycleGeneration&&(this.hydratingGeneration=null)}if(t.lifecycleGeneration!==this.lifecycleGeneration||(this.scopedRecoveryPending||(a=await this.flushQueuedHydrationTransactionsUnsafe(n)),t.lifecycleGeneration!==this.lifecycleGeneration))return!0}catch(e){if(t.requestLocalLoadFailure&&!r&&this.cacheGenerationClaim&&this.hasExpiredCacheClaim())return!1;if(t.requestLocalLoadFailure&&!r){if(this.scopedRecoveryPending)throw this.recoverQueuedAfterLocalLoadFailure=!0,e;this.hydratingGeneration=t.lifecycleGeneration;try{await this.recoverBufferedTransactionsAfterLocalLoadFailureUnsafe(t.lifecycleGeneration,n)}catch(e){throw this.markTerminalFailure(e,t.lifecycleGeneration)}finally{this.hydratingGeneration===t.lifecycleGeneration&&(this.hydratingGeneration=null)}throw e}throw this.markTerminalFailure(e,t.lifecycleGeneration)}finally{this.activeHydrationContext===s&&(this.activeHydrationContext=void 0)}if(a&&t.rejectBufferedReplayFailure)throw a.reason;return!0}async recoverBufferedTransactionsAfterLocalLoadFailureUnsafe(e,t){let n,r=new Map,i=!1;for(;this.queuedHydrationTransactions.length>0;){let a=this.queuedHydrationTransactions.shift();if(a)try{this.throwIfLifecycleReplaced(e);let o=new Map,s=new Map,c=a.truncate,l=e=>{let t=s.get(e);if(t!==void 0)return t;if(c)return s.set(e,`absent`),`absent`;let n=r.get(e);if(n!==void 0)return s.set(e,n),n;let a=this.collection?._hasHydratedKey(e)===!0?`present`:i?`absent`:`unknown`;return s.set(e,a),a};if(!a.signal?.aborted){for(let[r,i]of a.operations.entries()){let c=i.key;if(i.type===`update`&&a.partialUpdateOperationIndexes.has(r)&&l(c)===`unknown`){if(n===void 0){let r=this.scopedRecovery?void 0:await t.loadResumeSnapshot(this.storageTargetFor(),{requiredIndexSignatures:this.getRequiredIndexSignatures(),includeRows:!0,cacheGenerationClaimId:this.cacheGenerationClaim?.claimId});if(this.throwIfLifecycleReplaced(e),a.signal?.aborted)break;let i=r&&!this.scopedRecovery?r.rows:[];n=new Map(i.map(e=>[e.key,e]))}let r=n.get(c);r===void 0?s.set(c,`absent`):(o.set(c,r),s.set(c,`present`))}s.set(c,i.type===`delete`?`absent`:`present`)}o.size>0&&(a.signal?.aborted||a.prependHydrationRows([...o.values()]))}if((await this.applyBufferedSyncTransactionUnsafe(a,t)).applied){a.truncate&&(i=!0,r.clear());for(let e of a.operations)r.set(e.key,e.type===`delete`?`absent`:`present`)}}catch(e){a.rejectApplied?.(e);for(let t of this.queuedHydrationTransactions)t.rejectApplied?.(e);throw this.queuedHydrationTransactions.length=0,e}}}rejectQueuedHydrationTransactions(e){for(let t of this.queuedHydrationTransactions)t.rejectApplied?.(e);this.queuedHydrationTransactions.length=0}applyRowsToCollection(e,t,n){return!this.syncControls.begin||!this.syncControls.write||!this.syncControls.commit?!0:this.withInternalApply(()=>{if(this.syncControls.begin?.(),t){let e=new Map(t.map(e=>[e.key,e]));for(let t of this.collection?.base.keys()??[]){if(this.collection?._hasHydratedKey(t))continue;let n=e.get(t);if(!n)this.syncControls.write?.({type:`delete`,key:t});else{let e=!u(this.collection?.base.get(t),n.value),r=!u(this.syncControls.metadata?.row.get(t),n.metadata);(e||r&&n.metadata!==void 0)&&(e&&this.syncControls.write?.({type:`delete`,key:t}),this.syncControls.write?.({type:`update`,value:n.value,metadata:n.metadata})),r&&n.metadata===void 0&&this.syncControls.metadata?.row.delete(t)}}for(let e of this.collection?._syncedRowMetadataKeysOutsideBase()??[])this.syncControls.metadata?.row.delete(e)}for(let n of e)t&&this.collection?.base.has(n.key)||this.collection?._hasHydratedKey(n.key)||(this.collection?.base.has(n.key)&&!u(this.collection.base.get(n.key),n.value)&&this.syncControls.write?.({type:`delete`,key:n.key}),this.syncControls.write?.({type:`update`,value:n.value,metadata:n.metadata}));return n&&this.applyCollectionMetadataSnapshot(n),this.syncControls.commit?.()??!0})}getResumeSnapshotGeneration(e){return{latestTerm:e.latestTerm,latestSeq:e.latestSeq,latestRowVersion:e.latestRowVersion,resetEpoch:e.resetEpoch}}isExpectedResumeGeneration(e){let t=this.persistedResumeGeneration;return t!==void 0&&t.latestRowVersion===e.latestRowVersion&&t.resetEpoch===e.resetEpoch&&(t.latestTerm===e.latestTerm&&t.latestSeq===e.latestSeq||e.latestTerm>t.latestTerm&&e.latestSeq===0)}bindResumeSnapshotEvidence(e){let t=this.getResumeSnapshotGeneration(e),n=this.persistedKeySetEvidence?.status,r=this.mode===`sync-present`&&n!==`consistent`&&n!==`incompatible`||this.mode===`sync-absent`&&n===`consistent`&&e.keySet?.status===`consistent`;this.observeStreamPosition(e.latestTerm,e.latestSeq,e.latestRowVersion),this.persistedKeySetEvidence=this.isExpectedResumeGeneration(t)||r?e.keySet:{status:`incompatible`}}replaceCollectionSnapshot(e,t,n){if(!this.syncControls.begin||!this.syncControls.write||!this.syncControls.commit||!this.syncControls.metadata)return!0;let r=this.collection?.base,i=new Set(Array.from(r?.keys()??[]).filter(e=>this.collection?._hasHydratedKey(e)===!0)),a=new Set(e.map(e=>e.key)),o=this.canRouteRemoteDemandThroughCoordinator()&&!this.persistence.coordinator.isLeader(this.storageCollectionId),s=i.size===0&&(n||!o);return this.withInternalApply(()=>{if(this.syncControls.begin?.(),s)this.syncControls.truncate?.();else{for(let e of r?.keys()??[])!i.has(e)&&!a.has(e)&&this.syncControls.write?.({type:`delete`,key:e});for(let e of this.collection?._syncedRowMetadataKeysOutsideBase()??[])this.syncControls.metadata?.row.delete(e)}for(let t of e)i.has(t.key)||(!s&&r?.has(t.key)&&this.syncControls.write?.({type:`delete`,key:t.key}),this.syncControls.write?.({type:`update`,value:t.value,metadata:t.metadata}));return this.applyCollectionMetadataSnapshot(t),this.syncControls.commit?.()??!0})}matchesCollectionSnapshot(e,t){if(!this.collection||!this.syncControls.metadata)return!1;let n=this.collection.base;if(n.size!==e.size)return!1;for(let[t,r]of e)if(!n.has(t)||!u(n.get(t),r.value)||!u(this.syncControls.metadata.row.get(t),r.metadata))return!1;let r=this.syncControls.metadata.collection.list();if(r.length!==t.length)return!1;let i=new Map(t.map(({key:e,value:t})=>[e,t]));return r.every(({key:e,value:t})=>i.has(e)&&u(i.get(e),t))}async flushQueuedHydrationTransactionsUnsafe(e){let t;for(;this.queuedHydrationTransactions.length>0;){let n=this.queuedHydrationTransactions.shift();if(n)try{let r=await this.applyBufferedSyncTransactionUnsafe(n,e);t??=r.hydrationFailure}catch(e){n.rejectApplied?.(e);for(let t of this.queuedHydrationTransactions)t.rejectApplied?.(e);throw this.queuedHydrationTransactions.length=0,e}}return t}async applyBufferedSyncTransactionUnsafe(t,n){if(this.throwIfTerminal(),this.throwIfLifecycleReplaced(t.lifecycleGeneration),t.admittedStorageCollectionId!==void 0&&t.admittedStorageCollectionId!==this.storageCollectionId){let n=new e;if(!t.rejectApplied)throw n;return t.rejectApplied(n),{applied:!1}}if(!t.internal&&this.scopedRecoveryPending){let n=new e;if(!t.rejectApplied)throw n;return t.rejectApplied(n),{applied:!1}}if(!t.internal&&this.cacheGenerationClaim&&(n??this.persistence.adapter).renewCacheGenerationClaim&&!await this.renewCacheClaim(n??this.persistence.adapter)){let n=new e;if(queueMicrotask(()=>{t.lifecycleGeneration===this.lifecycleGeneration&&(this.scopedRecoveryPending||this.startScopedRecovery().catch(e=>{this.markTerminalFailure(e,t.lifecycleGeneration)}))}),!t.rejectApplied)throw n;return t.rejectApplied(n),{applied:!1}}let r=t.signal?.aborted===!0,i=!1,a=!1;try{let e=t.internal?this.withInternalApply(t.applyToCollection):t.applyToCollection();return a=!0,i=t.signal?.aborted===!0,t.internal?await g(e):e!==!0&&!this.collection?._state.hasPersistingTransaction()&&await e,this.throwIfLifecycleReplaced(t.lifecycleGeneration),t.internal||await this.persistAndBroadcastExternalSyncTransactionUnsafe(t,n),t.resolveApplied?.(),{applied:!0}}catch(n){a||(i=t.signal?.aborted===!0);let o=t.signal?.aborted||n instanceof e,s=o&&t.shouldFailStopOnAbort?.()===!0,c=this.classifyBufferedTransactionFailure(t,n);if(t.rejectApplied?.(c),o&&!s&&t.rejectApplied)return{applied:!1,hydrationFailure:!r&&i?{reason:c}:void 0};throw c}}classifyBufferedTransactionFailure(t,n){return n instanceof S?this.markTerminalFailure(n,t.lifecycleGeneration):(t.signal?.aborted||n instanceof e)&&t.shouldFailStopOnAbort?.()!==!0?n:this.markTerminalFailure(n,t.lifecycleGeneration)}async persistAndBroadcastExternalSyncTransactionUnsafe(e,t){if(e.internal||(this.throwIfLifecycleReplaced(e.lifecycleGeneration),!e.truncate&&e.operations.length===0&&e.rowMetadataWrites.size===0&&e.collectionMetadataWrites.size===0))return;let n=this.persistedResumeGeneration&&{latestRowVersion:this.latestRowVersion,resetEpoch:this.persistedResumeGeneration.resetEpoch},r=this.nextLocalStreamPosition(),i=this.createPersistedTxFromOperations(e,r),a=this.storageCollectionId,o;try{o=await this.persistence.coordinator.requestApplyCommittedTx(a,i,t)}catch(r){if(!(r instanceof C)||!n||!this.persistence.coordinator.reconcileCommittedTx)throw r;let o;try{o=await this.persistence.coordinator.reconcileCommittedTx(a,i,n,t)}catch(e){throw e instanceof S?e:r}if(!o.ok)throw o.code===`PERSISTENCE_ERROR`?new S(`Failed to reconcile collection "${this.collectionId}": ${o.error}`,{cause:o,code:o.sourceCode??o.code,path:o.path}):r;this.recordDurableSourceCommit(e,o.committed);return}if(!o.ok)throw o.code===`PERSISTENCE_ERROR`?new S(`Failed to durably persist collection "${this.collectionId}": ${o.error}`,{cause:o,code:o.sourceCode??o.code,path:o.path}):Error(`failed to apply external sync transaction through coordinator: ${o.error}`);this.recordDurableSourceCommit(e,{term:o.term,seq:o.seq,rowVersion:o.latestRowVersion})}recordDurableSourceCommit(e,t){e.lifecycleGeneration===this.lifecycleGeneration&&(this.observeStreamPosition(t.term,t.seq,t.rowVersion),t.rowVersion===this.publicRowVersion+1&&(this.publicRowVersion=t.rowVersion),e.expectedResumeGenerationOwner===this.resumeGenerationOwner&&this.persistedResumeGeneration!==void 0&&(this.persistedResumeGeneration={...this.persistedResumeGeneration,latestTerm:t.term,latestSeq:t.seq,latestRowVersion:t.rowVersion}))}async applyCommittedTx(e,t){this.throwIfTerminal(),this.throwIfLifecycleReplaced(t);try{await this.persistence.adapter.applyCommittedTx(this.storageTargetFor(),e)}catch(e){throw this.markTerminalFailure(re(this.collectionId,e),t)}this.throwIfLifecycleReplaced(t)}createPersistedTxFromOperations(e,t){return{txId:s(),term:t.term,seq:t.seq,rowVersion:t.rowVersion,cacheGenerationClaimId:this.cacheGenerationClaim?.claimId,truncate:e.truncate,mutations:e.operations.map(e=>e.type===`update`?{type:`update`,key:e.key,value:e.value}:{type:`delete`,key:e.key,value:e.value}),rowMetadataMutations:Array.from(e.rowMetadataWrites.entries()).map(([e,t])=>t.type===`delete`?{type:`delete`,key:e}:{type:`set`,key:e,value:t.value}),collectionMetadataMutations:Array.from(e.collectionMetadataWrites.entries()).map(([e,t])=>t.type===`delete`?{type:`delete`,key:e}:{type:`set`,key:e,value:t.value})}}createPersistedTxFromMutations(e,t){return{txId:s(),term:t.term,seq:t.seq,rowVersion:t.rowVersion,cacheGenerationClaimId:this.cacheGenerationClaim?.claimId,mutations:e.map(e=>e.type===`delete`?{type:`delete`,key:e.key,value:e.original}:e.type===`insert`?{type:`insert`,key:e.key,value:e.modified}:{type:`update`,key:e.key,value:e.modified})}}async confirmMutationsSyncUnsafe(e){if(!this.syncControls.begin||!this.syncControls.write||!this.syncControls.commit)return;let t=g(this.withInternalApply(()=>{this.syncControls.begin?.();for(let t of e)t.type===`delete`?this.syncControls.write?.({type:`delete`,key:t.key}):this.syncControls.write?.({type:`update`,value:t.modified});return this.syncControls.commit?.()??!0}));t!==!0&&await t}filterMutationsForCollection(e){let t=this.collection;return e.filter(e=>t?e.collection===t:e.collection.id===this.collectionId)}async persistCollectionMutationsUnsafe(e,t){if(this.throwIfLifecycleReplaced(t),this.persistence.coordinator.requestApplyLocalMutations){let n=this.storageTargetFor(),r=e.map(e=>gt(e)),i=await this.persistence.coordinator.requestApplyLocalMutations(this.storageCollectionId,r,n.kind===`managed`?n.claimId:void 0);if(this.throwIfLifecycleReplaced(t),!i.ok)throw i.code===`PERSISTENCE_ERROR`?new S(`Failed to durably persist collection "${this.collectionId}": ${i.error}`,{cause:i,code:i.sourceCode??i.code,path:i.path}):Error(`failed to apply local mutations through coordinator: ${i.error}`);this.observeStreamPosition(i.term,i.seq,i.latestRowVersion);let a=Array.from(new Set(i.acceptedMutationIds)),o=new Set(e.map(e=>e.mutationId));if(a.some(e=>!o.has(e)))throw Error(`persistence coordinator returned unknown mutation ids in applyLocalMutations response`);return a}let n=this.nextLocalStreamPosition(),r=this.createPersistedTxFromMutations(e,n);return await this.applyCommittedTx(r,t),this.throwIfLifecycleReplaced(t),this.publishTxCommittedEvent(this.createTxCommittedPayload({term:r.term,seq:r.seq,txId:r.txId,latestRowVersion:r.rowVersion,changedRows:e.filter(e=>e.type!==`delete`).map(e=>({key:e.key,value:e.modified})),deletedKeys:e.filter(e=>e.type===`delete`).map(e=>e.key),rowMetadataMutations:r.rowMetadataMutations,collectionMetadataMutations:r.collectionMetadataMutations})),e.map(e=>e.mutationId)}createTxCommittedPayload(e){let t=e.rowMetadataMutations??[],n=e.collectionMetadataMutations??[];return e.requiresFullReload===!0||e.changedRows.length+e.deletedKeys.length+t.length+n.length>Qe?{type:`tx:committed`,term:e.term,seq:e.seq,txId:e.txId,latestRowVersion:e.latestRowVersion,requiresFullReload:!0}:{type:`tx:committed`,term:e.term,seq:e.seq,txId:e.txId,latestRowVersion:e.latestRowVersion,requiresFullReload:!1,changedRows:e.changedRows,deletedKeys:e.deletedKeys,rowMetadataMutations:t,collectionMetadataMutations:n}}publishTxCommittedEvent(e){this.observeStreamPosition(e.term,e.seq,e.latestRowVersion);let t={v:1,dbName:this.dbName,collectionId:this.storageCollectionId,senderId:this.persistence.coordinator.getNodeId(),ts:Date.now(),payload:e};this.persistence.coordinator.publish(this.storageCollectionId,t)}observeStreamPosition(e,t,n){(e>this.latestTerm||e===this.latestTerm&&t>this.latestSeq)&&(this.latestTerm=e,this.latestSeq=t),n>this.latestRowVersion&&(this.latestRowVersion=n),e>this.localTerm?(this.localTerm=e,this.localSeq=t):e===this.localTerm&&t>this.localSeq&&(this.localSeq=t),n>this.localRowVersion&&(this.localRowVersion=n)}nextLocalStreamPosition(){return this.localTerm=Math.max(this.localTerm,this.latestTerm||1),this.localSeq=Math.max(this.localSeq,this.latestSeq)+1,this.localRowVersion=Math.max(this.localRowVersion,this.latestRowVersion)+1,{term:this.localTerm,seq:this.localSeq,rowVersion:this.localRowVersion}}getSubsetKey(e){let t=this.requestIds.get(e);return t===void 0&&(t=`request:${++this.nextRequestId}`,this.requestIds.set(e,t)),t}canRouteRemoteDemandThroughCoordinator(){return this.getCurrentTerminalFailure()||this.mode!==`sync-present`||this.persistence.coordinator instanceof tt?!1:!this.persistence.coordinator.isLeader(this.storageCollectionId)||this.remoteSubsetOwnerUnsubscribe!==null}queueRemoteSubsetEnsure(e){if(e.signal?.aborted||!this.canRouteRemoteDemandThroughCoordinator()||this.activeSubsets.get(this.getSubsetKey(e))!==e)return;let t=this.getSubsetKey(e);this.activeSubsets.get(t)===e&&(ge(e),this.pendingRemoteSubsetEnsures.set(t,e),this.flushPendingRemoteSubsetEnsures())}scheduleRemoteEnsureRetry(){this.getCurrentTerminalFailure()||this.mode!==`sync-present`||this.persistence.coordinator instanceof tt||this.pendingRemoteSubsetEnsures.size===0||this.remoteEnsureRetryTimer!==null||(this.remoteEnsureRetryTimer=setTimeout(()=>{this.remoteEnsureRetryTimer=null,this.flushPendingRemoteSubsetEnsures()},et))}async flushPendingRemoteSubsetEnsures(){if(!(this.getCurrentTerminalFailure()||this.mode!==`sync-present`||this.persistence.coordinator instanceof tt)){this.remoteEnsureRetryTimer!==null&&(clearTimeout(this.remoteEnsureRetryTimer),this.remoteEnsureRetryTimer=null);for(let[e,t]of this.pendingRemoteSubsetEnsures){if(t.signal?.aborted||this.activeSubsets.get(e)!==t){this.pendingRemoteSubsetEnsures.delete(e);continue}try{await this.persistence.coordinator.requestEnsureRemoteSubset(this.storageCollectionId,this.rotatedAcquisitions.get(t)??t),this.pendingRemoteSubsetEnsures.delete(e)}catch(n){t.signal?.aborted||this.activeSubsets.get(e)!==t?this.pendingRemoteSubsetEnsures.delete(e):console.warn(`Failed to ensure remote subset:`,n)}}this.scheduleRemoteEnsureRetry()}}attachCoordinatorSubscription(){this.coordinatorUnsubscribe||=(this.persistence.coordinator.setAdapterForCollection?.(this.storageCollectionId,this.persistence.adapter,this.cacheGenerationClaim?.claimId),this.persistence.coordinator.subscribe(this.storageCollectionId,e=>{this.onCoordinatorMessage(e)}))}onCoordinatorMessage(e){if(e.collectionId!==this.storageCollectionId||this.getCurrentTerminalFailure())return;let{payload:t}=e,n=this.lifecycleGeneration,r=e.senderId===this.persistence.coordinator.getNodeId(),i=this.hasExpiredCacheClaim();if(i&&!mt(t)){this.scheduleCacheClaimRecovery(n);return}if(mt(t)){this.queuedTxCommitted.push({txCommitted:t,lifecycleGeneration:n,storageCollectionId:e.collectionId}),i?this.scheduleCacheClaimRecovery(n):this.isHydratingNow()||this.applyMutex.run(()=>this.flushQueuedTxCommittedUnsafe()).catch(e=>{this.markTerminalFailure(e,n)});return}r||ht(t)&&this.applyMutex.run(async()=>{e.collectionId===this.storageCollectionId&&(await this.runInHydrationScope(async e=>{await this.truncateAndReloadUnsafe(e,n),await this.rebaseDurableStreamFromSnapshotUnsafe(e,n),n===this.lifecycleGeneration&&(this.publicRowVersion=0,this.resetTermFence=this.latestTerm)}),n===this.lifecycleGeneration&&await this.flushQueuedTxCommittedUnsafe())}).catch(e=>{this.markTerminalFailure(e,n)})}async flushQueuedTxCommittedUnsafe(){for(;this.queuedTxCommitted.length>0;){if(this.hasExpiredCacheClaim()){this.scheduleCacheClaimRecovery(this.lifecycleGeneration);return}let e=this.queuedTxCommitted.shift();if(e&&e.storageCollectionId===this.storageCollectionId)try{await this.processCommittedTxUnsafe(e.txCommitted,e.lifecycleGeneration)}catch(t){throw this.markTerminalFailure(t,e.lifecycleGeneration)}}}async processCommittedTxUnsafe(e,t=this.lifecycleGeneration){if(t!==this.lifecycleGeneration)return;if(this.resetTermFence!==void 0&&e.term<=this.resetTermFence){await this.runInHydrationScope(e=>this.reloadActiveSubsetsUnsafe(e));return}if(e.requiresFullReload&&e.reconciliationReload){await this.invalidateFromCommittedTxUnsafe(e,this.persistence.adapter),t===this.lifecycleGeneration&&(this.observeStreamPosition(e.term,e.seq,e.latestRowVersion),this.publicRowVersion=Math.max(this.publicRowVersion,e.latestRowVersion),await this.flushQueuedTxCommittedUnsafe());return}if(e.latestRowVersion<=this.publicRowVersion)return;let n=e.term<this.latestTerm||e.term===this.latestTerm&&e.seq<=this.latestSeq,r=e.term===this.latestTerm&&e.seq>this.latestSeq+1,i=e.term>this.latestTerm&&e.seq>1;(n||e.latestRowVersion>this.publicRowVersion+1||r||i)&&(!await this.recoverFromSeqGapUnsafe(t)||t!==this.lifecycleGeneration||e.latestRowVersion<=this.publicRowVersion)||(this.observeStreamPosition(e.term,e.seq,e.latestRowVersion),await this.invalidateFromCommittedTxUnsafe(e,this.persistence.adapter),t===this.lifecycleGeneration&&(this.publicRowVersion=Math.max(this.publicRowVersion,e.latestRowVersion),await this.flushQueuedTxCommittedUnsafe()))}async rebaseDurableStreamFromSnapshotUnsafe(e,t){if(t!==this.lifecycleGeneration)return;let n=await e.loadResumeSnapshot(this.storageTargetFor(),{includeRows:!1,cacheGenerationClaimId:this.cacheGenerationClaim?.claimId});t===this.lifecycleGeneration&&(this.latestRowVersion=n.latestRowVersion,this.localRowVersion=n.latestRowVersion,this.observeStreamPosition(n.latestTerm,n.latestSeq,n.latestRowVersion))}async recoverFromSeqGapUnsafe(e){if(e!==this.lifecycleGeneration)return!1;if(this.persistence.coordinator.pullSince&&this.latestRowVersion>=0){let t;try{t=await this.persistence.coordinator.pullSince(this.storageCollectionId,this.publicRowVersion,void 0,this.cacheGenerationClaim?.claimId)}catch(e){console.warn(`Failed pullSince recovery attempt:`,e)}if(this.scopedRecoveryPending)return!1;if(this.cacheGenerationClaim&&!await this.renewCacheClaim(this.persistence.adapter))return this.scheduleCacheClaimRecovery(e),!1;if(t){if(e!==this.lifecycleGeneration)return!1;if(t.ok){if(this.observeStreamPosition(t.latestTerm,t.latestSeq,t.latestRowVersion),t.requiresFullReload)return await this.runInHydrationScope(e=>this.reloadActiveSubsetsUnsafe(e)),this.publicRowVersion=Math.max(this.publicRowVersion,t.latestRowVersion),!0;let n=t.deltas;return n?(await this.runInHydrationScope(async r=>{for(let i of n)if(e!==this.lifecycleGeneration||(await this.invalidateFromCommittedTxUnsafe({type:`tx:committed`,term:t.latestTerm,seq:t.latestSeq,txId:i.txId,latestRowVersion:i.latestRowVersion,requiresFullReload:!1,changedRows:i.changedRows,deletedKeys:i.deletedKeys,rowMetadataMutations:i.rowMetadataMutations,collectionMetadataMutations:i.collectionMetadataMutations},r),e!==this.lifecycleGeneration))return}),this.publicRowVersion=Math.max(this.publicRowVersion,t.latestRowVersion),!0):(await this.runInHydrationScope(e=>this.reloadActiveSubsetsUnsafe(e)),this.publicRowVersion=Math.max(this.publicRowVersion,t.latestRowVersion),!0)}}}if(e!==this.lifecycleGeneration)return!1;if(await this.runInHydrationScope(e=>this.reloadActiveSubsetsUnsafe(e)),this.publicRowVersion=Math.max(this.publicRowVersion,this.latestRowVersion),this.mode===`sync-present`)for(let e of this.activeSubsets.values())this.queueRemoteSubsetEnsure(e);return!0}refreshScopedSubsets(){if(!this.remoteSubsetOwner)return;let e=this.lifecycleGeneration,t=this.storageCollectionId;for(let[n,r]of this.activeSubsets){if(r.signal?.aborted)continue;this.hydratedDemands.delete(d(r));let i={...r,refetch:!0};this.scopedRefreshes.set(i,t),Promise.resolve().then(()=>{if(!(e!==this.lifecycleGeneration||this.activeSubsets.get(n)!==r))return this.persistence.coordinator.requestEnsureRemoteSubset(t,i)}).catch(t=>{e===this.lifecycleGeneration&&!r.signal?.aborted&&this.reportSyncError(t)}).finally(()=>{this.scopedRefreshes.delete(i)&&this.persistence.coordinator.requestReleaseRemoteSubset(t,i).catch(t=>{e===this.lifecycleGeneration&&this.reportSyncError(t)})})}}async truncateAndReloadUnsafe(e,t=this.lifecycleGeneration){if(t===this.lifecycleGeneration){if(this.scopedRecovery){this.refreshScopedSubsets();return}this.hydratedDemands.clear(),this.resetSequence++,this.syncMode===`eager`&&this.syncControls.begin&&this.syncControls.commit&&await g(this.withInternalApply(()=>(this.syncControls.begin?.(),this.syncControls.truncate?.(),this.syncControls.commit?.()??!0))),t===this.lifecycleGeneration&&await this.reloadActiveSubsetsUnsafe(e,!1,this.syncMode===`eager`,!0)}}async invalidateFromCommittedTxUnsafe(e,t){if(this.scopedRecovery){this.refreshScopedSubsets();return}let n=(e=!1)=>this.runInHydrationScope(t=>this.reloadActiveSubsetsUnsafe(t,e),t);if(e.requiresFullReload){await n(e.reconciliationReload===!0);return}let r=e.changedRows.length+e.deletedKeys.length;if(r>Qe){await n();return}let i=Array.from(this.activeSubsets.values()).some(e=>e.limit!=null||e.offset!=null||e.cursor!=null),a=new Set(e.changedRows.map(e=>e.key)),o=a.size!==e.changedRows.length,s=e.deletedKeys.some(e=>a.has(e)),c=e.changedRows.some(e=>this.collection?.base.has(e.key)),l=this.activeSubsets.size>0&&e.changedRows.some(e=>!this.collection?.base.has(e.key)&&!this.collection?._hasHydratedKey(e.key));if(o||s||c||this.syncMode===`on-demand`&&l){await n();return}if(!i||r===0){await this.applyTargetedInvalidationUnsafe(e);return}await n()}async applyTargetedInvalidationUnsafe(e){let t=Array.from(this.activeSubsets.values()).map(e=>e.where?_(e.where):null);await g(this.withInternalApply(()=>{this.syncControls.begin?.();for(let{key:n,value:r}of e.changedRows){let e=n;if(this.collection?._hasHydratedKey(e))continue;let i=this.collection?.base.get(e);if(i===void 0&&this.activeSubsets.size===0)continue;let a={...i,...r},o=dt(a,t),s=i!==void 0&&!dt(i,t);o||s?this.syncControls.write?.({type:`update`,value:a}):i!==void 0&&this.syncControls.write?.({type:`delete`,key:e})}for(let t of e.deletedKeys){let e=t;this.collection?._hasHydratedKey(e)||this.syncControls.write?.({type:`delete`,key:e})}return e.rowMetadataMutations?.forEach(e=>{this.collection?._hasHydratedKey(e.key)||(e.type===`delete`?this.syncControls.metadata?.row.delete(e.key):this.syncControls.metadata?.row.set(e.key,e.value))}),e.collectionMetadataMutations?.forEach(e=>{e.type===`delete`?this.syncControls.metadata?.collection.delete(e.key):this.syncControls.metadata?.collection.set(e.key,e.value)}),this.syncControls.commit?.()??!0}))}async reloadActiveSubsetsUnsafe(e,t=!1,n=!1,r=!1){if(this.scopedRecovery){this.refreshScopedSubsets();return}let i=this.lifecycleGeneration,a=this.sourceTruncateGeneration,o=Array.from(this.activeSubsets.values());n&&o.length===0&&o.push({});let s=o.map(e=>e.where?_(e.where):null),c=o.some(e=>e.limit!=null||e.offset!=null||e.cursor!=null)?[]:Array.from(this.collection?.base??[]).filter(([e,t])=>!this.collection?._hasHydratedKey(e)&&!dt(t,s)).map(([e])=>e);this.hydratedDemands.clear(),this.hydrationSequence++;let l={suppliedRowKeys:new Set};this.activeHydrationContext=l,this.hydratingGeneration=i;try{let n=new Map,a,s=[];try{if(a=(o.length===0||c.length>0)&&this.collection?.base.size?await e.loadResumeSnapshot(this.storageTargetFor(),{requiredIndexSignatures:this.getRequiredIndexSignatures(),includeRows:!0,cacheGenerationClaimId:this.cacheGenerationClaim?.claimId}):void 0,s=a?a.collectionMetadata:await this.loadCollectionMetadataSnapshot(e),i!==this.lifecycleGeneration)return;for(let t of o){let r=await this.loadSubsetRowsUnsafe(t,e);if(i!==this.lifecycleGeneration)return;for(let e of r)n.set(e.key,{value:e.value,metadata:e.metadata})}if(c.length>0&&a){let e=new Map(a.rows.map(e=>[e.key,e]));for(let t of c){if(n.has(t))continue;let r=e.get(t);r&&n.set(t,{value:r.value,metadata:r.metadata})}}}catch(e){if(this.scopedRecovery)return;if(!this.cacheGenerationClaim||!this.hasExpiredCacheClaim())throw e;this.scheduleCacheClaimRecovery(i);return}if(this.isScopedRecoveryPending())return;if(this.cacheGenerationClaim&&!await this.renewCacheClaim(e)){this.scheduleCacheClaimRecovery(i);return}if(this.isScopedRecoveryPending()||i!==this.lifecycleGeneration)return;for(let e of n.keys())l.suppliedRowKeys.add(e);if(o.length===0)await g(this.applyRowsToCollection([],a?.rows??[],s));else if(t&&this.matchesCollectionSnapshot(n,s)){let e=this.collection?._syncedRowMetadataKeysOutsideBase()??[];e.length>0&&await g(this.withInternalApply(()=>{this.syncControls.begin?.();for(let t of e)this.syncControls.metadata?.row.delete(t);return this.syncControls.commit?.()??!0}))}else await g(this.replaceCollectionSnapshot(Array.from(n.entries()).map(([e,t])=>({key:e,value:t.value,metadata:t.metadata})),s,r))}finally{this.activeHydrationContext===l&&this.hydratingGeneration===i&&(this.hydratingGeneration=null),this.activeHydrationContext===l&&(this.activeHydrationContext=void 0)}if(i===this.lifecycleGeneration&&(await this.flushQueuedHydrationTransactionsUnsafe(e),a===this.sourceTruncateGeneration&&this.queuedTxCommitted.length===0))for(let e of o)this.activeSubsets.get(this.getSubsetKey(e))===e&&this.hydratedDemands.add(d(e))}attachIndexLifecycleListeners(){!this.collection||this.indexAddedUnsubscribe||this.indexRemovedUnsubscribe||(this.indexAddedUnsubscribe=this.collection.on(`index:added`,e=>{this.ensurePersistedIndex(e.index).catch(e=>{console.warn(`Failed to ensure persisted index after index:added:`,e)})}),this.indexRemovedUnsubscribe=this.collection.on(`index:removed`,e=>{this.markIndexRemoved(e.index)}))}async bootstrapPersistedIndexes(e,t=this.persistence.adapter){let n=this.collection;if(!n&&!e)return new Set;let r=e??n?.getIndexMetadata()??[],i=new Set,a=this.lifecycleGeneration;for(let e of r){let n=this.storageCollectionId,r=this.cacheGenerationClaim?.claimId;await this.ensureLocalPersistedIndex(e,t)&&await this.reconcilePersistedIndex(e,t,n,r,a,!0)&&i.add(e.signature)}return i}async requestCoordinatorPersistedIndexes(e,t){let n=this.lifecycleGeneration;for(let r of e){if(!this.hasCurrentIndex(r))continue;let e=this.storageCollectionId,i=this.cacheGenerationClaim?.claimId;await this.requestCoordinatorPersistedIndex(r,t.has(r.signature)),await this.reconcilePersistedIndex(r,this.persistence.adapter,e,i,n,!0)}}async reconcilePersistedIndex(e,t,n,r,i,a){for(;i===this.lifecycleGeneration&&n===this.storageCollectionId;){let i=this.hasCurrentIndex(e);if(i===a)return i;if(i){if(!await this.ensureLocalPersistedIndex(e,t))return!1}else{if(!t.markIndexRemoved)return!1;try{await t.markIndexRemoved(this.storageTargetFor(n,r),e.signature,{cacheGenerationClaimId:r})}catch(e){return console.warn(`Failed to mark persisted index removed:`,e),!1}}a=i}return!1}buildPersistedIndexSpec(e){return{expressionSql:[ft(e.expression)],metadata:{name:e.name??null,resolver:K(e.resolver),options:K(e.options)}}}async ensurePersistedIndex(e,t=this.persistence.adapter){if(this.scopedRecoveryPending)return;let n=this.lifecycleGeneration;if(await this.ensureCacheClaimActive(),n!==this.lifecycleGeneration||!this.hasCurrentIndex(e))return;let r=await this.ensureLocalPersistedIndex(e,t);if(n===this.lifecycleGeneration){if(!this.hasCurrentIndex(e)){await this.markIndexRemoved(e);return}await this.requestCoordinatorPersistedIndex(e,r),n===this.lifecycleGeneration&&!this.hasCurrentIndex(e)&&await this.markIndexRemoved(e)}}hasCurrentIndex(e){return this.collection?.getIndexMetadata().some(t=>t.signature===e.signature)??!1}async ensureLocalPersistedIndex(e,t){try{let n=this.buildPersistedIndexSpec(e);return await t.ensureIndex(this.storageTargetFor(),e.signature,n,{cacheGenerationClaimId:this.cacheGenerationClaim?.claimId}),!0}catch(e){return console.warn(`Failed to ensure persisted index in adapter:`,e),!1}}async requestCoordinatorPersistedIndex(e,t){try{let n=this.buildPersistedIndexSpec(e);await this.persistence.coordinator.requestEnsurePersistedIndex(this.storageCollectionId,e.signature,n,t?this.persistence.adapter:void 0,t,this.cacheGenerationClaim?.claimId)}catch(e){console.warn(`Failed to ensure persisted index through coordinator:`,e)}}async markIndexRemoved(e){if(this.persistence.adapter.markIndexRemoved)try{if(this.scopedRecoveryPending)return;let t=this.lifecycleGeneration;if(await this.ensureCacheClaimActive(),t!==this.lifecycleGeneration||this.hasCurrentIndex(e))return;await this.persistence.adapter.markIndexRemoved(this.storageTargetFor(),e.signature,{cacheGenerationClaimId:this.cacheGenerationClaim?.claimId}),t===this.lifecycleGeneration&&this.hasCurrentIndex(e)&&await this.ensurePersistedIndex(e)}catch(e){console.warn(`Failed to mark persisted index removed:`,e)}}};function vt(t,n,r){return{...t,sync:i=>{let a=[],s=[],c=()=>a[a.length-1],l=(e,t)=>{let n=e.publicationAdmissionWaiters;if(e.publicationAdmissionWaiters=void 0,n)for(let e of n)t===void 0?e.resolve():e.reject(t)},u=e=>{if(e.internal||!n.isHydratingNow())return;let t=n.getHydrationSequence();if(e.hydrationSequence!==void 0&&e.hydrationSequence!==t)throw new y(`a persisted sync transaction cannot cross a hydration cycle`);e.queuedBecauseHydrating=!0,e.hydrationSequence=t,e.hydrationContext=n.getActiveHydrationContext()},d=e=>{if(e.hydrationSequence!==void 0&&e.hydrationSequence!==n.getHydrationSequence())throw new y(`a persisted sync transaction cannot cross a hydration cycle`)},f=e=>{let t=c();t&&!t.internal&&(e.hasDependentSuccessor=!0)},m=e=>{let t=s.indexOf(e);t!==-1&&s.splice(t,1)},h=e=>{m(e)},g=(e,t)=>{let n=t.then(async()=>{let t=e.applicationReceipt;t!==void 0&&t!==!0&&await t});return n.catch(()=>void 0),te(n,t)},_=(e,t)=>{t.then(()=>h(e),()=>{h(e)})},v=e=>{for(let t=s.length-1;t>=0;t--){let n=s[t],r=n.rowMetadataWrites.get(e);if(r)return f(n),{found:!0,write:r};if(n.truncate)return f(n),{found:!0,write:{type:`delete`}}}return{found:!1}},ne=e=>{for(let t=s.length-1;t>=0;t--){let n=s[t],r=n.collectionMetadataWrites.get(e);if(r)return f(n),{found:!0,write:r}}return{found:!1}},b=null,x=null,S,re=new Promise(e=>{S=e}),C={cleanedUp:!1},ie=()=>C.cleanedUp,w=new Map,T=(t,n,r)=>n.signal?.aborted?Promise.reject(n.signal.reason??new e):new Promise((i,a)=>{let o=t.publicationAdmissionWaiters??=new Set,s=!1,c=e=>{s||(s=!0,o.delete(l),n.signal?.removeEventListener(`abort`,u),r.cancelAdmissionWait=void 0,e())},l={resolve:()=>c(i),reject:e=>c(()=>a(e))},u=()=>l.reject(n.signal?.reason??new e);o.add(l),n.signal?.addEventListener(`abort`,u,{once:!0}),r.cancelAdmissionWait=l.resolve}),E=()=>n.getCurrentTerminalFailure(),ae=e=>{if(r?.getSnapshot().status!==`loading`){n.reportSyncError(e);return}(b??n.ensureStarted()).then(()=>{!ie()&&!E()&&n.reportSyncError(e)},()=>void 0)},oe=e=>{let t=Promise.reject(e);return t.catch(()=>void 0),t},D=(e,t)=>{if(e.applicationReceipt!==void 0)return e.applicationReceipt;try{d(e);for(let t of e.deferredHydrationMetadataDeleteKeys)!e.hydrationContext?.suppliedRowKeys.has(t)&&!e.rowMetadataWrites.has(t)&&e.rowMetadataWrites.set(t,{type:`delete`});e.deferredHydrationMetadataDeleteKeys.clear(),i.begin(),e.truncate&&i.truncate();for(let t of e.operations)t.type===`delete`?i.write({type:`delete`,key:t.key}):i.write({type:`update`,value:t.value,metadata:t.metadata});if(i.metadata){for(let[t,n]of e.rowMetadataWrites)n.type===`delete`?i.metadata.row.delete(t):i.metadata.row.set(t,n.value);for(let[t,n]of e.collectionMetadataWrites)n.type===`delete`?i.metadata.collection.delete(t):i.metadata.collection.set(t,n.value)}let n=i.commit(t);return e.applicationReceipt=n,m(e),n!==!0&&n.catch(()=>void 0),n}catch(t){throw m(e),t}};n.setCollection(i.collection,{begin:i.begin,write:i.write,commit:i.commit,truncate:i.truncate,metadata:i.metadata??null,markError:i.markError});let se={protocol:ee,version:1,get managedCacheGeneration(){return n.hasManagedCacheGeneration()},get startupCacheGenerationRotated(){return n.hasRotatedStartupCacheGeneration()},reserveCommitTurn:()=>{let e=c();e&&!e.internal&&(e.reservesCommitTurn=!0)},hydrateBaseline:async()=>{if(!C.cleanedUp)try{await n.ensureResumeBaselineHydrated()}catch(e){throw n.reportSyncError(e)}},startScopedRecovery:e=>C.cleanedUp?Promise.resolve():n.startScopedRecovery(e),scanPersistedRows:e=>C.cleanedUp?Promise.resolve([]):n.scanPersistedRows(e),resumeSnapshot:{certify:async()=>{if(!C.cleanedUp)try{await n.ensureResumeBaselineCertified()}catch(e){throw n.reportSyncError(e)}},getKeySetEvidence:()=>C.cleanedUp?void 0:n.getKeySetEvidence(),expectCurrentCommit:()=>{if(C.cleanedUp)return;let e=c();if(!e)throw new y(`resumeSnapshot.expectCurrentCommit must be called within an open sync transaction`);e.expectedResumeGenerationOwner=n.getResumeGenerationOwner()}}},ce=0,O={...i,markError:ae,markReady:()=>{C.cleanedUp||E()||(b??n.ensureStarted()).then(async()=>{if(!(ie()||E())){await re;try{await x}catch(e){ae(e);return}ie()||E()||i.markReady()}}).catch(()=>void 0)},begin:()=>{if(C.cleanedUp)return;let e=E(),t=n.isApplyingInternally(),r={operations:[],partialUpdateOperationIndexes:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,deferredHydrationMetadataDeleteKeys:new Set,truncate:!1,internal:t,lifecycleGeneration:n.getLifecycleGeneration(),operationKeys:new Set,hasDependentSuccessor:!1,queuedBecauseHydrating:e===void 0&&!t&&n.isHydratingNow(),hydrationSequence:e===void 0&&!t?n.getHydrationSequence():void 0,hydrationContext:e===void 0&&!t&&n.isHydratingNow()?n.getActiveHydrationContext():void 0,...e===void 0?{}:{terminalFailure:e}};a.push(r)},write:e=>{if(C.cleanedUp)return;let r=c(),i=r?.terminalFailure??E();if(i){r&&(r.terminalFailure=i);return}if(!r)throw new p;u(r);let a=n.normalizeSyncWriteMessage(e);if(e.type===`update`&&t.rowUpdateMode!==`full`){r.internal||r.partialUpdateOperationIndexes.add(r.operations.length);for(let e of s)(e.truncate||e.operationKeys.has(a.operation.key))&&f(e)}r.operations.push(a.operation),r.operationKeys.add(a.operation.key),a.operation.type===`delete`?r.rowMetadataWrites.set(a.operation.key,{type:`delete`}):e.type===`insert`&&a.operation.metadata===void 0?r.queuedBecauseHydrating?r.deferredHydrationMetadataDeleteKeys.add(a.operation.key):r.rowMetadataWrites.has(a.operation.key)||r.rowMetadataWrites.set(a.operation.key,{type:`delete`}):a.operation.metadata!==void 0&&r.rowMetadataWrites.set(a.operation.key,{type:`set`,value:a.operation.metadata})},metadata:i.metadata?{persistence:se,row:{get:e=>{if(C.cleanedUp)return;let t=c(),n=t?.rowMetadataWrites.get(e);if(n)return n.type===`delete`?void 0:n.value;if(t?.truncate)return;let r=v(e);return r.found?r.write.type===`delete`?void 0:r.write.value:i.metadata.row.get(e)},set:(e,t)=>{if(C.cleanedUp)return;let n=c();if(!(n?.terminalFailure??E())){if(!n)throw new y(`metadata.row.set must be called within an open sync transaction`);n.rowMetadataWrites.set(e,{type:`set`,value:t})}},delete:e=>{if(C.cleanedUp)return;let t=c();if(!(t?.terminalFailure??E())){if(!t)throw new y(`metadata.row.delete must be called within an open sync transaction`);t.rowMetadataWrites.set(e,{type:`delete`})}}},collection:{get:e=>{if(C.cleanedUp)return;let t=c()?.collectionMetadataWrites.get(e);if(t)return t.type===`delete`?void 0:t.value;let n=ne(e);return n.found?n.write.type===`delete`?void 0:n.write.value:i.metadata.collection.get(e)},set:(e,t)=>{if(C.cleanedUp)return;let n=c();if(!(n?.terminalFailure??E())){if(!n)throw new y(`metadata.collection.set must be called within an open sync transaction`);n.collectionMetadataWrites.set(e,{type:`set`,value:t})}},delete:e=>{if(C.cleanedUp)return;let t=c();if(!(t?.terminalFailure??E())){if(!t)throw new y(`metadata.collection.delete must be called within an open sync transaction`);t.collectionMetadataWrites.set(e,{type:`delete`})}},list:e=>{if(C.cleanedUp)return[];let t=new Map(i.metadata.collection.list().map(({key:e,value:t})=>[e,t])),n=new Map;for(let r of s)for(let[i,a]of r.collectionMetadataWrites)(!e||i.startsWith(e))&&n.set(i,r),a.type===`delete`?t.delete(i):t.set(i,a.value);for(let e of new Set(n.values()))f(e);let r=c();if(r)for(let[e,n]of r.collectionMetadataWrites)n.type===`delete`?t.delete(e):t.set(e,n.value);return Array.from(t.entries()).filter(([t])=>e?t.startsWith(e):!0).map(([e,t])=>({key:e,value:t}))}}}:void 0,truncate:()=>{if(C.cleanedUp)return;n.noteSourceTruncate();let e=c();if(!(e?.terminalFailure??E())){if(!e)throw new p;e.operations=[],e.operationKeys.clear(),e.partialUpdateOperationIndexes.clear(),e.rowMetadataWrites.clear(),e.deferredHydrationMetadataDeleteKeys.clear(),e.truncate=!0}},commit:t=>{if(C.cleanedUp)return!0;let r=a.pop(),i=r?.terminalFailure??E();if(i)return r&&(h(r),l(r,i.error)),oe(i.error);if(!r)throw new o;if(r.internal)return D(r,t);if(t?.aborted){h(r);let t=new e;return l(r,t),oe(t)}if(n.isScopedRecoveryPending()){h(r);let t=new e;return l(r,t),oe(t)}try{u(r),d(r)}catch(e){throw l(r,e),e}let c={operations:r.operations,partialUpdateOperationIndexes:r.partialUpdateOperationIndexes,rowMetadataWrites:r.rowMetadataWrites,collectionMetadataWrites:r.collectionMetadataWrites,deferredHydrationMetadataDeleteKeys:r.deferredHydrationMetadataDeleteKeys,hydrationContext:r.hydrationContext,hydrationSequence:r.hydrationSequence,truncate:r.truncate,internal:!1,lifecycleGeneration:r.lifecycleGeneration,expectedResumeGenerationOwner:r.expectedResumeGenerationOwner,signal:t,prependHydrationRows:e=>{r.operations=e.map(({key:e,value:t,metadata:n})=>({type:`update`,key:e,value:t,metadata:n})).concat(r.operations);for(let{key:t,metadata:n}of e)n!==void 0&&!r.rowMetadataWrites.has(t)&&r.rowMetadataWrites.set(t,{type:`set`,value:n})},applyToCollection:()=>D(r,t),shouldFailStopOnAbort:()=>r.hasDependentSuccessor};if(r.signal=t,s.push(r),r.queuedBecauseHydrating&&n.isHydratingNow()){let e,t,i=new Promise((n,r)=>{e=n,t=r});return i.catch(()=>void 0),n.queueHydrationBufferedTransaction({...c,resolveApplied:e,rejectApplied:t}),l(r),_(r,i),g(r,i)}r.hydrationSequence=void 0;let f;try{f=n.applyHydrationBufferedTransaction(c)}catch(e){throw l(r,e),e}return l(r),_(r,f),g(r,f)}},k=e=>{let t=()=>!C.cleanedUp&&e===ce,n=O.metadata;return{...O,markReady:()=>{t()&&O.markReady()},markError:e=>{t()&&O.markError(e)},begin:()=>{t()&&O.begin()},write:e=>{t()&&O.write(e)},truncate:()=>{t()&&O.truncate()},commit:e=>t()?O.commit(e):!0,metadata:n&&{...n,row:{get:e=>t()?n.row.get(e):void 0,set:(e,r)=>{t()&&n.row.set(e,r)},delete:e=>{t()&&n.row.delete(e)}},collection:{get:e=>t()?n.collection.get(e):void 0,set:(e,r)=>{t()&&n.collection.set(e,r)},delete:e=>{t()&&n.collection.delete(e)},list:e=>t()?n.collection.list(e):[]},persistence:{...n.persistence,reserveCommitTurn:()=>{t()&&n.persistence.reserveCommitTurn()},hydrateBaseline:()=>t()?n.persistence.hydrateBaseline():Promise.resolve(),startScopedRecovery:e=>t()?n.persistence.startScopedRecovery?.(e)??Promise.resolve():Promise.resolve(),scanPersistedRows:e=>t()?n.persistence.scanPersistedRows(e):Promise.resolve([]),resumeSnapshot:{certify:()=>t()?n.persistence.resumeSnapshot.certify():Promise.resolve(),getKeySetEvidence:()=>t()?n.persistence.resumeSnapshot.getKeySetEvidence():void 0,expectCurrentCommit:()=>{t()&&n.persistence.resumeSnapshot.expectCurrentCommit()}}}}}},A={},le=!1,j,M,ue=0,N=()=>{let e=++ce,r;j=new Promise(e=>{r=e});try{if(A=pt(t.sync(n.hasManagedCacheGeneration()?k(e):O)),!C.cleanedUp&&A.loadSubset){let t=A;n.registerRemoteSubsetOwner(Object.assign(async n=>{if(C.cleanedUp||e!==ce)throw Error(`persisted sync source is no longer active`);await t.loadSubset?.(n)},{unloadSubset:e=>t.unloadSubset?.(e),onError:t=>{e===ce&&ae(t)}}))}}finally{j=void 0,r()}},de=t=>{let r=++ue;if(!M){ce++;let t=new e;for(let e of a)l(e,t);a.length=0;let n=A;M=Promise.resolve().then(()=>n.cleanup?.())}return Promise.all([M,t]).then(()=>{C.cleanedUp||r!==ue||(M=void 0,N(),n.setSourceRestartAfterScopedRecovery(A.restartAfterScopedRecovery??(n.hasManagedCacheGeneration()?de:void 0)))})};return b=n.ensureStarted(),b.catch(()=>void 0),x=(async()=>(await n.ensureStartupMetadataLoaded(),C.cleanedUp?(le=!0,A):(N(),le=!0,n.setSourceRestartAfterScopedRecovery(A.restartAfterScopedRecovery??(n.hasManagedCacheGeneration()?de:void 0)),A)))(),S(),x.catch(e=>{ae(e)}),{cleanup:async()=>{C.cleanedUp=!0,n.clearSourceRestartAfterScopedRecovery();let t=j,r=new e;for(let e of w.values())e.cancelAdmissionWait?.();w.clear(),s.length=0;for(let e of a)l(e,r);a.length=0;let i;try{i=M??(t?t.then(()=>A.cleanup?.()):Promise.resolve(A.cleanup?.()))}catch(e){i=Promise.reject(e)}let o;try{o=n.cleanup()}catch(e){o=Promise.reject(e)}let[c,u]=await Promise.allSettled([i,o]);if(c.status===`rejected`&&u.status===`rejected`)throw AggregateError([c.reason,u.reason],`Source cleanup and persistence runtime teardown both failed`,{cause:c.reason});if(c.status===`rejected`)throw c.reason;if(u.status===`rejected`)throw u.reason},loadSubset:t=>{let r={forwarded:!1};w.set(t,r);let i=e=>{if(C.cleanedUp||w.get(t)!==r)return!0;let n=A;if(!n.loadSubset)return!0;r.forwarded=!0,r.source=n;try{return n.loadSubset(e)}catch(e){throw r.forwarded=!1,r.source=void 0,e}},a=c()?.reservesCommitTurn===!0,o=!1,s=(n,i=()=>!0)=>{let a=t.signal;return(a?new Promise((t,r)=>{let o=()=>a.reason??new e,s=()=>{i()&&r(o())};a.addEventListener(`abort`,s,{once:!0}),a.aborted&&s(),n.then(()=>{a.removeEventListener(`abort`,s),a.aborted?r(o()):t()},e=>{a.removeEventListener(`abort`,s),r(a.aborted?o():e)})}):n).catch(e=>{if(!(C.cleanedUp||w.get(t)!==r))throw e})},l=le&&!a?n.loadHydratedSubset(t,e=>i(e)):void 0;return l===void 0?s((async()=>{if(await b,await x,C.cleanedUp||w.get(t)!==r)return;let e=c();if(e?.reservesCommitTurn&&await T(e,t,r),!(t.signal?.aborted||w.get(t)!==r))return n.loadSubset(t,e=>i(e),()=>{o=!0},()=>!C.cleanedUp&&w.get(t)===r)})(),()=>!o):l===!0?!0:s(l)},unloadSubset:e=>{let t=w.get(e);t?.cancelAdmissionWait?.(),w.delete(e),n.unloadSubset(e,t?.forwarded?t.source?.unloadSubset:void 0)}}}}}function yt(e){return{sync:t=>(e.setCollection(t.collection,{begin:t.begin,write:t.write,commit:t.commit,truncate:t.truncate,metadata:t.metadata??null,markError:t.markError}),e.ensureStarted().then(()=>{e.getCurrentTerminalFailure()||t.markReady()}).catch(()=>void 0),{loadSubset:t=>e.loadHydratedSubset(t)??e.loadSubset(t),cleanup:()=>e.cleanup(),unloadSubset:t=>e.unloadSubset(t)}),getSyncMetadata:()=>({source:`persisted-phase-2-loopback`})}}function bt(e){if(!ct(e.persistence))throw new y(`persistedCollectionOptions requires a persistence adapter`);let t=Ye(e.initialRender);if(t!==void 0&&e.syncMode===`on-demand`)throw new y(`network-first initial rendering requires eager persistence syncMode`);let n=t===void 0?void 0:new Ge(t),r=!1,i,a=()=>{if(r)throw new y(`Persisted options can create only one Collection. Create fresh options for each Collection.`);return r=!0,()=>{i?.hasBoundCollection()||(r=!1)}};if(st(e)){if(!lt(e.sync))throw new ne(`when the "sync" key is present it must provide a callable sync function`);let{schemaVersion:t,initialRender:r,...o}=e,c=o.id??`persisted-collection:${s()}`,l=ot(o.persistence,{collectionId:c,mode:`sync-present`,schemaVersion:t}),u=new _t(`sync-present`,c,l,o.syncMode??`eager`,c,n,a);return i=u,m({...o,id:c,sync:vt(o.sync,u,n),persistence:l,...n?{[h]:n}:{}},()=>bt({...e,id:c}),a)}let{schemaVersion:o,initialRender:c,...l}=e,u=l.id??`persisted-collection:${s()}`,d=ot(l.persistence,{collectionId:u,mode:`sync-absent`,schemaVersion:o}),f=new _t(`sync-absent`,u,d,l.syncMode??`eager`,l.id??$e,n,a);i=f;let p=async e=>{let t=f.getLifecycleGeneration(),n=l.onInsert?await l.onInsert(e):void 0;return await f.persistAndConfirmCollectionMutations(e.transaction.mutations,t),n??{}},ee=async e=>{let t=f.getLifecycleGeneration(),n=l.onUpdate?await l.onUpdate(e):void 0;return await f.persistAndConfirmCollectionMutations(e.transaction.mutations,t),n??{}},g=async e=>{let t=f.getLifecycleGeneration(),n=l.onDelete?await l.onDelete(e):void 0;return await f.persistAndConfirmCollectionMutations(e.transaction.mutations,t),n??{}},_={acceptMutations:async e=>{await f.acceptTransactionMutations(e)},getLeadershipState:()=>f.getLeadershipState(),forceReloadSubset:e=>f.forceReloadSubset(e)},te={...l.utils??{},..._};return m({...l,id:u,persistence:d,...n?{[h]:n}:{},sync:yt(f),onInsert:p,onUpdate:ee,onDelete:g,utils:te,startSync:!0,gcTime:l.gcTime??0},()=>bt({...e,id:u}),a)}function q(e){if(typeof e==`number`){if(!Number.isFinite(e))throw new E(e);return Object.is(e,-0)?`n:-0`:`n:${e}`}return`s:${e}`}function xt(e){if(e===`n:-0`)return-0;if(e.startsWith(`n:`))return Number(e.slice(2));if(e.startsWith(`s:`))return e.slice(2);throw new ae(e)}var St=`abcdefghijklmnopqrstuvwxyz234567`;function Ct(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function wt(e){if(e===0)return St.charAt(0);let t=e>>>0,n=``;for(;t>0;)n=`${St.charAt(t%32)}${n}`,t=Math.floor(t/32);return n}function Tt(e,t=`c`){if(!e)throw new y(`collectionId is required to derive a persisted table name`);return`${t}_${wt(Ct(e))}_${e.length.toString(36)}`}function Et(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.latestRowVersion==`number`&&Number.isSafeInteger(t.latestRowVersion)&&t.latestRowVersion>=0&&typeof t.resetEpoch==`number`&&Number.isSafeInteger(t.resetEpoch)&&t.resetEpoch>=0}var Dt=125,Ot=class{constructor(){this.regularQueue=[],this.hydrateQueue=[],this.running=!1}runRegular(e){return this.enqueue(`regular`,e)}runHydrate(e){return this.enqueue(`hydrate`,e)}adoptRunningHydrate(e){if(this.running)return;this.running=!0;let t=()=>{this.lastCompletedKind=`hydrate`,this.running=!1,this.drain()};e.then(t,t)}enqueue(e,t){let n=new Promise((n,r)=>{let i={kind:e,task:t,resolve:n,reject:r};(e===`hydrate`?this.hydrateQueue:this.regularQueue).push(i)});return this.drain(),n}drain(){if(this.running)return;let e=this.takeNext();e&&(this.running=!0,this.execute(e))}async execute(e){try{e.resolve(await e.task())}catch(t){e.reject(t)}finally{this.lastCompletedKind=e.kind,this.running=!1,this.drain()}}takeNext(){return this.hydrateQueue.length>0?this.regularQueue.length>0&&this.lastCompletedKind===`hydrate`?this.regularQueue.shift():this.hydrateQueue.shift():this.regularQueue.shift()}},kt=new WeakMap,At=new WeakMap;function jt(e){let t=kt.get(e);return t||(t=new Ot,kt.set(e,t)),t}function Mt(e){if(typeof e!=`object`&&typeof e!=`function`||!e)return;let t=e[We];return t!==null&&(typeof t==`object`||typeof t==`function`)?t:void 0}function Nt(e,t){let n=!0,r=e=>{if(!n)return e;n=!1;let r=Mt(e);return r&&t(r),e};return{maxBoundParameters:e.maxBoundParameters,exec:t=>r(e.exec(t)),query:(t,n=[])=>r(e.query(t,n)),run:(t,n=[])=>r(e.run(t,n)),transaction:t=>r(e.transaction(t)),transactionWithDriver:t=>r(e.transactionWithDriver?e.transactionWithDriver(t):e.transaction(t))}}var Pt=1,Ft=`tanstack-db-cache:`,It=`\0tanstack-db-cache:`;function Lt(e){return e.startsWith(Ft)||e.startsWith(It)}var Rt=128,zt=1e3,Bt=1440*60,Vt=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Ht=/(;|--|\/\*)/,Ut=new Set([`bigint`,`date`,`nan`,`infinity`,`-infinity`,`string`,`Temporal.Instant`,`Temporal.PlainDate`]),Wt=new WeakMap,Gt=1;function Kt(e,t){if(typeof e!=`string`&&!(e instanceof Error))return!1;let n=(typeof e==`string`?e:e.message).toLowerCase();return n.includes(t.toLowerCase())&&(n.includes(`duplicate column name`)||n.includes(`already exists`))}function J(e){if(!Vt.test(e))throw new y(`Invalid SQLite identifier "${e}"`);return`"${e}"`}function qt(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t[O]!=`string`||typeof t[k]!=`string`?!1:Ut.has(t[O])}function Jt(e){if(e==null)return e;if(typeof e==`bigint`)return le(e);let t=N(e);if(t)return t;if(e instanceof Date)return{[O]:`date`,[k]:e.toISOString()};if(typeof e==`number`)return Number.isNaN(e)?{[O]:`nan`,[k]:`NaN`}:e===1/0?{[O]:`infinity`,[k]:`Infinity`}:e===-1/0?{[O]:`-infinity`,[k]:`-Infinity`}:e;if(Array.isArray(e))return e.map(e=>Jt(e));if(typeof e==`object`){let t={},n=e;for(let[e,r]of Object.entries(n)){let n=Jt(r);n!==void 0&&(t[e]=n)}return typeof n[O]==`string`&&(t[O]={[O]:`string`,[k]:n[O]}),t}return e}function Yt(e){if(e==null)return e;if(qt(e))switch(e[O]){case`string`:return e[k];case`Temporal.Instant`:case`Temporal.PlainDate`:return ue(e[O],e[k]);case`bigint`:return BigInt(e[k]);case`date`:{let t=new Date(e[k]);return Number.isNaN(t.getTime())?null:t}case`nan`:return NaN;case`infinity`:return 1/0;case`-infinity`:return-1/0;default:return e}if(Array.isArray(e))return e.map(e=>Yt(e));if(typeof e==`object`){let t={},n=e;for(let[e,r]of Object.entries(n))t[e]=Yt(r);return t}return e}function Y(e){return JSON.stringify(Jt(e))}function X(e){return Yt(JSON.parse(e))}function Xt(e){return e==null?null:typeof e==`number`?Number.isFinite(e)?e:null:typeof e==`bigint`?(A(e),e.toString()):typeof e==`boolean`?+!!e:typeof e==`string`?e:e instanceof Date?e.toISOString():N(e)?.order??Y(e)}function Z(e){return e===null?`NULL`:typeof e==`number`?Number.isFinite(e)?String(e):`NULL`:e.includes(`\0`)?`json_extract(${Z(JSON.stringify(e))}, '$')`:`'${e.replace(/'/g,`''`)}'`}function Zt(e){return typeof e==`bigint`?A(e).toString():Z(Xt(e))}function Qt(e){let t;try{t=_(e)}catch(e){throw new y(`Unsupported expression for SQLite adapter fallback evaluator: ${e.message}`)}return t}function $t(e){let t=Wt.get(e);if(t!==void 0)return t;let n=Gt;return Gt++,Wt.set(e,n),n}function en(e,n,r){if(e==null&&n==null)return 0;if(e==null)return r.nulls===`first`?-1:1;if(n==null)return r.nulls===`first`?1:-1;if(typeof e==`string`&&typeof n==`string`)return r.stringSort===`custom`?r.compare(e,n):r.stringSort===`locale`?e.localeCompare(n,r.locale,r.localeOptions):e<n?-1:+(e>n);if(Array.isArray(e)&&Array.isArray(n)){let t=Math.min(e.length,n.length);for(let i=0;i<t;i++){let t=en(e[i],n[i],r);if(t!==0)return t}return e.length-n.length}if(e instanceof Date&&n instanceof Date)return e.getTime()-n.getTime();if(j(e)&&j(n))return t(e,n);let i=typeof e==`object`,a=typeof n==`object`;return i||a?i&&a?$t(e)-$t(n):i?1:-1:e<n?-1:+(e>n)}function tn(e){if(e.length===0)return null;let t=`$`;for(let n of e){if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)){t=`${t}.${n}`;continue}if(/^[0-9]+$/.test(n)){t=`${t}[${n}]`;continue}return null}return t}var nn=3;function rn(e){return e.type===`ref`?c(e).filter(e=>/^[0-9]+$/.test(String(e))).length>nn:e.type===`func`&&e.args.some(rn)}function an(e){let t=tn(e);if(!t)return null;let n=[`$`];for(let r of e)if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))n=n.map(e=>`${e}.${r}`);else if(/^[0-9]+$/.test(r)){if(n.length>=2**nn)return[t];n=n.flatMap(e=>[`${e}[${r}]`,`${e}."${r}"`])}return n}function on(e){return typeof e==`bigint`?`bigint`:e instanceof Date?`datetime`:`unknown`}function sn(e){return e.valueKind??`unknown`}function cn(e,t,n,r){let i=sn(n),a=sn(r);return e.type===`val`&&typeof e.value==`bigint`||t.type===`val`&&typeof t.value==`bigint`||i===`bigint`||a===`bigint`?`bigint`:e.type===`val`&&e.value instanceof Date||t.type===`val`&&t.value instanceof Date||i===`datetime`||a===`datetime`?`datetime`:i===`date`||a===`date`?`date`:`unknown`}function ln(e,t,n,r,i,a,o,s){let c=(e,t,n)=>e.type===`val`?a===`date`&&n===`date`?`date(${t})`:a===`datetime`&&n===`datetime`?`datetime(${t})`:t:t;return`(${c(t,r,s)} ${e} ${c(n,i,o)})`}function un(e){let t=`${e}.${O}`,n=`${e}.${k}`,r=Z(t),i=Z(n),a=Z(e),o=`json_extract(value, ${r})`,s=Z(`${e}.order`),c=`(CASE ${o}
|
|
2
|
+
WHEN 'bigint' THEN CAST(json_extract(value, ${i}) AS NUMERIC)
|
|
3
|
+
WHEN 'date' THEN json_extract(value, ${i})
|
|
4
|
+
WHEN 'string' THEN json_extract(value, ${i})
|
|
5
|
+
WHEN 'Temporal.Instant' THEN json_extract(value, ${s})
|
|
6
|
+
WHEN 'Temporal.PlainDate' THEN json_extract(value, ${s})
|
|
7
|
+
WHEN 'nan' THEN NULL
|
|
8
|
+
WHEN 'infinity' THEN NULL
|
|
9
|
+
WHEN '-infinity' THEN NULL
|
|
10
|
+
ELSE json_extract(value, ${a})
|
|
11
|
+
END)`;return{supported:!0,sql:c,identitySql:`(CASE WHEN ${o} IN ('Temporal.Instant', 'Temporal.PlainDate') THEN ${o} || ':' || json_extract(value, ${i}) ELSE ${c} END)`,params:[],valueKind:`unknown`}}function dn(e){if(e.trim().length===0||Ht.test(e))throw new y(`Invalid persisted index SQL fragment: "${e}"`);return e}function fn(e){return e.map(e=>({key:xt(e.key),value:X(e.value),metadata:e.metadata==null?void 0:X(e.metadata),rowVersion:e.row_version}))}function pn(e){return Y(e)}function mn(e){if(e.length===1)return e[0];let t=Math.floor(e.length/2);return`(${mn(e.slice(0,t))} OR ${mn(e.slice(t))})`}function hn(e,t,n,r){if(r===`index-expression`)return`index-expression`;switch(e){case`and`:case`or`:case`not`:return`predicate`;case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:case`like`:case`ilike`:return n.type===`val`?typeof n.value==`bigint`?`index-expression`:`predicate`:`index-expression`;case`in`:return t===0?`index-expression`:`predicate`;case`isNull`:case`isUndefined`:return`index-expression`;default:return`index-expression`}}function gn(e){return/[\uD800-\uDFFF]/u.test(e)}function _n(e){return typeof e==`string`||typeof e==`boolean`||typeof e==`bigint`||j(e)!==void 0}function vn(e){return e?.type===`func`&&e.name===`coalesce`&&e.args.length===2&&e.args[0]?.type===`ref`&&e.args[1]?.type===`val`&&_n(e.args[1].value)&&!(typeof e.args[1].value==`string`&&gn(e.args[1].value))}function Q(e,t=`predicate`){if(e.type===`val`){if(t===`predicate`&&typeof e.value==`string`&&gn(e.value))return{supported:!0,sql:`json_extract(?, '$')`,params:[JSON.stringify(e.value)]};let n=N(e.value),r=n?.order??Xt(e.value);return{identitySql:n?Z(de(n)):void 0,supported:!0,sql:t===`index-expression`?Zt(typeof e.value==`bigint`?e.value:r):`?`,params:t===`predicate`?[r]:[],valueKind:on(e.value)}}if(e.type===`ref`){let t=an(c(e).map(String));if(!t)return{supported:!1,sql:``,params:[]};if(t.length===1)return un(t[0]);let n=t.map(un);return{supported:!0,identitySql:`COALESCE(${n.map(e=>e.identitySql).join(`, `)})`,sql:`COALESCE(${n.map(e=>e.sql).join(`, `)})`,params:[],valueKind:`unknown`}}let n=(e.name===`in`?e.args.slice(0,1):e.args).map((n,r)=>Q(n,hn(e.name,r,n,t)));if(n.some(e=>!e.supported))return{supported:!1,sql:``,params:[]};let r=n.flatMap(e=>e.params),i=n.map(e=>e.sql);switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:{if(e.args.length!==2||!i[0]||!i[1]||!n[0]||!n[1])return{supported:!1,sql:``,params:[]};let a=cn(e.args[0],e.args[1],n[0],n[1]),o=ln({eq:`=`,gt:`>`,gte:`>=`,lt:`<`,lte:`<=`}[e.name],e.args[0],e.args[1],i[0],i[1],a,sn(n[0]),sn(n[1]));return{supported:!0,sql:e.name===`eq`&&e.args.every(e=>e.type!==`val`||j(e.value)||t===`index-expression`&&typeof e.value==`string`)?`(${o} AND (${n[0].identitySql??i[0]} = ${n[1].identitySql??i[1]}))`:o,params:r}}case`and`:case`or`:return i.length===0?{supported:!0,sql:e.name===`and`?`(1 = 1)`:`(0 = 1)`,params:[]}:{supported:!0,sql:i.map(e=>`(${e})`).join(e.name===`and`?` AND `:` OR `),params:r};case`not`:return i.length===1?{supported:!0,sql:`(NOT (${i[0]}))`,params:r}:{supported:!1,sql:``,params:[]};case`in`:{if(e.args.length!==2||e.args[1]?.type!==`val`)return{supported:!1,sql:``,params:[]};let r=e.args[1].value;if(!Array.isArray(r))return{supported:!1,sql:``,params:[]};if(r.length===0)return{supported:!0,sql:`(0 = 1)`,params:[]};let a=i[0],o=n[0]?.params??[];if(!a)return{supported:!1,sql:``,params:[]};let s=r.map(e=>{let t=N(e);return{value:typeof e==`bigint`?A(e):t?.order??Xt(e),identity:t?de(t):void 0}}),c=``;if(r.some(e=>j(e)||t===`index-expression`&&typeof e==`string`)){let e=n[0]?.identitySql??a;c=t===`index-expression`?` AND (${mn(s.map(({value:t,identity:n})=>`(${a} = ${Zt(t)} AND ${e} = ${Zt(n??t)})`))})`:` AND ((${a}, ${e}) IN (VALUES ${[...new Set(s.map(({value:e,identity:t})=>`(${Zt(e)}, ${Zt(t??e)})`))].join(`, `)}))`}if(t===`index-expression`)return{supported:!0,sql:`(${a} IN (${s.map(({value:e})=>Zt(e)).join(`, `)})${c})`,params:o};let l=`[${s.map(({value:e})=>typeof e==`bigint`?A(e).toString():JSON.stringify(e)).join(`,`)}]`;return{supported:!0,sql:`(${a} IN (SELECT value FROM json_each(?))${c})`,params:[...o,l]}}case`like`:return{supported:!0,sql:`(${i[0]} LIKE ${i[1]})`,params:r};case`ilike`:return{supported:!0,sql:`(LOWER(${i[0]}) LIKE LOWER(${i[1]}))`,params:r};case`isNull`:case`isUndefined`:return{supported:!0,sql:`(${i[0]} IS NULL)`,params:r};case`upper`:return{supported:!0,sql:`UPPER(${i[0]})`,params:r};case`lower`:return{supported:!0,sql:`LOWER(${i[0]})`,params:r};case`length`:return{supported:!0,sql:`LENGTH(${i[0]})`,params:r};case`concat`:return{supported:!0,sql:`(${i.join(` || `)})`,params:r};case`coalesce`:return{supported:!0,sql:`COALESCE(${i.join(`, `)})`,identitySql:`COALESCE(${n.map(e=>e.identitySql??e.sql).join(`, `)})`,params:r};case`add`:return{supported:!0,sql:`(${i[0]} + ${i[1]})`,params:r};case`subtract`:return{supported:!0,sql:`(${i[0]} - ${i[1]})`,params:r};case`multiply`:return{supported:!0,sql:`(${i[0]} * ${i[1]})`,params:r};case`divide`:return{supported:!0,sql:`(${i[0]} / ${i[1]})`,params:r};case`date`:return{supported:!0,sql:`date(${i[0]})`,params:r,valueKind:`date`};case`datetime`:return{supported:!0,sql:`datetime(${i[0]})`,params:r,valueKind:`datetime`};case`strftime`:return{supported:!0,sql:`strftime(${i.join(`, `)})`,params:r};default:return{supported:!1,sql:``,params:[]}}}function yn(e){if(e.type!==`func`||e.args.length!==2)return;let[t,n]=e.args;if(e.name===`in`)return t?.type===`ref`&&n?.type===`val`&&Array.isArray(n.value)&&n.value.length>0&&n.value.every(e=>j(e))?t:void 0;if([`eq`,`gt`,`gte`,`lt`,`lte`].includes(e.name)){if(t?.type===`ref`&&n?.type===`val`&&j(n.value))return t;if(n?.type===`ref`&&t?.type===`val`&&j(t.value))return n}}function bn(e){let t=an(c(e).map(String)).map(e=>`json_extract(value, ${Z(`${e}.${O}`)})`);return`${t.length===1?t[0]:`COALESCE(${t.join(`, `)})`} IN ('Temporal.Instant', 'Temporal.PlainDate')`}function xn(e,t){let n=()=>{let n=t??Q(e);return n.supported?n:void 0};if(e.type===`val`)return typeof e.value==`boolean`||e.value==null?n():void 0;if(e.type===`ref`)return;if(e.name===`and`||e.name===`or`){if(e.args.length===0)return n();let t=e.args.map(e=>xn(e));if(e.name===`or`&&t.some(e=>!e))return;let r=t.filter(e=>e!==void 0);return r.length===0?void 0:{supported:!0,sql:r.map(({sql:e})=>`(${e})`).join(e.name===`and`?` AND `:` OR `),params:r.flatMap(({params:e})=>e)}}if(rn(e)||(t??=Q(e),!t.supported))return;let[r,i]=e.args;if(e.name===`not`&&e.args.length===1&&r&&yn(r))return{...t,sql:`COALESCE(${t.sql}, 1)`};if(e.args.length===2){let n=yn(e);if(n){if(e.name===`eq`||e.name===`in`)return t;let r=Q(n,`index-expression`).sql;return{...t,sql:`(${t.sql} OR ${r} IS NULL)`}}if(e.name===`eq`&&r?.type===`ref`&&i?.type===`ref`)return{...t,sql:`(CASE WHEN ${bn(r)} AND ${bn(i)} THEN ${t.sql} ELSE 1 END)`};if([`gt`,`gte`,`lt`,`lte`].includes(e.name)&&(r?.type===`ref`||i?.type===`ref`)){let t=r?.type===`ref`?r:i?.type===`ref`?i:void 0,n=t===r?i:r;if(t&&n?.type===`val`&&(typeof n.value==`number`&&Number.isSafeInteger(n.value)||typeof n.value==`bigint`)){let a=Q(t,`index-expression`).sql,o=Q(n,typeof n.value==`bigint`?`index-expression`:`predicate`),s=t===r&&[`gt`,`gte`].includes(e.name)||t===i&&[`lt`,`lte`].includes(e.name),c=typeof n.value==`bigint`&&!Number.isSafeInteger(Number(n.value))?n.value>0n?` OR ${a} >= ${2**53-1}`:` OR ${a} <= -${2**53-1}`:``;return{supported:!0,sql:s?`(${a} >= ${o.sql} OR ${a} IS NULL${c})`:`(${a} <= ${o.sql} OR ${a} IS NULL OR ${a} >= ''${c})`,params:o.params}}}if(e.name===`eq`){if((r?.type===`ref`||vn(r))&&i?.type===`val`&&_n(i.value)||(i?.type===`ref`||vn(i))&&r?.type===`val`&&_n(r.value))return t;let e=r?.type===`func`&&r.name===`lower`?r:i?.type===`func`&&i.name===`lower`?i:void 0,n=e===r?i:r;if(e?.args.length===1&&e.args[0]?.type===`ref`&&n?.type===`val`&&typeof n.value==`string`&&[...n.value].every(e=>e.charCodeAt(0)<=127)&&!n.value.includes(`\0`)){let r=Q(e,`index-expression`).sql;return{supported:!0,sql:`(${t.sql} OR (${r} >= ? AND ${r} GLOB '*[^ -~]*'))`,params:[...t.params,n.value]}}}}if(e.name===`in`&&e.args.length===2&&i?.type===`val`&&Array.isArray(i.value)){if(i.value.length===0)return t;if(r?.type===`ref`){if(i.value.every(e=>typeof e==`bigint`))return t;if(i.value.every(e=>typeof e==`string`))return{supported:!0,sql:`(${Q(r,`index-expression`).sql} IN (SELECT value FROM json_each(?)))`,params:[JSON.stringify(i.value)]}}}if(e.name===`like`&&e.args.length===2&&r?.type===`ref`&&i?.type===`val`&&typeof i.value==`string`&&/^[\x20-\x7e]*%$/.test(i.value)&&!i.value.slice(0,-1).includes(`%`)&&!i.value.includes(`_`))return t}function Sn(e){if(!e||e.length===0)return{supported:!0,sql:``,params:[]};let t=[],n=[];for(let r of e){let e=Q(r.expression,`index-expression`);if(!e.supported)return{supported:!1,sql:``,params:[]};n.push(...e.params);let i=r.compareOptions.direction===`desc`?`DESC`:`ASC`,a=r.compareOptions.nulls===`first`?`NULLS FIRST`:`NULLS LAST`;t.push(`${e.sql} ${i} ${a}`)}return{supported:!0,sql:t.join(`, `),params:n}}function Cn(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.type===`val`?Object.prototype.hasOwnProperty.call(t,`value`):t.type===`ref`?Array.isArray(t.path)&&(t.sourceAlias===void 0||typeof t.sourceAlias==`string`&&t.path[0]===t.sourceAlias):t.type===`func`?typeof t.name!=`string`||!Array.isArray(t.args)?!1:t.args.every(e=>Cn(e)):!1}function wn(e){let t=e.trim();if(t.length===0)throw new y(`Index SQL fragment cannot be empty`);let n,r=!1;try{n=JSON.parse(t),r=!0}catch{}let i=r?Yt(n):void 0;if(r&&Cn(i)){let e=Q(i,`index-expression`);if(!e.supported)throw new y(`Persisted index expression is not supported by the SQLite compiler`);if(e.params.length!==0)throw new y(`Persisted index expression cannot contain bound parameters`);return e.sql}return dn(e)}function Tn(e,t){return typeof e==`object`&&e?Object.assign({},e,t):t}function*En(e,t){for(let n=0;n<e.length;n+=t)yield e.slice(n,n+t)}function Dn(e,t,n=!1){let r=new Map;for(let i of e){let e=t(i),a=r.get(e);if(a?.type===`set`&&(a.value!==void 0||!n)&&Y(a.value)===void 0)throw TypeError(`Metadata value cannot be bound to SQLite`);r.set(e,i)}return[...r.values()]}function On(e,t){let n=t.toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,24);return`idx_${Tt(`${e}:${t}`,`c`)}_${n.length>0?n:`sig`}`}var kn=class{constructor(e){this.initialized=!1,this.collectionTableCache=new Map,this.collectionTableLoads=new Map;let t=e.driver.maxBoundParameters;if(t!==void 0&&(!Number.isInteger(t)||t<4))throw new y(`SQLite driver maxBoundParameters must be an integer of at least 4`);if(this.replacementBatchSize=t===void 0?Dt:Math.min(Dt,Math.floor(t/4)),this.cacheGenerationClaimTtlMs=e.cacheGenerationClaimTtlMs??3e5,!Number.isSafeInteger(this.cacheGenerationClaimTtlMs)||this.cacheGenerationClaimTtlMs<=0)throw new y(`SQLite adapter cacheGenerationClaimTtlMs must be a positive safe integer`);this.now=e.now??Date.now;let n=e.schemaVersion??Pt;if(!Number.isInteger(n)||n<0)throw new y(`SQLite adapter schemaVersion must be a non-negative integer`);if(e.appliedTxPruneMaxRows!==void 0&&(!Number.isInteger(e.appliedTxPruneMaxRows)||e.appliedTxPruneMaxRows<0))throw new y(`SQLite adapter appliedTxPruneMaxRows must be a non-negative integer when provided`);if(e.appliedTxPruneMaxAgeSeconds!==void 0&&(!Number.isInteger(e.appliedTxPruneMaxAgeSeconds)||e.appliedTxPruneMaxAgeSeconds<0))throw new y(`SQLite adapter appliedTxPruneMaxAgeSeconds must be a non-negative integer when provided`);let r=e.pullSinceReloadThreshold??Rt;if(!Number.isInteger(r)||r<0)throw new y(`SQLite adapter pullSinceReloadThreshold must be a non-negative integer`);this.schedulingIdentitySource=e.driver;let i=Mt(e.driver)??At.get(e.driver);this.scheduler=i?jt(i):void 0,this.driver=i?e.driver:Nt(e.driver,t=>{At.set(e.driver,t);let n=jt(t);this.scheduler??=n,this.activeUnscheduledHydration&&n.adoptRunningHydrate(this.activeUnscheduledHydration)}),this.schemaVersion=n,this.schemaMismatchPolicy=e.schemaMismatchPolicy??`sync-present-reset`,this.appliedTxPruneMaxRows=e.appliedTxPruneMaxRows,this.appliedTxPruneMaxAgeSeconds=e.appliedTxPruneMaxAgeSeconds,this.pullSinceReloadThreshold=r,this.hydrationAdapter={loadSubset:(e,t,n)=>this.loadSubsetUnscheduled(e,t,n),loadResumeSnapshot:(e,t)=>this.loadResumeSnapshotUnscheduled(e,t),applyCommittedTx:(e,t)=>this.applyCommittedTxUnscheduled(e,t),renewCacheGenerationClaim:(e,t)=>this.renewCacheGenerationClaimUnscheduled(e,t),reconcileCommittedTx:(e,t,n)=>this.reconcileCommittedTxUnscheduled(e,t,n),loadCollectionMetadata:(e,t)=>this.loadCollectionMetadataUnscheduled(e,t),scanRows:(e,t,n)=>this.scanRowsUnscheduled(e,t,n),ensureIndex:(e,t,n,r)=>this.ensureIndexUnscheduled(e,t,n,r),markIndexRemoved:(e,t,n)=>this.markIndexRemovedUnscheduled(e,t,n),getStreamPosition:(e,t)=>this.getStreamPositionUnscheduled(e,t),pullSince:(e,t,n)=>this.pullSinceUnscheduled(e,t,n),runInHydrationScope:async e=>e(this.hydrationAdapter)}}claimCacheGeneration(e){return this.runRegular(async()=>(await this.ensureInitialized(),this.driver.transaction(async t=>{let n=this.now()+this.cacheGenerationClaimTtlMs,r=`${Ft}${s()}`;await t.run(`INSERT INTO cache_generation (logical_id, generation, physical_id, retired)
|
|
12
|
+
SELECT ?, 0, ?, 0
|
|
13
|
+
WHERE NOT EXISTS (
|
|
14
|
+
SELECT 1 FROM cache_generation WHERE logical_id = ?
|
|
15
|
+
)`,[e,r,e]);let i=(await t.query(`SELECT physical_id FROM cache_generation
|
|
16
|
+
WHERE logical_id = ? AND retired = 0`,[e]))[0]?.physical_id;if(!i)throw new y(`No active persisted cache generation for collection "${e}"`);let a=s();return await t.run(`INSERT INTO cache_generation_claim
|
|
17
|
+
(claim_id, logical_id, physical_id, expires_at_ms)
|
|
18
|
+
VALUES (?, ?, ?, ?)`,[a,e,i,n]),await this.collectRetiredCacheGenerations(t),{storageCollectionId:i,claimId:a,expiresAtMs:n}})))}rotateCacheGeneration(e,t,n,r){return this.runRegular(async()=>(await this.ensureInitialized(),this.driver.transaction(async i=>{let a=this.now(),o=a+this.cacheGenerationClaimTtlMs,c=await i.query(`SELECT physical_id, expires_at_ms
|
|
19
|
+
FROM cache_generation_claim
|
|
20
|
+
WHERE claim_id = ? AND logical_id = ?`,[t,e]),l=c[0]&&c[0].expires_at_ms>a?c[0].physical_id:void 0;if(l&&r&&l!==r)throw new y(`Persisted cache claim changed generations before recovery`);let u=(await i.query(`SELECT generation, physical_id FROM cache_generation
|
|
21
|
+
WHERE logical_id = ? AND retired = 0`,[e]))[0];if(!u)throw new y(`No active persisted cache generation for collection "${e}"`);await i.run(`INSERT INTO cache_generation_sequence (logical_id, next_generation)
|
|
22
|
+
SELECT ?, COALESCE(MAX(generation), -1) + 1
|
|
23
|
+
FROM cache_generation WHERE logical_id = ?
|
|
24
|
+
ON CONFLICT(logical_id) DO NOTHING`,[e,e]);let d=(await i.query(`SELECT next_generation FROM cache_generation_sequence
|
|
25
|
+
WHERE logical_id = ?`,[e]))[0].next_generation;await i.run(`UPDATE cache_generation_sequence SET next_generation = ?
|
|
26
|
+
WHERE logical_id = ?`,[d+1,e]);let f=l===u.physical_id,p=`${Ft}${s()}`;f&&await i.run(`UPDATE cache_generation SET retired = 1
|
|
27
|
+
WHERE logical_id = ? AND generation = ?`,[e,u.generation]),await i.run(`INSERT INTO cache_generation (logical_id, generation, physical_id, retired)
|
|
28
|
+
VALUES (?, ?, ?, ?)`,[e,d,p,+!f]);let m=c[0]?t:s();return c[0]?await i.run(`UPDATE cache_generation_claim
|
|
29
|
+
SET physical_id = ?, expires_at_ms = ? WHERE claim_id = ?`,[p,o,t]):await i.run(`INSERT INTO cache_generation_claim
|
|
30
|
+
(claim_id, logical_id, physical_id, expires_at_ms)
|
|
31
|
+
VALUES (?, ?, ?, ?)`,[m,e,p,o]),await i.run(`INSERT INTO collection_version (
|
|
32
|
+
collection_id, latest_row_version,
|
|
33
|
+
key_set_evidence_available, key_set_evidence_incompatible
|
|
34
|
+
) VALUES (?, 0, 1, 1)`,[p]),n&&await i.run(`INSERT INTO collection_metadata (collection_id, key, value, updated_at)
|
|
35
|
+
VALUES (?, ?, ?, CAST(strftime('%s', 'now') AS INTEGER))`,[p,n.key,Y(n.value)]),await this.collectRetiredCacheGenerations(i),{storageCollectionId:p,claimId:m,expiresAtMs:o}})))}releaseCacheGenerationClaim(e){return this.runRegular(async()=>{await this.ensureInitialized(),await this.runInTransaction(async t=>{await t.run(`DELETE FROM cache_generation_claim WHERE claim_id = ?`,[e]),await this.collectRetiredCacheGenerations(t)})})}renewCacheGenerationClaim(e,t){return this.runRegular(()=>this.renewCacheGenerationClaimUnscheduled(e,t))}async renewCacheGenerationClaimUnscheduled(e,t){return await this.ensureInitialized(),this.runInTransaction(async n=>{let r=this.now();if(!(await n.query(`SELECT claim_id FROM cache_generation_claim
|
|
36
|
+
WHERE claim_id = ? AND physical_id = ? AND expires_at_ms > ?`,[t,e,r]))[0]){await this.collectRetiredCacheGenerations(n);return}let i=r+this.cacheGenerationClaimTtlMs;return await n.run(`UPDATE cache_generation_claim SET expires_at_ms = ?
|
|
37
|
+
WHERE claim_id = ?`,[i,t]),i})}async collectRetiredCacheGenerations(e){await e.run(`DELETE FROM cache_generation_claim WHERE expires_at_ms <= ?`,[this.now()]);let t=await e.query(`SELECT generation.physical_id, registry.table_name,
|
|
38
|
+
registry.tombstone_table_name
|
|
39
|
+
FROM cache_generation AS generation
|
|
40
|
+
LEFT JOIN collection_registry AS registry
|
|
41
|
+
ON registry.collection_id = generation.physical_id
|
|
42
|
+
WHERE generation.retired = 1
|
|
43
|
+
AND NOT EXISTS (
|
|
44
|
+
SELECT 1 FROM cache_generation_claim AS claim
|
|
45
|
+
WHERE claim.physical_id = generation.physical_id
|
|
46
|
+
)`);for(let n of t){n.table_name&&await e.exec(`DROP TABLE IF EXISTS ${J(n.table_name)}`),n.tombstone_table_name&&await e.exec(`DROP TABLE IF EXISTS ${J(n.tombstone_table_name)}`);for(let t of[`applied_tx`,`collection_expected_keys`,`collection_metadata`,`persisted_index_registry`,`leader_term`])await e.run(`DELETE FROM ${t} WHERE collection_id = ?`,[n.physical_id]);await e.run(`DELETE FROM collection_version WHERE collection_id = ?`,[n.physical_id]),await e.run(`DELETE FROM collection_reset_epoch WHERE collection_id = ?`,[n.physical_id]),await e.run(`DELETE FROM collection_registry WHERE collection_id = ?`,[n.physical_id]),await e.run(`DELETE FROM cache_generation WHERE physical_id = ?`,[n.physical_id]),this.collectionTableCache.delete(n.physical_id)}}getCacheGenerationNow(){return this.now()}runInHydrationScope(e){let t=this.resolveScheduler();if(t)return t.runHydrate(()=>e(this.hydrationAdapter));let n=Promise.resolve().then(()=>e(this.hydrationAdapter));this.activeUnscheduledHydration=n;let r=()=>{this.activeUnscheduledHydration===n&&(this.activeUnscheduledHydration=void 0)};return n.then(r,r),n}runInRegularScope(e){return this.runRegular(()=>e(this.hydrationAdapter))}isHydrationScopeScheduled(){return this.resolveScheduler()!==void 0}runRegular(e){let t=this.resolveScheduler();return t?t.runRegular(e):e()}resolveScheduler(){if(this.scheduler)return this.scheduler;let e=At.get(this.schedulingIdentitySource);return e&&(this.scheduler=jt(e)),this.scheduler}runInTransaction(e){return typeof this.driver.transactionWithDriver==`function`?this.driver.transactionWithDriver(e):this.driver.transaction(e)}async assertCurrentSchemaVersion(e,t,n){let r=(await t.query(`SELECT schema_version
|
|
47
|
+
FROM collection_registry
|
|
48
|
+
WHERE collection_id = ?
|
|
49
|
+
LIMIT 1`,[e]))[0]?.schema_version;if(r!==this.schemaVersion)throw new y(`Schema version mismatch for collection "${e}": found ${r??`missing`}, expected ${this.schemaVersion}. Refusing to ${n} through a stale cached adapter.`)}async assertCacheGenerationReadClaim(e,t,n){if(await this.ensureInitialized(),!n){if(!Lt(t))return;if((await e.query(`SELECT physical_id FROM cache_generation WHERE physical_id = ?`,[t]))[0])throw new y(`Persisted cache claim is required for collection "${t}"`);return}if(!(await e.query(`SELECT claim.claim_id
|
|
50
|
+
FROM cache_generation_claim AS claim
|
|
51
|
+
JOIN cache_generation AS generation
|
|
52
|
+
ON generation.physical_id = claim.physical_id
|
|
53
|
+
WHERE claim.claim_id = ? AND claim.physical_id = ?
|
|
54
|
+
AND claim.expires_at_ms > ?`,[n,t,this.now()]))[0])throw new y(`Persisted cache claim is no longer active for collection "${t}"`)}loadSubset(e,t,n){return this.runRegular(()=>this.loadSubsetUnscheduled(e,t,n))}async loadSubsetUnscheduled(e,t,r){let i=G(e,r?.cacheGenerationClaimId),a=i.collectionId;r=i.claimId?{...r,cacheGenerationClaimId:i.claimId}:r,await this.assertCacheGenerationReadClaim(this.driver,a,r?.cacheGenerationClaimId);let o=await this.ensureCollectionReady(a,r?.cacheGenerationClaimId);return this.runInTransaction(async e=>{if(await this.assertCacheGenerationReadClaim(e,a,r?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(a,e,`load persisted rows`),await this.touchRequiredIndexes(a,r?.requiredIndexSignatures,e),t.cursor){let r={where:t.where?new n(`and`,[t.where,t.cursor.whereCurrent]):t.cursor.whereCurrent,orderBy:t.orderBy},i={where:t.where?new n(`and`,[t.where,t.cursor.whereFrom]):t.cursor.whereFrom,orderBy:t.orderBy,limit:t.limit},[a,s]=await Promise.all([this.loadSubsetInternal(o,r,e),this.loadSubsetInternal(o,i,e)]),c=new Map;for(let e of[...a,...s])c.set(q(e.key),e);return this.applyInMemoryOrderBy(Array.from(c.values()),t.orderBy).map(e=>({key:e.key,value:e.value,metadata:e.metadata}))}return(await this.loadSubsetInternal(o,t,e)).map(e=>({key:e.key,value:e.value,metadata:e.metadata}))})}loadResumeSnapshot(e,t){return this.runRegular(()=>this.loadResumeSnapshotUnscheduled(e,t))}async loadResumeSnapshotUnscheduled(e,t){let n=G(e,t?.cacheGenerationClaimId),r=n.collectionId;t=n.claimId?{...t,cacheGenerationClaimId:n.claimId}:t,await this.assertCacheGenerationReadClaim(this.driver,r,t?.cacheGenerationClaimId);let i=await this.ensureCollectionReady(r,t?.cacheGenerationClaimId),a=t?.includeRows!==!1;return this.runInTransaction(async e=>{await this.assertCacheGenerationReadClaim(e,r,t?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(r,e,`load a resume snapshot`),a&&await this.touchRequiredIndexes(r,t?.requiredIndexSignatures,e);let n=a?await this.loadSubsetInternal(i,{},e):[],{latestRowVersion:o,keySet:s}=await this.readKeySetEvidence(r,e),c=await e.query(`SELECT key, value
|
|
55
|
+
FROM collection_metadata
|
|
56
|
+
WHERE collection_id = ?`,[r]),{latestTerm:l,latestSeq:u}=await this.readStreamPosition(r,e),d=await e.query(`SELECT reset_epoch
|
|
57
|
+
FROM collection_reset_epoch
|
|
58
|
+
WHERE collection_id = ?
|
|
59
|
+
LIMIT 1`,[r]);return{rows:n.map(e=>({key:e.key,value:e.value,metadata:e.metadata})),keySet:s,collectionMetadata:c.map(e=>({key:e.key,value:X(e.value)})),latestTerm:l,latestSeq:u,latestRowVersion:o,resetEpoch:d[0]?.reset_epoch??0}})}applyCommittedTx(e,t){return this.runRegular(()=>this.applyCommittedTxUnscheduled(e,t))}reconcileCommittedTx(e,t,n){return this.runRegular(()=>this.reconcileCommittedTxUnscheduled(e,t,n))}async applyCommittedTxUnscheduled(e,t){await this.applyCommittedTxInternal(e,t)}reconcileCommittedTxUnscheduled(e,t,n){if(!Et(n))throw Error(`Cannot reconcile a committed transaction without a valid durable anchor`);return this.applyCommittedTxInternal(e,t,n)}async applyCommittedTxInternal(e,t,n){let r=G(e,t.cacheGenerationClaimId),i=r.collectionId;t={...t,cacheGenerationClaimId:r.claimId},await this.assertCacheGenerationReadClaim(this.driver,i,t.cacheGenerationClaimId);let a=await this.ensureCollectionReady(i,t.cacheGenerationClaimId),o=J(a.tableName),s=J(a.tombstoneTableName);return this.runInTransaction(async e=>{await this.assertCacheGenerationReadClaim(e,i,t.cacheGenerationClaimId);let r=(await e.query(`SELECT
|
|
60
|
+
latest_row_version,
|
|
61
|
+
key_set_evidence_available,
|
|
62
|
+
(SELECT reset_epoch FROM collection_reset_epoch
|
|
63
|
+
WHERE collection_id = ? LIMIT 1) AS reset_epoch,
|
|
64
|
+
(
|
|
65
|
+
SELECT schema_version
|
|
66
|
+
FROM collection_registry
|
|
67
|
+
WHERE collection_id = ?
|
|
68
|
+
LIMIT 1
|
|
69
|
+
) AS schema_version,
|
|
70
|
+
EXISTS (
|
|
71
|
+
SELECT 1
|
|
72
|
+
FROM applied_tx
|
|
73
|
+
WHERE collection_id = ? AND term = ? AND seq = ?
|
|
74
|
+
) AS already_applied
|
|
75
|
+
FROM collection_version
|
|
76
|
+
WHERE collection_id = ?
|
|
77
|
+
LIMIT 1`,[i,i,i,t.term,t.seq,i]))[0];if(!r)throw new y(`Missing persisted version state for collection "${i}"`);if(r.schema_version!==this.schemaVersion)throw new y(`Schema version mismatch for collection "${i}": found ${r.schema_version}, expected ${this.schemaVersion}. Refusing to apply a committed transaction through a stale cached adapter.`);if(n){let a=(r.reset_epoch??0)===n.resetEpoch,o=await e.query(`SELECT term, seq, row_version FROM applied_tx
|
|
78
|
+
WHERE collection_id = ? AND tx_id = ? LIMIT 2`,[i,t.txId]);if(o.length>1)return{kind:`unknown`};if(o[0])return o[0].row_version<=n.latestRowVersion||!a?{kind:`unknown`}:{kind:`already-applied`,committed:{term:o[0].term,seq:o[0].seq,rowVersion:o[0].row_version},latestRowVersion:r.latest_row_version};if(r.latest_row_version!==n.latestRowVersion||!a)return{kind:`unknown`}}if(r.already_applied===1)return{kind:`unknown`};let a=r.latest_row_version,c=Math.max(a+1,t.rowVersion),l=t.truncate===!0,u=r.key_set_evidence_available===1||l,d=l?null:{txId:t.txId,latestRowVersion:c,changedRows:t.mutations.filter(e=>e.type!==`delete`).map(e=>({key:e.key,value:e.value})),deletedKeys:t.mutations.filter(e=>e.type===`delete`).map(e=>e.key),rowMetadataMutations:t.rowMetadataMutations??[],collectionMetadataMutations:t.collectionMetadataMutations??[]};l&&(await e.run(`DELETE FROM collection_expected_keys
|
|
79
|
+
WHERE collection_id = ?`,[i]),await e.run(`DELETE FROM ${o}`),await e.run(`DELETE FROM ${s}`));let f=new Map;for(let e of t.mutations){let t=q(e.key),n=f.get(t);if(!n){f.set(t,e);continue}if(Y(n.value),n.type!==`delete`&&n.metadataChanged===!0&&n.metadata!==void 0&&Y(n.metadata),e.type===`delete`){f.set(t,e);continue}let r=e.type===`insert`||n.type===`delete`?e.value:Tn(n.value,e.value),i=e.metadataChanged===!0||n.type===`delete`||n.metadataChanged===!0,a=e.metadataChanged===!0?e.metadata:n.type===`delete`?void 0:n.metadata,o={key:e.key,value:r,metadataChanged:i,metadata:a};f.set(t,e.type===`insert`||n.type!==`update`?{type:`insert`,...o}:{type:`update`,...o})}for(let t of En([...f.values()],this.replacementBatchSize)){let n=t.filter(e=>e.type!==`delete`),r=t.filter(e=>e.type===`delete`),a=n.filter(e=>e.type===`update`||e.metadataChanged!==!0).map(e=>q(e.key)),l=a.length>0?await e.query(`SELECT key, value, metadata
|
|
80
|
+
FROM ${o}
|
|
81
|
+
WHERE key IN (${a.map(()=>`?`).join(`, `)})`,a):[],d=new Map(l.map(e=>[e.key,e])),f=n.map(e=>q(e.key)),p=r.map(e=>q(e.key));u&&f.length>0&&await e.run(`INSERT INTO collection_expected_keys (collection_id, key)
|
|
82
|
+
VALUES ${f.map(()=>`(?, ?)`).join(`, `)}
|
|
83
|
+
ON CONFLICT(collection_id, key) DO NOTHING`,f.flatMap(e=>[i,e])),u&&p.length>0&&await e.run(`DELETE FROM collection_expected_keys
|
|
84
|
+
WHERE collection_id = ? AND key IN (${p.map(()=>`?`).join(`, `)})`,[i,...p]),p.length>0&&await e.run(`DELETE FROM ${o}
|
|
85
|
+
WHERE key IN (${p.map(()=>`?`).join(`, `)})`,p),f.length>0&&(await e.run(`INSERT INTO ${o} (key, value, metadata, row_version)
|
|
86
|
+
VALUES ${f.map(()=>`(?, ?, ?, ?)`).join(`, `)}
|
|
87
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
88
|
+
value = excluded.value,
|
|
89
|
+
metadata = excluded.metadata,
|
|
90
|
+
row_version = excluded.row_version`,n.flatMap((e,t)=>{let n=d.get(f[t]),r=n?.value?X(n.value):void 0,i=n?.metadata==null?void 0:X(n.metadata),a=e.type===`update`?Tn(r,e.value):e.value,o=e.metadataChanged===!0?e.metadata:i;return[f[t],Y(a),o===void 0?null:Y(o),c]})),await e.run(`DELETE FROM ${s}
|
|
91
|
+
WHERE key IN (${f.map(()=>`?`).join(`, `)})`,f)),r.length>0&&await e.run(`INSERT INTO ${s} (key, value, row_version, deleted_at)
|
|
92
|
+
VALUES ${p.map(()=>`(?, ?, ?, ?)`).join(`, `)}
|
|
93
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
94
|
+
value = excluded.value,
|
|
95
|
+
row_version = excluded.row_version,
|
|
96
|
+
deleted_at = excluded.deleted_at`,r.flatMap((e,t)=>[p[t],Y(e.value),c,new Date().toISOString()]))}for(let n of En(Dn(t.rowMetadataMutations??[],e=>q(e.key),!0),this.replacementBatchSize)){let t=n.map(e=>q(e.key));await e.run(`UPDATE ${o}
|
|
97
|
+
SET metadata = CASE key ${t.map(()=>`WHEN ? THEN ?`).join(` `)} END
|
|
98
|
+
WHERE key IN (${t.map(()=>`?`).join(`, `)})`,[...n.flatMap((e,n)=>[t[n],e.type===`delete`||e.value===void 0?null:Y(e.value)]),...t])}for(let n of En(Dn(t.collectionMetadataMutations??[],e=>e.key),this.replacementBatchSize)){let t=n.filter(e=>e.type===`delete`),r=n.filter(e=>e.type===`set`);t.length>0&&await e.run(`DELETE FROM collection_metadata
|
|
99
|
+
WHERE collection_id = ? AND key IN (${t.map(()=>`?`).join(`, `)})`,[i,...t.map(e=>e.key)]),r.length>0&&await e.run(`INSERT INTO collection_metadata (collection_id, key, value, updated_at)
|
|
100
|
+
VALUES ${r.map(()=>`(?, ?, ?, CAST(strftime('%s', 'now') AS INTEGER))`).join(`, `)}
|
|
101
|
+
ON CONFLICT(collection_id, key) DO UPDATE SET
|
|
102
|
+
value = excluded.value,
|
|
103
|
+
updated_at = excluded.updated_at`,r.flatMap(e=>[i,e.key,Y(e.value)]))}return await e.run(`UPDATE collection_version
|
|
104
|
+
SET latest_row_version = ?,
|
|
105
|
+
key_set_evidence_available = CASE
|
|
106
|
+
WHEN ? = 1 THEN 1
|
|
107
|
+
ELSE key_set_evidence_available
|
|
108
|
+
END,
|
|
109
|
+
key_set_evidence_incompatible = CASE
|
|
110
|
+
WHEN ? = 1 THEN 0
|
|
111
|
+
ELSE key_set_evidence_incompatible
|
|
112
|
+
END
|
|
113
|
+
WHERE collection_id = ?`,[c,+!!l,+!!l,i]),await e.run(`INSERT INTO leader_term (collection_id, latest_term)
|
|
114
|
+
VALUES (?, ?)
|
|
115
|
+
ON CONFLICT(collection_id) DO UPDATE SET
|
|
116
|
+
latest_term = CASE
|
|
117
|
+
WHEN leader_term.latest_term > excluded.latest_term
|
|
118
|
+
THEN leader_term.latest_term
|
|
119
|
+
ELSE excluded.latest_term
|
|
120
|
+
END`,[i,t.term]),await e.run(`INSERT INTO applied_tx (
|
|
121
|
+
collection_id,
|
|
122
|
+
term,
|
|
123
|
+
seq,
|
|
124
|
+
tx_id,
|
|
125
|
+
row_version,
|
|
126
|
+
replay_json,
|
|
127
|
+
replay_requires_full_reload,
|
|
128
|
+
applied_at
|
|
129
|
+
)
|
|
130
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, CAST(strftime('%s', 'now') AS INTEGER))`,[i,t.term,t.seq,t.txId,c,d?pn(d):null,+!!l]),await this.pruneAppliedTxRows(i,e),{kind:`applied-now`,committed:{term:t.term,seq:t.seq,rowVersion:c},latestRowVersion:c}})}loadCollectionMetadata(e,t){return this.runRegular(()=>this.loadCollectionMetadataUnscheduled(e,t))}async loadCollectionMetadataUnscheduled(e,t){let n=G(e,t?.cacheGenerationClaimId),r=n.collectionId;return t=n.claimId?{...t,cacheGenerationClaimId:n.claimId}:t,await this.assertCacheGenerationReadClaim(this.driver,r,t?.cacheGenerationClaimId),await this.ensureCollectionReady(r,t?.cacheGenerationClaimId),this.runInTransaction(async e=>(await this.assertCacheGenerationReadClaim(e,r,t?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(r,e,`load collection metadata`),(await e.query(`SELECT key, value
|
|
131
|
+
FROM collection_metadata
|
|
132
|
+
WHERE collection_id = ?`,[r])).map(e=>({key:e.key,value:X(e.value)}))))}scanRows(e,t,n){return this.runRegular(()=>this.scanRowsUnscheduled(e,t,n))}async scanRowsUnscheduled(e,t,n){let r=G(e,n?.cacheGenerationClaimId),i=r.collectionId;n=r.claimId?{...n,cacheGenerationClaimId:r.claimId}:n,await this.assertCacheGenerationReadClaim(this.driver,i,n?.cacheGenerationClaimId);let a=J((await this.ensureCollectionReady(i,n?.cacheGenerationClaimId)).tableName);return this.runInTransaction(async e=>(await this.assertCacheGenerationReadClaim(e,i,n?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(i,e,`scan persisted rows`),fn(await e.query(t?.metadataOnly?`SELECT key, value, metadata, row_version
|
|
133
|
+
FROM ${a}
|
|
134
|
+
WHERE metadata IS NOT NULL`:`SELECT key, value, metadata, row_version
|
|
135
|
+
FROM ${a}`)).map(e=>({key:e.key,value:e.value,metadata:e.metadata}))))}ensureIndex(e,t,n,r){return this.runRegular(()=>this.ensureIndexUnscheduled(e,t,n,r))}async ensureIndexUnscheduled(e,t,n,r){let i=G(e,r?.cacheGenerationClaimId),a=i.collectionId;r=i.claimId?{...r,cacheGenerationClaimId:i.claimId}:r,await this.assertCacheGenerationReadClaim(this.driver,a,r?.cacheGenerationClaimId);let o=J((await this.ensureCollectionReady(a,r?.cacheGenerationClaimId)).tableName),s=On(a,t),c=J(s),l=n.expressionSql.map(e=>wn(e)),u=l.join(`, `),d=JSON.stringify(l),f=n.whereSql?wn(n.whereSql):void 0,p=f??null;await this.runInTransaction(async e=>{await this.assertCacheGenerationReadClaim(e,a,r?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(a,e,`create a persisted index`);let n=(await e.query(`SELECT index_name, expression_sql, where_sql
|
|
136
|
+
FROM persisted_index_registry
|
|
137
|
+
WHERE collection_id = ? AND signature = ?
|
|
138
|
+
LIMIT 1`,[a,t]))[0];n&&(n.index_name!==s||n.expression_sql!==d||n.where_sql!==p)&&await e.exec(`DROP INDEX IF EXISTS ${J(n.index_name)}`),await e.run(`INSERT INTO persisted_index_registry (
|
|
139
|
+
collection_id,
|
|
140
|
+
signature,
|
|
141
|
+
index_name,
|
|
142
|
+
expression_sql,
|
|
143
|
+
where_sql,
|
|
144
|
+
removed,
|
|
145
|
+
created_at,
|
|
146
|
+
updated_at,
|
|
147
|
+
last_used_at
|
|
148
|
+
)
|
|
149
|
+
VALUES (?, ?, ?, ?, ?, 0,
|
|
150
|
+
CAST(strftime('%s', 'now') AS INTEGER),
|
|
151
|
+
CAST(strftime('%s', 'now') AS INTEGER),
|
|
152
|
+
CAST(strftime('%s', 'now') AS INTEGER))
|
|
153
|
+
ON CONFLICT(collection_id, signature) DO UPDATE SET
|
|
154
|
+
index_name = excluded.index_name,
|
|
155
|
+
expression_sql = excluded.expression_sql,
|
|
156
|
+
where_sql = excluded.where_sql,
|
|
157
|
+
removed = 0,
|
|
158
|
+
updated_at = CAST(strftime('%s', 'now') AS INTEGER),
|
|
159
|
+
last_used_at = CAST(strftime('%s', 'now') AS INTEGER)`,[a,t,s,d,p]);let i=f?`CREATE INDEX IF NOT EXISTS ${c}
|
|
160
|
+
ON ${o} (${u})
|
|
161
|
+
WHERE ${f}`:`CREATE INDEX IF NOT EXISTS ${c}
|
|
162
|
+
ON ${o} (${u})`;await e.exec(i)})}markIndexRemoved(e,t,n){return this.runRegular(()=>this.markIndexRemovedUnscheduled(e,t,n))}async markIndexRemovedUnscheduled(e,t,n){let r=G(e,n?.cacheGenerationClaimId),i=r.collectionId;n=r.claimId?{...n,cacheGenerationClaimId:r.claimId}:n,await this.assertCacheGenerationReadClaim(this.driver,i,n?.cacheGenerationClaimId),await this.ensureCollectionReady(i,n?.cacheGenerationClaimId),await this.runInTransaction(async e=>{await this.assertCacheGenerationReadClaim(e,i,n?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(i,e,`remove a persisted index`);let r=(await e.query(`SELECT index_name
|
|
163
|
+
FROM persisted_index_registry
|
|
164
|
+
WHERE collection_id = ? AND signature = ?
|
|
165
|
+
LIMIT 1`,[i,t]))[0]?.index_name;await e.run(`UPDATE persisted_index_registry
|
|
166
|
+
SET removed = 1,
|
|
167
|
+
updated_at = CAST(strftime('%s', 'now') AS INTEGER),
|
|
168
|
+
last_used_at = CAST(strftime('%s', 'now') AS INTEGER)
|
|
169
|
+
WHERE collection_id = ? AND signature = ?`,[i,t]),r&&await e.exec(`DROP INDEX IF EXISTS ${J(r)}`)})}reserveLeadershipTerm(e,t,n){return this.reserveLeadershipTermUnscheduled(e,t,n)}async reserveLeadershipTermUnscheduled(e,t,n){let r=G(e,n?.cacheGenerationClaimId),i=r.collectionId;return n=r.claimId?{...n,cacheGenerationClaimId:r.claimId}:n,await this.assertCacheGenerationReadClaim(this.driver,i,n?.cacheGenerationClaimId),await this.ensureCollectionReady(i,n?.cacheGenerationClaimId),this.runInTransaction(async e=>{await this.assertCacheGenerationReadClaim(e,i,n?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(i,e,`reserve a leadership term`),await e.run(`INSERT INTO leader_term (collection_id, latest_term)
|
|
170
|
+
VALUES (?, ? + 1)
|
|
171
|
+
ON CONFLICT(collection_id) DO UPDATE SET
|
|
172
|
+
latest_term = MAX(leader_term.latest_term, ?) + 1`,[i,t,t]);let[r,a]=await Promise.all([this.readStreamPosition(i,e),this.readLatestRowVersion(i,e)]);return{...r,latestRowVersion:a}})}getStreamPosition(e,t){return this.getStreamPositionUnscheduled(e,t)}async getStreamPositionUnscheduled(e,t){let n=G(e,t?.cacheGenerationClaimId),r=n.collectionId;return t=n.claimId?{...t,cacheGenerationClaimId:n.claimId}:t,await this.assertCacheGenerationReadClaim(this.driver,r,t?.cacheGenerationClaimId),await this.ensureCollectionReady(r,t?.cacheGenerationClaimId),this.runInTransaction(async e=>{await this.assertCacheGenerationReadClaim(e,r,t?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(r,e,`read the stream position`);let[n,i]=await Promise.all([this.readStreamPosition(r,e),this.readLatestRowVersion(r,e)]);return{...n,latestRowVersion:i}})}async readLatestRowVersion(e,t){return(await t.query(`SELECT latest_row_version
|
|
173
|
+
FROM collection_version
|
|
174
|
+
WHERE collection_id = ?
|
|
175
|
+
LIMIT 1`,[e]))[0]?.latest_row_version??0}async readStreamPosition(e,t){let[n,r]=await Promise.all([t.query(`SELECT latest_term
|
|
176
|
+
FROM leader_term
|
|
177
|
+
WHERE collection_id = ?
|
|
178
|
+
LIMIT 1`,[e]),t.query(`SELECT MAX(seq) AS max_seq
|
|
179
|
+
FROM applied_tx
|
|
180
|
+
WHERE collection_id = ? AND term = (
|
|
181
|
+
SELECT latest_term FROM leader_term WHERE collection_id = ? LIMIT 1
|
|
182
|
+
)`,[e,e])]);return{latestTerm:n[0]?.latest_term??0,latestSeq:r[0]?.max_seq??0}}async readKeySetEvidence(e,t){let n=(await t.query(`SELECT
|
|
183
|
+
latest_row_version,
|
|
184
|
+
key_set_evidence_available,
|
|
185
|
+
key_set_evidence_incompatible AS key_set_incompatible
|
|
186
|
+
FROM collection_version
|
|
187
|
+
WHERE collection_id = ?
|
|
188
|
+
LIMIT 1`,[e]))[0];return{latestRowVersion:n?.latest_row_version??0,keySet:{status:n?.key_set_evidence_available===1?n.key_set_incompatible===1?`incompatible`:`consistent`:`unknown`}}}pullSince(e,t,n){return this.runRegular(()=>this.pullSinceUnscheduled(e,t,n))}async pullSinceUnscheduled(e,t,n){let r=G(e,n?.cacheGenerationClaimId),i=r.collectionId;n=r.claimId?{...n,cacheGenerationClaimId:r.claimId}:n,await this.assertCacheGenerationReadClaim(this.driver,i,n?.cacheGenerationClaimId);let a=await this.ensureCollectionReady(i,n?.cacheGenerationClaimId),o=J(a.tableName),s=J(a.tombstoneTableName);return this.runInTransaction(async e=>{await this.assertCacheGenerationReadClaim(e,i,n?.cacheGenerationClaimId),await this.assertCurrentSchemaVersion(i,e,`read persisted transaction deltas`);let[r,a,c,l,u]=await Promise.all([e.query(`SELECT key
|
|
189
|
+
FROM ${o}
|
|
190
|
+
WHERE row_version > ?`,[t]),e.query(`SELECT key
|
|
191
|
+
FROM ${s}
|
|
192
|
+
WHERE row_version > ?`,[t]),e.query(`SELECT latest_row_version
|
|
193
|
+
FROM collection_version
|
|
194
|
+
WHERE collection_id = ?
|
|
195
|
+
LIMIT 1`,[i]),e.query(`SELECT tx_id, row_version, replay_json, replay_requires_full_reload
|
|
196
|
+
FROM applied_tx
|
|
197
|
+
WHERE collection_id = ? AND row_version > ?
|
|
198
|
+
ORDER BY term ASC, seq ASC`,[i,t]),e.query(`SELECT MIN(row_version) AS min_row_version
|
|
199
|
+
FROM applied_tx
|
|
200
|
+
WHERE collection_id = ?`,[i])]),d=c[0]?.latest_row_version??0,f=u[0]?.min_row_version;if(d>t&&(f==null||f>t+1)||r.length+a.length>this.pullSinceReloadThreshold||l.some(e=>e.replay_requires_full_reload!==0||e.replay_json==null))return{latestRowVersion:d,requiresFullReload:!0};let p=e=>{try{return xt(e)}catch(t){throw new ae(`${e}: ${t.message}`)}},m=l.map(e=>{let t=X(e.replay_json??`null`);if(!t)throw new y(`missing replay payload for applied_tx row`);return t});return m.reduce((e,t)=>e+t.changedRows.length+t.deletedKeys.length+t.rowMetadataMutations.length+t.collectionMetadataMutations.length,0)>this.pullSinceReloadThreshold?{latestRowVersion:d,requiresFullReload:!0}:{latestRowVersion:d,requiresFullReload:!1,changedKeys:r.map(e=>p(e.key)),deletedKeys:a.map(e=>p(e.key)),deltas:m}})}async loadSubsetInternal(e,t,n=this.driver){let r=J(e.tableName),i=t.where?Q(t.where):{supported:!1,sql:``,params:[]},a=t.where?xn(t.where,i):void 0,o=Sn(t.orderBy),s=[],c=`SELECT key, value, metadata, row_version FROM ${r}`;a&&(c=`${c} WHERE ${a.sql}`,s.push(...a.params)),t.orderBy&&o.supported&&(c=`${c} ORDER BY ${o.sql}, key ASC`,s.push(...o.params)),s.length>(n.maxBoundParameters??this.driver.maxBoundParameters??999)&&(c=`SELECT key, value, metadata, row_version FROM ${r}`,s.length=0);let l=fn(await n.query(c,s)),u=this.applyInMemoryWhere(l,t.where),d=this.applyInMemoryOrderBy(u,t.orderBy);return this.applyInMemoryPagination(d,t.limit,t.offset)}applyInMemoryWhere(e,t){if(!t)return e;let n=Qt(t);return e.filter(e=>l(n(e.value)))}applyInMemoryOrderBy(e,t){if(!t||t.length===0)return e;let n=t.map(e=>({evaluator:Qt(e.expression),compareOptions:e.compareOptions})),r=[...e];return r.sort((e,t)=>{for(let r of n){let n=en(r.evaluator(e.value),r.evaluator(t.value),r.compareOptions);if(n!==0)return r.compareOptions.direction===`desc`?n*-1:n}let r=q(e.key),i=q(t.key);return r<i?-1:+(r>i)}),r}applyInMemoryPagination(e,t,n){let r=n??0;return t===void 0?e.slice(r):e.slice(r,r+t)}async touchRequiredIndexes(e,t,n=this.driver){if(!(!t||t.length===0))for(let r of t)await n.run(`UPDATE persisted_index_registry
|
|
201
|
+
SET last_used_at = CAST(strftime('%s', 'now') AS INTEGER),
|
|
202
|
+
updated_at = CAST(strftime('%s', 'now') AS INTEGER)
|
|
203
|
+
WHERE collection_id = ? AND signature = ? AND removed = 0`,[e,r])}async pruneAppliedTxRows(e,t=this.driver){if(this.appliedTxPruneMaxAgeSeconds!==void 0&&this.appliedTxPruneMaxAgeSeconds>0&&await t.run(`DELETE FROM applied_tx
|
|
204
|
+
WHERE collection_id = ?
|
|
205
|
+
AND applied_at < (CAST(strftime('%s', 'now') AS INTEGER) - ?)`,[e,this.appliedTxPruneMaxAgeSeconds]),this.appliedTxPruneMaxRows===void 0||this.appliedTxPruneMaxRows<=0)return;let n=((await t.query(`SELECT COUNT(*) AS count
|
|
206
|
+
FROM applied_tx
|
|
207
|
+
WHERE collection_id = ?`,[e]))[0]?.count??0)-this.appliedTxPruneMaxRows;n<=0||await t.run(`DELETE FROM applied_tx
|
|
208
|
+
WHERE rowid IN (
|
|
209
|
+
SELECT rowid
|
|
210
|
+
FROM applied_tx
|
|
211
|
+
WHERE collection_id = ?
|
|
212
|
+
ORDER BY term ASC, seq ASC
|
|
213
|
+
LIMIT ?
|
|
214
|
+
)`,[e,n])}async ensureCollectionReady(e,t){await this.ensureInitialized();let n=this.collectionTableCache.get(e);if(n)return n;let r=this.collectionTableLoads.get(e);if(r)return r;let i=this.ensureCollectionReadyInternal(e,t);this.collectionTableLoads.set(e,i);try{return await i}finally{this.collectionTableLoads.delete(e)}}async loadCollectionRegistration(e){return(await this.driver.query(`SELECT table_name, tombstone_table_name, schema_version
|
|
215
|
+
FROM collection_registry
|
|
216
|
+
WHERE collection_id = ?
|
|
217
|
+
LIMIT 1`,[e]))[0]}async ensureCollectionReadyInternal(e,t){let n=t!==void 0||Lt(e)&&(await this.driver.query(`SELECT physical_id FROM cache_generation WHERE physical_id = ?`,[e]))[0]!==void 0,r=await this.loadCollectionRegistration(e);if(!r){let n=Tt(e,`c`),i=Tt(e,`t`);if(await this.runInTransaction(async r=>{await this.assertCacheGenerationReadClaim(r,e,t),await r.run(`INSERT INTO collection_registry (
|
|
218
|
+
collection_id,
|
|
219
|
+
table_name,
|
|
220
|
+
tombstone_table_name,
|
|
221
|
+
schema_version,
|
|
222
|
+
updated_at
|
|
223
|
+
)
|
|
224
|
+
VALUES (?, ?, ?, ?, CAST(strftime('%s', 'now') AS INTEGER))
|
|
225
|
+
ON CONFLICT DO NOTHING`,[e,n,i,this.schemaVersion])}),r=await this.loadCollectionRegistration(e),!r)throw new y(`Unable to register persistence tables for collection "${e}"`)}let i=r.table_name,a=r.tombstone_table_name;r.schema_version!==this.schemaVersion&&await this.handleSchemaMismatch(e,r.schema_version,this.schemaVersion,i,a,t);let o=J(i),s=J(a);if(await this.driver.exec(`CREATE TABLE IF NOT EXISTS ${o} (
|
|
226
|
+
key TEXT PRIMARY KEY,
|
|
227
|
+
value TEXT NOT NULL,
|
|
228
|
+
metadata TEXT,
|
|
229
|
+
row_version INTEGER NOT NULL
|
|
230
|
+
)`),await this.driver.exec(`CREATE INDEX IF NOT EXISTS ${J(`${i}_row_version_idx`)}
|
|
231
|
+
ON ${o} (row_version)`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS ${s} (
|
|
232
|
+
key TEXT PRIMARY KEY,
|
|
233
|
+
value TEXT,
|
|
234
|
+
row_version INTEGER NOT NULL,
|
|
235
|
+
deleted_at TEXT NOT NULL
|
|
236
|
+
)`),await this.driver.exec(`CREATE INDEX IF NOT EXISTS ${J(`${a}_row_version_idx`)}
|
|
237
|
+
ON ${s} (row_version)`),await this.driver.run(`INSERT INTO collection_version (
|
|
238
|
+
collection_id,
|
|
239
|
+
latest_row_version,
|
|
240
|
+
key_set_evidence_available,
|
|
241
|
+
key_set_evidence_incompatible
|
|
242
|
+
)
|
|
243
|
+
VALUES (?, 0, 1, 0)
|
|
244
|
+
ON CONFLICT(collection_id) DO NOTHING`,[e]),await this.driver.run(`INSERT INTO collection_reset_epoch (collection_id, reset_epoch, updated_at)
|
|
245
|
+
VALUES (?, 0, CAST(strftime('%s', 'now') AS INTEGER))
|
|
246
|
+
ON CONFLICT(collection_id) DO NOTHING`,[e]),await this.ensureCollectionKeyEvidenceTriggers(e,i),n&&!(await this.driver.query(`SELECT physical_id FROM cache_generation WHERE physical_id = ?`,[e]))[0])throw await this.driver.exec(`DROP TABLE IF EXISTS ${J(i)}`),await this.driver.exec(`DROP TABLE IF EXISTS ${J(a)}`),await this.driver.run(`DELETE FROM collection_registry WHERE collection_id = ?`,[e]),await this.driver.run(`DELETE FROM collection_version WHERE collection_id = ?`,[e]),await this.driver.run(`DELETE FROM collection_reset_epoch WHERE collection_id = ?`,[e]),new y(`Persisted cache generation was collected before registration finished`);let c={tableName:i,tombstoneTableName:a};return this.collectionTableCache.set(e,c),c}async ensureCollectionKeyEvidenceTriggers(e,t){let n=J(t),r=Z(e),i=J(`${t}_key_evidence_insert`),a=J(`${t}_key_evidence_delete`),o=J(`${t}_key_evidence_update`);await this.driver.exec(`CREATE TRIGGER IF NOT EXISTS ${i}
|
|
247
|
+
AFTER INSERT ON ${n}
|
|
248
|
+
WHEN EXISTS (
|
|
249
|
+
SELECT 1
|
|
250
|
+
FROM collection_version
|
|
251
|
+
WHERE collection_id = ${r}
|
|
252
|
+
AND key_set_evidence_available = 1
|
|
253
|
+
) AND NOT EXISTS (
|
|
254
|
+
SELECT 1
|
|
255
|
+
FROM collection_expected_keys
|
|
256
|
+
WHERE collection_id = ${r}
|
|
257
|
+
AND key = NEW.key
|
|
258
|
+
)
|
|
259
|
+
BEGIN
|
|
260
|
+
UPDATE collection_version
|
|
261
|
+
SET key_set_evidence_incompatible = 1
|
|
262
|
+
WHERE collection_id = ${r};
|
|
263
|
+
END`),await this.driver.exec(`CREATE TRIGGER IF NOT EXISTS ${a}
|
|
264
|
+
AFTER DELETE ON ${n}
|
|
265
|
+
WHEN EXISTS (
|
|
266
|
+
SELECT 1
|
|
267
|
+
FROM collection_version
|
|
268
|
+
WHERE collection_id = ${r}
|
|
269
|
+
AND key_set_evidence_available = 1
|
|
270
|
+
) AND EXISTS (
|
|
271
|
+
SELECT 1
|
|
272
|
+
FROM collection_expected_keys
|
|
273
|
+
WHERE collection_id = ${r}
|
|
274
|
+
AND key = OLD.key
|
|
275
|
+
)
|
|
276
|
+
BEGIN
|
|
277
|
+
UPDATE collection_version
|
|
278
|
+
SET key_set_evidence_incompatible = 1
|
|
279
|
+
WHERE collection_id = ${r};
|
|
280
|
+
END`),await this.driver.exec(`CREATE TRIGGER IF NOT EXISTS ${o}
|
|
281
|
+
AFTER UPDATE OF key ON ${n}
|
|
282
|
+
WHEN OLD.key <> NEW.key AND EXISTS (
|
|
283
|
+
SELECT 1
|
|
284
|
+
FROM collection_version
|
|
285
|
+
WHERE collection_id = ${r}
|
|
286
|
+
AND key_set_evidence_available = 1
|
|
287
|
+
)
|
|
288
|
+
BEGIN
|
|
289
|
+
UPDATE collection_version
|
|
290
|
+
SET key_set_evidence_incompatible = 1
|
|
291
|
+
WHERE collection_id = ${r};
|
|
292
|
+
END`)}async handleSchemaMismatch(e,t,n,r,i,a){if(this.schemaMismatchPolicy===`sync-absent-error`)throw new y(`Schema version mismatch for collection "${e}": found ${t}, expected ${n}. Set schemaMismatchPolicy to "sync-present-reset" or "reset" to allow automatic reset.`);let o=J(r),s=J(i);await this.runInTransaction(async r=>{await this.assertCacheGenerationReadClaim(r,e,a);let i=(await r.query(`SELECT schema_version
|
|
293
|
+
FROM collection_registry
|
|
294
|
+
WHERE collection_id = ?
|
|
295
|
+
LIMIT 1`,[e]))[0]?.schema_version;if(i===n)return;if(i!==t)throw new y(`Schema version changed concurrently for collection "${e}": found ${i??`no registry entry`} after observing ${t}; refusing to reset it to ${n}.`);let c=await r.query(`SELECT index_name
|
|
296
|
+
FROM persisted_index_registry
|
|
297
|
+
WHERE collection_id = ?`,[e]);for(let e of c)await r.exec(`DROP INDEX IF EXISTS ${J(e.index_name)}`);await r.run(`DELETE FROM collection_expected_keys
|
|
298
|
+
WHERE collection_id = ?`,[e]),await r.run(`DELETE FROM ${o}`),await r.run(`DELETE FROM ${s}`),await r.run(`DELETE FROM applied_tx
|
|
299
|
+
WHERE collection_id = ?`,[e]),await r.run(`DELETE FROM persisted_index_registry
|
|
300
|
+
WHERE collection_id = ?`,[e]),await r.run(`DELETE FROM collection_metadata
|
|
301
|
+
WHERE collection_id = ?`,[e]),await r.run(`UPDATE collection_registry
|
|
302
|
+
SET schema_version = ?,
|
|
303
|
+
updated_at = CAST(strftime('%s', 'now') AS INTEGER)
|
|
304
|
+
WHERE collection_id = ?`,[n,e]),await r.run(`INSERT INTO collection_version (
|
|
305
|
+
collection_id,
|
|
306
|
+
latest_row_version,
|
|
307
|
+
key_set_evidence_available,
|
|
308
|
+
key_set_evidence_incompatible
|
|
309
|
+
)
|
|
310
|
+
VALUES (?, 0, 1, 0)
|
|
311
|
+
ON CONFLICT(collection_id) DO UPDATE SET
|
|
312
|
+
latest_row_version = 0,
|
|
313
|
+
key_set_evidence_available = 1,
|
|
314
|
+
key_set_evidence_incompatible = 0`,[e]),await r.run(`INSERT INTO collection_reset_epoch (collection_id, reset_epoch, updated_at)
|
|
315
|
+
VALUES (?, 1, CAST(strftime('%s', 'now') AS INTEGER))
|
|
316
|
+
ON CONFLICT(collection_id) DO UPDATE SET
|
|
317
|
+
reset_epoch = collection_reset_epoch.reset_epoch + 1,
|
|
318
|
+
updated_at = CAST(strftime('%s', 'now') AS INTEGER)`,[e])})}async ensureInitialized(){if(this.initialized)return;await this.driver.exec(`CREATE TABLE IF NOT EXISTS cache_generation (
|
|
319
|
+
logical_id TEXT NOT NULL,
|
|
320
|
+
generation INTEGER NOT NULL,
|
|
321
|
+
physical_id TEXT NOT NULL UNIQUE,
|
|
322
|
+
retired INTEGER NOT NULL DEFAULT 0,
|
|
323
|
+
PRIMARY KEY (logical_id, generation)
|
|
324
|
+
)`),await this.driver.exec(`CREATE UNIQUE INDEX IF NOT EXISTS cache_generation_head
|
|
325
|
+
ON cache_generation (logical_id) WHERE retired = 0`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS cache_generation_sequence (
|
|
326
|
+
logical_id TEXT PRIMARY KEY,
|
|
327
|
+
next_generation INTEGER NOT NULL
|
|
328
|
+
)`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS cache_generation_claim (
|
|
329
|
+
claim_id TEXT PRIMARY KEY,
|
|
330
|
+
logical_id TEXT NOT NULL,
|
|
331
|
+
physical_id TEXT NOT NULL,
|
|
332
|
+
expires_at_ms INTEGER NOT NULL
|
|
333
|
+
)`);let e=await this.driver.query(`PRAGMA table_info(cache_generation_claim)`);e.some(({name:e})=>e===`logical_id`)||await this.driver.exec(`ALTER TABLE cache_generation_claim
|
|
334
|
+
ADD COLUMN logical_id TEXT NOT NULL DEFAULT ''`),e.some(({name:e})=>e===`expires_at_ms`)||await this.driver.exec(`ALTER TABLE cache_generation_claim
|
|
335
|
+
ADD COLUMN expires_at_ms INTEGER NOT NULL DEFAULT 0`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS collection_registry (
|
|
336
|
+
collection_id TEXT PRIMARY KEY,
|
|
337
|
+
table_name TEXT NOT NULL UNIQUE,
|
|
338
|
+
tombstone_table_name TEXT NOT NULL UNIQUE,
|
|
339
|
+
schema_version INTEGER NOT NULL,
|
|
340
|
+
updated_at INTEGER NOT NULL
|
|
341
|
+
)`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS persisted_index_registry (
|
|
342
|
+
collection_id TEXT NOT NULL,
|
|
343
|
+
signature TEXT NOT NULL,
|
|
344
|
+
index_name TEXT NOT NULL,
|
|
345
|
+
expression_sql TEXT NOT NULL,
|
|
346
|
+
where_sql TEXT,
|
|
347
|
+
removed INTEGER NOT NULL DEFAULT 0,
|
|
348
|
+
created_at INTEGER NOT NULL,
|
|
349
|
+
updated_at INTEGER NOT NULL,
|
|
350
|
+
last_used_at INTEGER NOT NULL,
|
|
351
|
+
PRIMARY KEY (collection_id, signature)
|
|
352
|
+
)`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS applied_tx (
|
|
353
|
+
collection_id TEXT NOT NULL,
|
|
354
|
+
term INTEGER NOT NULL,
|
|
355
|
+
seq INTEGER NOT NULL,
|
|
356
|
+
tx_id TEXT NOT NULL,
|
|
357
|
+
row_version INTEGER NOT NULL,
|
|
358
|
+
replay_json TEXT,
|
|
359
|
+
replay_requires_full_reload INTEGER NOT NULL DEFAULT 0,
|
|
360
|
+
applied_at INTEGER NOT NULL,
|
|
361
|
+
PRIMARY KEY (collection_id, term, seq)
|
|
362
|
+
)`),await this.driver.exec(`CREATE INDEX IF NOT EXISTS idx_applied_tx_collection_tx_id
|
|
363
|
+
ON applied_tx (collection_id, tx_id)`);try{await this.driver.exec(`ALTER TABLE applied_tx ADD COLUMN replay_json TEXT`)}catch(e){if(!Kt(e,`replay_json`))throw e}try{await this.driver.exec(`ALTER TABLE applied_tx ADD COLUMN replay_requires_full_reload INTEGER NOT NULL DEFAULT 0`)}catch(e){if(!Kt(e,`replay_requires_full_reload`))throw e}await this.driver.exec(`CREATE TABLE IF NOT EXISTS collection_version (
|
|
364
|
+
collection_id TEXT PRIMARY KEY,
|
|
365
|
+
latest_row_version INTEGER NOT NULL,
|
|
366
|
+
key_set_evidence_available INTEGER NOT NULL DEFAULT 0,
|
|
367
|
+
key_set_evidence_incompatible INTEGER NOT NULL DEFAULT 0
|
|
368
|
+
)`);let t=await this.driver.query(`PRAGMA table_info(collection_version)`);for(let e of[`key_set_evidence_available`,`key_set_evidence_incompatible`])if(!t.some(({name:t})=>t===e))try{await this.driver.exec(`ALTER TABLE collection_version ADD COLUMN ${e} INTEGER NOT NULL DEFAULT 0`)}catch(t){if(!Kt(t,e))throw t}await this.driver.exec(`CREATE TABLE IF NOT EXISTS collection_expected_keys (
|
|
369
|
+
collection_id TEXT NOT NULL,
|
|
370
|
+
key TEXT NOT NULL,
|
|
371
|
+
PRIMARY KEY (collection_id, key)
|
|
372
|
+
)`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS collection_metadata (
|
|
373
|
+
collection_id TEXT NOT NULL,
|
|
374
|
+
key TEXT NOT NULL,
|
|
375
|
+
value TEXT NOT NULL,
|
|
376
|
+
updated_at INTEGER NOT NULL,
|
|
377
|
+
PRIMARY KEY (collection_id, key)
|
|
378
|
+
)`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS leader_term (
|
|
379
|
+
collection_id TEXT PRIMARY KEY,
|
|
380
|
+
latest_term INTEGER NOT NULL
|
|
381
|
+
)`),await this.driver.exec(`CREATE TABLE IF NOT EXISTS schema_version (
|
|
382
|
+
scope TEXT PRIMARY KEY,
|
|
383
|
+
version INTEGER NOT NULL,
|
|
384
|
+
updated_at INTEGER NOT NULL
|
|
385
|
+
)`),await this.driver.run(`INSERT INTO schema_version (scope, version, updated_at)
|
|
386
|
+
VALUES ('global', ?, CAST(strftime('%s', 'now') AS INTEGER))
|
|
387
|
+
ON CONFLICT(scope) DO UPDATE SET
|
|
388
|
+
version = excluded.version,
|
|
389
|
+
updated_at = excluded.updated_at`,[this.schemaVersion]),await this.driver.exec(`CREATE TABLE IF NOT EXISTS collection_reset_epoch (
|
|
390
|
+
collection_id TEXT PRIMARY KEY,
|
|
391
|
+
reset_epoch INTEGER NOT NULL,
|
|
392
|
+
updated_at INTEGER NOT NULL
|
|
393
|
+
)`),this.initialized=!0}};function An(e){return new kn(e)}var jn=3e3,Mn=200,Nn=1e4,Pn=2,Fn=200,In=2,Ln=6e4,Rn=50,zn=20;function Bn(e){if(typeof e.reserveLeadershipTerm!=`function`)throw new x(`reserveLeadershipTerm`)}var Vn=class{constructor(e){this.nodeId=s(),this.collectionAdapters=new Map,this.collectionClaimIds=new Map,this.remoteSubsetOwners=new Map,this.remoteSubsetIds=new Map,this.outboundRemoteSubsetAcquisitions=new Map,this.inboundRemoteSubsetAcquisitions=new Map,this.releasedRemoteSubsetAcquisitionTimes=new Map,this.collections=new Map,this.pendingRPCs=new Map,this.appliedEnvelopes=new Map,this.inFlightEnvelopes=new Map,this.appliedEnvelopePruneTimer=null,this.rejectDisposed=null,this.disposed=!1,e.adapter&&Bn(e.adapter),this.dbName=e.dbName,this.coordinatorName=e.coordinatorName,this.defaultAdapter=e.adapter??null,this.channel=new BroadcastChannel(`tsdb:coord:${this.dbName}`),this.channel.onmessage=e=>{this.onChannelMessage(e.data)},this.disposedPromise=new Promise((e,t)=>{this.rejectDisposed=t}),this.disposedPromise.catch(()=>void 0)}isDisposed(){return this.disposed}participatesInLeadership(e){return e.participatesInLeadership}requireAdapter(e){let t=this.collectionAdapters.get(e);if(!t&&this.defaultAdapter&&(t=this.defaultAdapter,this.collectionAdapters.set(e,t)),!t)throw Error(`${this.coordinatorName}: adapter not set for collection "${e}". Call setAdapterForCollection() before using leader-side operations.`);return t}setAdapter(e){Bn(e),this.defaultAdapter=e}setAdapterForCollection(e,t,n){Bn(t),this.collectionAdapters.set(e,t),n?this.collectionClaimIds.set(e,n):this.collectionClaimIds.delete(e)}registerRemoteSubsetOwner(e,t){if(this.remoteSubsetOwners.has(e))throw new w(e);this.remoteSubsetOwners.set(e,t);for(let t of this.outboundRemoteSubsetAcquisitions.values())t.collectionId===e&&(t.acquiredLeaderId=null,t.forceReplay=!0);return this.replayRemoteSubsetAcquisitions(e),this.rebindRemoteInboundSubsetAcquisitions(e,t),()=>{this.remoteSubsetOwners.get(e)===t&&(this.remoteSubsetOwners.delete(e),this.releaseInboundRemoteSubsetAcquisitions(e,t))}}getNodeId(){return this.nodeId}subscribe(e,t){let n=this.ensureCollectionState(e);return n.subscribers.add(t),()=>{n.subscribers.delete(t),n.subscribers.size===0&&(n.participatesInLeadership=!1,this.releaseCollectionIfUnused(e,n))}}publish(e,t){this.channel.postMessage(t)}isLeader(e){return this.collections.get(e)?.isLeader??!1}async ensureLeadership(e){let t=this.ensureCollectionState(e);t.isLeader||await this.acquireLeadership(e,t)}async requestEnsureRemoteSubset(e,t){let n=he(t),r=ve(t,n),i=this.remoteSubsetIds.get(e);i||(i=new WeakMap,this.remoteSubsetIds.set(e,i));let a=i.get(t),o=a?this.outboundRemoteSubsetAcquisitions.get($(e,a)):void 0;o||(a=s(),i.set(t,a),o={collectionId:e,acquisitionId:a,options:n,localOptions:r,acquiredLeaderId:null,inFlight:null,release:null,releaseRequested:!1,forceReplay:!1,retryTimer:null,retryAttempts:0},this.outboundRemoteSubsetAcquisitions.set($(e,a),o));try{await this.acquireRemoteSubset(o)}catch(n){if(t.signal?.aborted){o.releaseRequested=!0,this.cancelRemoteSubsetReplayRetry(o),this.postRemoteSubsetRelease(o);let n=$(e,o.acquisitionId);this.outboundRemoteSubsetAcquisitions.get(n)===o&&(this.outboundRemoteSubsetAcquisitions.delete(n),i.delete(t))}throw n}}async requestReleaseRemoteSubset(e,t){let n=this.remoteSubsetIds.get(e),r=n?.get(t);if(!r)return;let i=$(e,r),a=this.outboundRemoteSubsetAcquisitions.get(i);if(a){a.releaseRequested=!0,this.cancelRemoteSubsetReplayRetry(a),a.release||=(async()=>{let o={type:`rpc:releaseRemoteSubset:req`,rpcId:s(),acquisitionId:r},c=this.isLeader(e),l=c;try{let t=c?await this.handleReleaseRemoteSubset(e,o,this.nodeId):await this.sendRPC(e,o);if(l=!0,!t.ok)throw Error(`releaseRemoteSubset failed: ${t.error}`)}finally{l&&this.outboundRemoteSubsetAcquisitions.get(i)===a&&(this.outboundRemoteSubsetAcquisitions.delete(i),n.delete(t))}})();try{await a.release}catch(e){throw this.scheduleRemoteSubsetReleaseRetry(a,t),e}finally{a.release=null}}}scheduleRemoteSubsetReleaseRetry(e,t){let n=$(e.collectionId,e.acquisitionId);this.isDisposed()||this.outboundRemoteSubsetAcquisitions.get(n)!==e||e.retryTimer!==null||(e.retryTimer=setTimeout(()=>{e.retryTimer=null,this.requestReleaseRemoteSubset(e.collectionId,t).catch(()=>void 0)},Fn))}async acquireRemoteSubset(e){if(e.inFlight)return e.inFlight;let t={localOwner:!1},n,r,i=new Promise((e,t)=>{n=e,r=t});e.inFlight=i,(async()=>{let n={type:`rpc:ensureRemoteSubset:req`,rpcId:s(),acquisitionId:e.acquisitionId,options:e.options},r=this.collections.get(e.collectionId);r?.participatesInLeadership&&!r.isLeader&&r.leaderId===null&&await this.waitForLeadershipRoute(e.collectionId,r,e.localOptions.signal),t.localOwner=this.isLeader(e.collectionId);let i;try{i=t.localOwner?await this.handleEnsureRemoteSubset(e.collectionId,n,this.nodeId,e.localOptions):await this.sendRPC(e.collectionId,n)}catch(e){throw t.localOwner||e instanceof T?e:new T(`Remote subset transport failed`,e)}if(!i.ok)throw i.retryable?new T(i.error):Error(`ensureRemoteSubset failed: ${i.error}`);e.acquiredLeaderId=i.leaderId})().then(n,r);let a=!1;try{await i,a=!0,e.releaseRequested||this.cancelRemoteSubsetReplayRetry(e)}finally{e.inFlight===i&&(e.inFlight=null);let t=this.collections.get(e.collectionId),n=t?.isLeader?this.nodeId:t?.leaderId??null,r=$(e.collectionId,e.acquisitionId);a&&!e.releaseRequested&&this.outboundRemoteSubsetAcquisitions.get(r)===e&&(e.forceReplay||n!==null&&e.acquiredLeaderId!==n)&&(e.forceReplay=!1,this.acquireRemoteSubset(e).catch(t=>{this.scheduleRemoteSubsetReplayRetry(e,t)}))}}async requestEnsurePersistedIndex(e,t,n,r,i=!1,a){if(this.isLeader(e)){if(i)return;let o=r??this.requireAdapter(e);a?await o.ensureIndex(W(e,a),t,n,{cacheGenerationClaimId:a}):await o.ensureIndex(U(e),t,n);return}let o=await this.sendRPC(e,{type:`rpc:ensurePersistedIndex:req`,rpcId:s(),signature:t,spec:n,cacheGenerationClaimId:a});if(!o.ok)throw Error(`ensurePersistedIndex failed: ${o.error??`unknown error`}`)}async requestApplyLocalMutations(e,t,n){let r=this.waitForInitialRoute(e);return r&&await r,this.isLeader(e)?this.handleApplyLocalMutations(e,{type:`rpc:applyLocalMutations:req`,rpcId:s(),envelopeId:s(),mutations:t,cacheGenerationClaimId:n}):this.sendRPC(e,{type:`rpc:applyLocalMutations:req`,rpcId:s(),envelopeId:s(),mutations:t,cacheGenerationClaimId:n})}async requestApplyCommittedTx(e,t,n){let r=this.waitForInitialRoute(e);r&&await r;let i={type:`rpc:applyCommittedTx:req`,rpcId:s(),envelopeId:s(),tx:t};return this.isLeader(e)?this.handleApplyCommittedTx(e,i,n):this.sendRPC(e,i)}async reconcileCommittedTx(e,t,n,r){let i=this.waitForInitialRoute(e);i&&await i;let a;for(let i=0;i<=Pn;i++){i>0&&await Gn(Fn*i);let o={type:`rpc:reconcileCommittedTx:req`,rpcId:s(),tx:t,anchor:n};if(a=this.isLeader(e)?await this.handleReconcileCommittedTx(e,o,r):await this.sendRPC(e,o),a.ok||a.code!==`NOT_LEADER`)return a}return a}async pullSince(e,t,n,r){return this.isLeader(e)?this.handlePullSince(e,{type:`rpc:pullSince:req`,rpcId:s(),fromRowVersion:t,cacheGenerationClaimId:r},n):this.sendRPC(e,{type:`rpc:pullSince:req`,rpcId:s(),fromRowVersion:t,cacheGenerationClaimId:r})}dispose(){if(this.disposed)return;this.disposed=!0;let e=Error(`coordinator disposed`);this.rejectDisposed?.(e),this.rejectDisposed=null;for(let e of this.outboundRemoteSubsetAcquisitions.values())this.cancelRemoteSubsetReplayRetry(e),this.postRemoteSubsetRelease(e);this.outboundRemoteSubsetAcquisitions.clear(),this.remoteSubsetIds.clear();for(let[e,t]of this.collections)this.releaseLeadership(e,t);for(let[,t]of this.pendingRPCs)clearTimeout(t.timer),t.reject(e);this.pendingRPCs.clear(),this.appliedEnvelopePruneTimer!==null&&(clearTimeout(this.appliedEnvelopePruneTimer),this.appliedEnvelopePruneTimer=null),this.channel.close(),this.collections.clear(),this.collectionAdapters.clear(),this.collectionClaimIds.clear();for(let e of this.remoteSubsetOwners.keys())this.releaseInboundRemoteSubsetAcquisitions(e);this.remoteSubsetOwners.clear(),this.inboundRemoteSubsetAcquisitions.clear(),this.releasedRemoteSubsetAcquisitionTimes.clear(),this.appliedEnvelopes.clear(),this.inFlightEnvelopes.clear()}getOrCreateCollectionState(e){let t=this.collections.get(e);return t||(t={participatesInLeadership:!1,isLeader:!1,leaderId:null,lockAbortController:null,heartbeatTimer:null,latestTerm:0,latestSeq:0,latestRowVersion:0,subscribers:new Set,routeWaiters:new Set},this.collections.set(e,t)),t}ensureCollectionState(e){let t=this.getOrCreateCollectionState(e);return t.participatesInLeadership||(t.participatesInLeadership=!0,this.acquireLeadership(e,t)),t}async acquireLeadership(e,t){if(this.disposed||!t.participatesInLeadership||t.isLeader)return;let n=`tsdb:leader:${this.dbName}:${e}`,r=new AbortController;t.lockAbortController?.abort(),t.lockAbortController=r;try{await navigator.locks.request(n,{signal:r.signal},async()=>{if(!(this.isDisposed()||!this.participatesInLeadership(t)||this.collections.get(e)!==t))try{let n=this.requireAdapter(e),i=n.reserveLeadershipTerm;if(!i)throw new x(`reserveLeadershipTerm`);let a=await this.withWriterLock(()=>{let r=this.collectionClaimIds.get(e);return i.call(n,r?W(e,r):U(e),t.latestTerm,{cacheGenerationClaimId:r})});if(t.latestTerm=a.latestTerm,t.latestSeq=a.latestSeq,t.latestRowVersion=a.latestRowVersion,this.isDisposed()||!this.participatesInLeadership(t)||this.collections.get(e)!==t||r.signal.aborted||t.lockAbortController!==r)return;t.isLeader=!0,t.leaderId=this.nodeId,this.notifyRouteWaiters(t),this.emitHeartbeat(e,t),this.replayRemoteSubsetAcquisitions(e),t.heartbeatTimer=setInterval(()=>{this.emitHeartbeat(e,t)},jn),await new Promise(e=>{let t=()=>{r.signal.removeEventListener(`abort`,t),e()};if(r.signal.aborted){e();return}r.signal.addEventListener(`abort`,t)})}finally{this.releaseInboundRemoteSubsetAcquisitions(e),t.isLeader=!1,t.leaderId=null,t.heartbeatTimer&&=(clearInterval(t.heartbeatTimer),null)}})}catch(n){if(n instanceof DOMException&&n.name===`AbortError`)return;console.warn(`Failed to acquire leadership for ${e}:`,n),!this.isDisposed()&&this.participatesInLeadership(t)&&this.collections.get(e)===t&&await Gn(Mn)}finally{t.lockAbortController===r&&(t.lockAbortController=null)}!this.isDisposed()&&this.participatesInLeadership(t)&&this.collections.get(e)===t&&t.lockAbortController===null&&this.acquireLeadership(e,t)}waitForInitialRoute(e){let t=this.collections.get(e);if(t?.participatesInLeadership&&!t.isLeader&&t.leaderId===null)return this.channel.postMessage({v:1,dbName:this.dbName,collectionId:e,senderId:this.nodeId,ts:Date.now(),payload:{type:`leader:routeRequest`}}),this.waitForLeadershipRoute(e,t,void 0,Nn)}waitForLeadershipRoute(e,t,n,r){return t.isLeader||t.leaderId!==null?Promise.resolve():new Promise((i,a)=>{let o,s=()=>{t.routeWaiters?.delete(l),n?.removeEventListener(`abort`,c),o!==void 0&&clearTimeout(o)},c=()=>{s(),a(new DOMException(`Remote subset acquisition aborted`,`AbortError`))},l=()=>{if(this.isDisposed()||!t.participatesInLeadership){s(),a(Error(`${this.coordinatorName}: leadership route closed for collection "${e}"`));return}(t.isLeader||t.leaderId!==null)&&(s(),i())};(t.routeWaiters??=new Set).add(l),r!==void 0&&(o=setTimeout(()=>{s(),a(Error(`${this.coordinatorName}: leadership route for collection "${e}" timed out after ${r}ms`))},r)),n?.addEventListener(`abort`,c,{once:!0}),n?.aborted?c():l()})}notifyRouteWaiters(e){for(let t of Array.from(e.routeWaiters??[]))t()}releaseLeadership(e,t){this.releaseInboundRemoteSubsetAcquisitions(e),t.lockAbortController&&=(t.lockAbortController.abort(),null),t.heartbeatTimer&&=(clearInterval(t.heartbeatTimer),null),t.isLeader=!1,t.leaderId=null,this.notifyRouteWaiters(t)}releaseCollectionIfUnused(e,t){if(t.subscribers.size>0||this.collections.get(e)!==t)return;this.releaseLeadership(e,t),this.collections.delete(e),this.collectionAdapters.delete(e),this.collectionClaimIds.delete(e);let n=`${JSON.stringify([e]).slice(0,-1)},`;for(let e of this.appliedEnvelopes.keys())e.startsWith(n)&&this.appliedEnvelopes.delete(e);this.pruneAppliedEnvelopes()}postRemoteSubsetRelease(e){if(e.release)return;let t={type:`rpc:releaseRemoteSubset:req`,rpcId:s(),acquisitionId:e.acquisitionId};if(this.isLeader(e.collectionId)){this.handleReleaseRemoteSubset(e.collectionId,t,this.nodeId).catch(()=>{});return}this.channel.postMessage({v:1,dbName:this.dbName,collectionId:e.collectionId,senderId:this.nodeId,ts:Date.now(),payload:t})}cancelRemoteSubsetReplayRetry(e){e.retryTimer!==null&&(clearTimeout(e.retryTimer),e.retryTimer=null),e.retryAttempts=0}scheduleRemoteSubsetReplayRetry(e,t){let n=$(e.collectionId,e.acquisitionId);!(t instanceof T)||this.isDisposed()||this.outboundRemoteSubsetAcquisitions.get(n)!==e||e.releaseRequested||e.retryTimer!==null||e.retryAttempts>=In||(e.retryAttempts++,e.retryTimer=setTimeout(()=>{e.retryTimer=null,!(this.isDisposed()||this.outboundRemoteSubsetAcquisitions.get(n)!==e||e.releaseRequested)&&this.acquireRemoteSubset(e).catch(t=>{this.scheduleRemoteSubsetReplayRetry(e,t)})},Fn))}async replayRemoteSubsetAcquisitions(e){if(this.isDisposed())return;let t=this.collections.get(e),n=t?.isLeader?this.nodeId:t?.leaderId;if(!n)return;let r=[];for(let t of this.outboundRemoteSubsetAcquisitions.values())if(!(t.collectionId!==e||t.releaseRequested||!t.forceReplay&&t.acquiredLeaderId===n)){if(t.inFlight){t.forceReplay=!0;continue}t.forceReplay=!1,r.push(this.acquireRemoteSubset(t).catch(e=>{this.scheduleRemoteSubsetReplayRetry(t,e)}))}await Promise.all(r)}emitHeartbeat(e,t){let n={v:1,dbName:this.dbName,collectionId:e,senderId:this.nodeId,ts:Date.now(),payload:{type:`leader:heartbeat`,term:t.latestTerm,leaderId:this.nodeId,latestSeq:t.latestSeq,latestRowVersion:t.latestRowVersion}};this.channel.postMessage(n)}onChannelMessage(e){if(!Hn(e))return;let t=e;if(t.senderId===this.nodeId)return;let n=t.payload;if(!n||typeof n!=`object`)return;let r=n.type;if(r===`leader:routeRequest`){let e=this.collections.get(t.collectionId);e?.isLeader&&this.emitHeartbeat(t.collectionId,e);return}if(r===`leader:heartbeat`){let e=n;if(typeof e.leaderId==`string`&&typeof e.term==`number`&&typeof e.latestSeq==`number`&&typeof e.latestRowVersion==`number`){let n=this.getOrCreateCollectionState(t.collectionId);if(n.isLeader||e.term<n.latestTerm)return;let r=n.leaderId!==e.leaderId;n.leaderId=e.leaderId,n.latestTerm=Math.max(n.latestTerm,e.term),n.latestSeq=Math.max(n.latestSeq,e.latestSeq),n.latestRowVersion=Math.max(n.latestRowVersion,e.latestRowVersion),this.notifyRouteWaiters(n),r&&this.replayRemoteSubsetAcquisitions(t.collectionId)}}if(r&&r.endsWith(`:res`)){let e=n.rpcId;if(e&&this.pendingRPCs.has(e)){let t=this.pendingRPCs.get(e);this.pendingRPCs.delete(e),clearTimeout(t.timer),t.resolve(n);return}}if(r&&r.endsWith(`:req`)){if(!Un(n))return;let e=t.collectionId;this.isLeader(e)&&this.handleRPCRequest(e,n,t.senderId);return}let i=this.collections.get(t.collectionId);if(i)for(let e of i.subscribers)e(t)}async sendRPC(e,t){if(this.isDisposed())throw Error(`coordinator disposed`);let n,r,i=Yn(t)?t.type:void 0,a=i?this.captureMutationRoute(e):void 0;for(let o=0;o<=Pn;o++){if(o>0&&await Promise.race([Gn(Fn*o),this.disposedPromise]),this.isDisposed())throw Error(`coordinator disposed`);if(a&&i&&r!==void 0&&this.assertMutationRouteUnchanged(e,i,a,r),this.isLeader(e))return await this.dispatchRPCRequest(e,t,this.nodeId);try{return await this.sendRPCOnce(e,t)}catch(t){if(this.isDisposed())throw t;r??=t,a&&i&&this.assertMutationRouteUnchanged(e,i,a,r),n=t instanceof Error?t:Error(String(t))}}throw n??Error(`RPC failed after retries`)}captureMutationRoute(e){let t=this.collections.get(e);return{leaderId:t?.isLeader?this.nodeId:t?.leaderId??null,term:t?.latestTerm??null}}assertMutationRouteUnchanged(e,t,n,r){let i=this.captureMutationRoute(e);if(!(n.leaderId!==null&&n.term!==null&&i.leaderId===n.leaderId&&i.term===n.term))throw new C({collectionId:e,requestType:t,previousLeaderId:n.leaderId,previousTerm:n.term,currentLeaderId:i.leaderId,currentTerm:i.term,cause:r})}sendRPCOnce(e,t){return new Promise((n,r)=>{let i=t.rpcId,a=setTimeout(()=>{this.pendingRPCs.delete(i),r(Error(`RPC ${t.type} timed out after ${Nn}ms`))},Nn);this.pendingRPCs.set(i,{resolve:n,reject:r,timer:a});let o={v:1,dbName:this.dbName,collectionId:e,senderId:this.nodeId,ts:Date.now(),payload:t};this.channel.postMessage(o)})}async handleRPCRequest(e,t,n){let r;try{r=await this.dispatchRPCRequest(e,t,n)}catch(e){r=Jn(t,e)}if(this.isDisposed())return;let i={v:1,dbName:this.dbName,collectionId:e,senderId:this.nodeId,ts:Date.now(),payload:r};this.channel.postMessage(i)}dispatchRPCRequest(e,t,n){switch(t.type){case`rpc:ensureRemoteSubset:req`:return this.handleEnsureRemoteSubset(e,t,n);case`rpc:releaseRemoteSubset:req`:return this.handleReleaseRemoteSubset(e,t,n);case`rpc:ensurePersistedIndex:req`:return this.handleEnsurePersistedIndex(e,t);case`rpc:applyLocalMutations:req`:return this.handleApplyLocalMutations(e,t);case`rpc:applyCommittedTx:req`:return this.handleApplyCommittedTx(e,t);case`rpc:reconcileCommittedTx:req`:return this.handleReconcileCommittedTx(e,t);case`rpc:pullSince:req`:return this.handlePullSince(e,t)}}async handleEnsureRemoteSubset(e,t,n,r){this.pruneReleasedRemoteSubsetAcquisitions();let i=qn(e,n,t.acquisitionId),a=this.inboundRemoteSubsetAcquisitions.get(i),o=a&&`awaitingOwner`in a?a:void 0;if(a){if(`owner`in a){if(!a.released)return await a.load,{type:`rpc:ensureRemoteSubset:res`,rpcId:t.rpcId,ok:!0,leaderId:this.nodeId};if(await a.release,a.terminalRelease)return{type:`rpc:ensureRemoteSubset:res`,rpcId:t.rpcId,ok:!0,leaderId:this.nodeId};this.inboundRemoteSubsetAcquisitions.get(i)===a&&this.inboundRemoteSubsetAcquisitions.delete(i)}else if(!(`awaitingOwner`in a))return{type:`rpc:ensureRemoteSubset:res`,rpcId:t.rpcId,ok:!0,leaderId:this.nodeId}}let s=this.remoteSubsetOwners.get(e);if(!s)throw new T(`${this.coordinatorName}: no remote subset owner registered for collection "${e}"`);return await this.startRemoteSubsetOwnerAcquisition({collectionId:e,requesterId:n,acquisitionId:t.acquisitionId,owner:s,options:o?.options??r??t.options,restoreOnSynchronousFailure:o}),{type:`rpc:ensureRemoteSubset:res`,rpcId:t.rpcId,ok:!0,leaderId:this.nodeId}}async handleReleaseRemoteSubset(e,t,n){this.pruneReleasedRemoteSubsetAcquisitions();let r=qn(e,n,t.acquisitionId),i=this.inboundRemoteSubsetAcquisitions.get(r);if(!i)this.setReleasedRemoteSubsetAcquisition(r,{collectionId:e,requesterId:n,acquisitionId:t.acquisitionId,released:!0});else if(`owner`in i){i.terminalRelease=!0;try{await this.releaseRemoteSubsetAcquisition(i)}finally{this.inboundRemoteSubsetAcquisitions.get(r)===i&&this.setReleasedRemoteSubsetAcquisition(r,{collectionId:e,requesterId:n,acquisitionId:t.acquisitionId,released:!0})}}else `awaitingOwner`in i&&this.setReleasedRemoteSubsetAcquisition(r,{collectionId:e,requesterId:n,acquisitionId:t.acquisitionId,released:!0});return{type:`rpc:releaseRemoteSubset:res`,rpcId:t.rpcId,ok:!0}}releaseRemoteSubsetAcquisition(e){return e.release?e.release:(e.released=!0,e.release=(async()=>{try{await e.admitted,e.transferred&&await Ue(e.owner,e.options)}finally{if(!e.terminalRelease){let t=qn(e.collectionId,e.requesterId,e.acquisitionId);this.inboundRemoteSubsetAcquisitions.get(t)===e&&this.inboundRemoteSubsetAcquisitions.set(t,{collectionId:e.collectionId,requesterId:e.requesterId,acquisitionId:e.acquisitionId,options:e.options,released:!0,awaitingOwner:!0})}}})(),e.release)}releaseInboundRemoteSubsetAcquisitions(e,t){for(let n of this.inboundRemoteSubsetAcquisitions.values())!(`owner`in n)||n.collectionId!==e||t&&n.owner!==t||this.releaseRemoteSubsetAcquisition(n).catch(()=>void 0)}rebindRemoteInboundSubsetAcquisitions(e,t){for(let n of this.inboundRemoteSubsetAcquisitions.values()){if(`awaitingOwner`in n){n.collectionId===e&&n.requesterId!==this.nodeId&&this.bindAwaitingRemoteSubsetAcquisition(n,t).catch(()=>{});continue}!(`owner`in n)||n.collectionId!==e||n.requesterId===this.nodeId||!n.released||n.terminalRelease||this.rebindRemoteInboundSubsetAcquisition(n,t).catch(()=>void 0)}}async rebindRemoteInboundSubsetAcquisition(e,t){if(await e.release,e.terminalRelease||this.remoteSubsetOwners.get(e.collectionId)!==t)return;let n=qn(e.collectionId,e.requesterId,e.acquisitionId),r=this.inboundRemoteSubsetAcquisitions.get(n);if(r&&r!==e){`awaitingOwner`in r&&await this.bindAwaitingRemoteSubsetAcquisition(r,t);return}let i={collectionId:e.collectionId,requesterId:e.requesterId,acquisitionId:e.acquisitionId,options:e.options,released:!0,awaitingOwner:!0};this.inboundRemoteSubsetAcquisitions.set(n,i),await this.bindAwaitingRemoteSubsetAcquisition(i,t)}async bindAwaitingRemoteSubsetAcquisition(e,t){if(this.remoteSubsetOwners.get(e.collectionId)!==t)return;let n=qn(e.collectionId,e.requesterId,e.acquisitionId);this.inboundRemoteSubsetAcquisitions.get(n)===e&&await this.startRemoteSubsetOwnerAcquisition({collectionId:e.collectionId,requesterId:e.requesterId,acquisitionId:e.acquisitionId,owner:t,options:e.options,restoreOnSynchronousFailure:e})}async startRemoteSubsetOwnerAcquisition(e){let t=qn(e.collectionId,e.requesterId,e.acquisitionId),n={collectionId:e.collectionId,requesterId:e.requesterId,acquisitionId:e.acquisitionId,owner:e.owner,options:e.options,load:Promise.resolve(),admitted:Promise.resolve(),transferred:!1,released:!1,terminalRelease:!1,release:null};this.releasedRemoteSubsetAcquisitionTimes.delete(t),this.inboundRemoteSubsetAcquisitions.set(t,n);let r;n.admitted=new Promise(e=>{r=e});let i,a;n.load=new Promise((e,t)=>{i=e,a=t});try{let t=e.owner(n.options);n.transferred=!0,Promise.resolve(t).then(i,a)}catch(e){a(e)}finally{r()}try{await n.load}catch(r){throw n.transferred?await this.releaseRemoteSubsetAcquisition(n).catch(()=>void 0):this.inboundRemoteSubsetAcquisitions.get(t)===n&&(e.restoreOnSynchronousFailure?this.inboundRemoteSubsetAcquisitions.set(t,e.restoreOnSynchronousFailure):this.inboundRemoteSubsetAcquisitions.delete(t)),r}}async handleEnsurePersistedIndex(e,t){return await this.withScheduledWriterLock(e,n=>t.cacheGenerationClaimId?n.ensureIndex(W(e,t.cacheGenerationClaimId),t.signature,t.spec,{cacheGenerationClaimId:t.cacheGenerationClaimId}):n.ensureIndex(U(e),t.signature,t.spec)),{type:`rpc:ensurePersistedIndex:res`,rpcId:t.rpcId,ok:!0}}async handleApplyLocalMutations(e,t){let n=Kn(e,t.envelopeId);return this.runDeduplicatedEnvelope({envelopeKey:n,rpcId:t.rpcId,selectApplied:e=>e.requestType===`rpc:applyLocalMutations:req`?e.response:void 0,selectInFlight:e=>e.requestType===`rpc:applyLocalMutations:req`?e.response:void 0,conflict:e=>({type:`rpc:applyLocalMutations:res`,rpcId:t.rpcId,ok:!1,code:`CONFLICT`,error:`envelope ${t.envelopeId} ${e}`}),apply:()=>this.applyLocalMutationsOnce(e,t),createPending:e=>({requestType:t.type,response:e})})}async applyLocalMutationsOnce(e,t){if(this.collectionClaimIds.has(e)&&!t.cacheGenerationClaimId)throw new y(`A managed local mutation requires a persisted cache claim`);let n=this.collections.get(e);if(!n||!n.isLeader)return{type:`rpc:applyLocalMutations:res`,rpcId:t.rpcId,ok:!1,code:`NOT_LEADER`,error:`not the leader for ${e}`};let r=[];for(let e of t.mutations)!(`metadataChanged`in e)||!e.metadataChanged||r.push(e.metadata===void 0?{type:`delete`,key:e.key}:{type:`set`,key:e.key,value:e.metadata});let i={txId:s(),cacheGenerationClaimId:t.cacheGenerationClaimId,mutations:t.mutations.map(e=>({type:e.type,key:e.key,value:e.value,...`metadataChanged`in e?{metadata:e.metadata,metadataChanged:e.metadataChanged}:{}})),rowMetadataMutations:r},a=await this.applyDurablyAtNextStreamPosition(e,n,i);if(a===null)return{type:`rpc:applyLocalMutations:res`,rpcId:t.rpcId,ok:!1,code:`NOT_LEADER`,error:`not the leader for ${e}`};let o={type:`rpc:applyLocalMutations:res`,rpcId:t.rpcId,ok:!0,term:a.term,seq:a.seq,latestRowVersion:a.rowVersion,acceptedMutationIds:t.mutations.map(e=>e.mutationId)};if(this.isDisposed()||this.collections.get(e)!==n)return o;this.appliedEnvelopes.set(Kn(e,t.envelopeId),{appliedAt:Date.now(),requestType:t.type,response:o}),this.pruneAppliedEnvelopes();let c=t.mutations.filter(e=>e.type!==`delete`).map(e=>({key:e.key,value:e.value})),l=t.mutations.filter(e=>e.type===`delete`).map(e=>e.key),u={v:1,dbName:this.dbName,collectionId:e,senderId:this.nodeId,ts:Date.now(),payload:{type:`tx:committed`,term:a.term,seq:a.seq,txId:a.txId,latestRowVersion:a.rowVersion,requiresFullReload:!1,changedRows:c,deletedKeys:l,rowMetadataMutations:r}};this.channel.postMessage(u);for(let e of n.subscribers)e(u);return o}async handleApplyCommittedTx(e,t,n){let r=Kn(e,t.envelopeId);return this.runDeduplicatedEnvelope({envelopeKey:r,rpcId:t.rpcId,selectApplied:e=>e.requestType===`rpc:applyCommittedTx:req`?e.response:void 0,selectInFlight:e=>e.requestType===`rpc:applyCommittedTx:req`?e.response:void 0,conflict:e=>({type:`rpc:applyCommittedTx:res`,rpcId:t.rpcId,ok:!1,code:`CONFLICT`,error:`envelope ${t.envelopeId} ${e}`}),apply:()=>this.applyCommittedTxOnce(e,t,n),createPending:e=>({requestType:t.type,response:e})})}async runDeduplicatedEnvelope(e){let t=this.appliedEnvelopes.get(e.envelopeKey);if(t){let n=e.selectApplied(t);return n?{...n,rpcId:e.rpcId}:e.conflict(`already applied`)}let n=this.inFlightEnvelopes.get(e.envelopeKey);if(n){let t=e.selectInFlight(n);return t?{...await t,rpcId:e.rpcId}:e.conflict(`is already in flight`)}let r=e.apply(),i=e.createPending(r);this.inFlightEnvelopes.set(e.envelopeKey,i);try{return await r}finally{this.inFlightEnvelopes.get(e.envelopeKey)===i&&this.inFlightEnvelopes.delete(e.envelopeKey)}}async applyCommittedTxOnce(e,t,n){let r=this.collections.get(e);if(!r||!r.isLeader)return{type:`rpc:applyCommittedTx:res`,rpcId:t.rpcId,ok:!1,code:`NOT_LEADER`,error:`not the leader for ${e}`};let i=await this.applyDurablyAtNextStreamPosition(e,r,t.tx,n);if(i===null)return{type:`rpc:applyCommittedTx:res`,rpcId:t.rpcId,ok:!1,code:`NOT_LEADER`,error:`not the leader for ${e}`};let a={type:`rpc:applyCommittedTx:res`,rpcId:t.rpcId,ok:!0,term:i.term,seq:i.seq,latestRowVersion:i.rowVersion};return this.isDisposed()||this.collections.get(e)!==r?a:(this.appliedEnvelopes.set(Kn(e,t.envelopeId),{appliedAt:Date.now(),requestType:t.type,response:a}),this.pruneAppliedEnvelopes(),this.publishCommittedTx(e,r,i),a)}publishCommittedTx(e,t,n,r=!1){let i={type:`tx:committed`,term:n.term,seq:n.seq,txId:n.txId,latestRowVersion:n.rowVersion},a=n.truncate||r?{...i,requiresFullReload:!0,...r?{reconciliationReload:!0}:{}}:{...i,requiresFullReload:!1,changedRows:n.mutations.filter(e=>e.type!==`delete`).map(e=>({key:e.key,value:e.value})),deletedKeys:n.mutations.filter(e=>e.type===`delete`).map(e=>e.key),rowMetadataMutations:n.rowMetadataMutations,collectionMetadataMutations:n.collectionMetadataMutations},o={v:1,dbName:this.dbName,collectionId:e,senderId:this.nodeId,ts:Date.now(),payload:a};this.channel.postMessage(o);for(let e of t.subscribers)e(o)}async handleReconcileCommittedTx(e,t,n){let r=this.collections.get(e),i=()=>({type:`rpc:reconcileCommittedTx:res`,rpcId:t.rpcId,ok:!1,code:`NOT_LEADER`,error:`not the leader for ${e}`});if(!r?.isLeader)return i();if(!Et(t.anchor)||!Wn(t.tx))return{type:`rpc:reconcileCommittedTx:res`,rpcId:t.rpcId,ok:!1,code:`UNDETERMINED`,error:`the source transaction has no valid durable proof`};let a=r.latestTerm,o=await this.withScheduledWriterLock(e,async n=>{let i=this.nextPersistedTxIfLeader(e,r,a,t.tx);if(i===null)return null;if(!n.reconcileCommittedTx)return{kind:`unknown`};try{let a=await n.reconcileCommittedTx(i.cacheGenerationClaimId?W(e,i.cacheGenerationClaimId):U(e),i,t.anchor);return a.kind!==`unknown`&&(r.latestRowVersion=Math.max(r.latestRowVersion,a.latestRowVersion),a.kind===`applied-now`&&(r.latestSeq=a.committed.seq)),a}catch(t){throw re(e,t)}},n);if(o===null)return i();if(o.kind===`unknown`)return{type:`rpc:reconcileCommittedTx:res`,rpcId:t.rpcId,ok:!1,code:`UNDETERMINED`,error:`the durable outcome cannot be certified`};let s={term:r.latestTerm,seq:r.latestSeq,rowVersion:r.latestRowVersion},c={type:`rpc:reconcileCommittedTx:res`,rpcId:t.rpcId,ok:!0,alreadyApplied:o.kind===`already-applied`,committed:o.committed};return!this.isDisposed()&&this.collections.get(e)===r&&this.publishCommittedTx(e,r,o.kind===`already-applied`?{...t.tx,...s}:{...t.tx,...o.committed},o.kind===`already-applied`),c}nextPersistedTxIfLeader(e,t,n,r){return this.isDisposed()||this.collections.get(e)!==t||!t.isLeader||t.leaderId!==this.nodeId||t.latestTerm!==n?null:{...r,term:t.latestTerm,seq:t.latestSeq+1,rowVersion:t.latestRowVersion+1}}async applyDurablyAtNextStreamPosition(e,t,n,r){let i=t.latestTerm;return this.withScheduledWriterLock(e,async r=>{let a=this.nextPersistedTxIfLeader(e,t,i,n);if(a===null)return null;try{await r.applyCommittedTx(a.cacheGenerationClaimId?W(e,a.cacheGenerationClaimId):U(e),a)}catch(t){throw re(e,t)}return t.latestSeq=a.seq,t.latestRowVersion=a.rowVersion,a},r)}async handlePullSince(e,t,n){let r=this.collections.get(e),i=n??this.requireAdapter(e);if(!i.pullSince)return{type:`rpc:pullSince:res`,rpcId:t.rpcId,ok:!0,latestTerm:r?.latestTerm??0,latestSeq:r?.latestSeq??0,latestRowVersion:r?.latestRowVersion??0,requiresFullReload:!0};let a=await i.pullSince(t.cacheGenerationClaimId?W(e,t.cacheGenerationClaimId):U(e),t.fromRowVersion,{cacheGenerationClaimId:t.cacheGenerationClaimId});return a.requiresFullReload?{type:`rpc:pullSince:res`,rpcId:t.rpcId,ok:!0,latestTerm:r?.latestTerm??0,latestSeq:r?.latestSeq??0,latestRowVersion:a.latestRowVersion,requiresFullReload:!0}:{type:`rpc:pullSince:res`,rpcId:t.rpcId,ok:!0,latestTerm:r?.latestTerm??0,latestSeq:r?.latestSeq??0,latestRowVersion:a.latestRowVersion,requiresFullReload:!1,changedKeys:a.changedKeys,deletedKeys:a.deletedKeys}}withScheduledWriterLock(e,t,n){if(n)return this.withWriterLock(()=>t(n));let r=this.requireAdapter(e);return r.runInRegularScope?r.runInRegularScope(e=>this.withWriterLock(()=>t(e))):this.withWriterLock(()=>t(r))}async withWriterLock(e){let t=`tsdb:writer:${this.dbName}`;for(let n=0;n<=zn;n++){let r={entered:!1};try{return await navigator.locks.request(t,async()=>(r.entered=!0,e()))}catch(e){if(r.entered||e instanceof DOMException&&e.name===`AbortError`)throw e;if(n<zn){await Gn(Rn*Math.min(n+1,5));continue}throw e}}throw Error(`writer lock acquisition failed`)}pruneAppliedEnvelopes(){this.appliedEnvelopePruneTimer!==null&&(clearTimeout(this.appliedEnvelopePruneTimer),this.appliedEnvelopePruneTimer=null);let e=Date.now()-Ln;for(let[t,n]of this.appliedEnvelopes)n.appliedAt<=e&&this.appliedEnvelopes.delete(t);if(this.disposed||this.appliedEnvelopes.size===0)return;let t=1/0;for(let e of this.appliedEnvelopes.values())t=Math.min(t,e.appliedAt);let n=Math.max(0,t+Ln-Date.now());this.appliedEnvelopePruneTimer=setTimeout(()=>{this.appliedEnvelopePruneTimer=null,this.pruneAppliedEnvelopes()},n)}setReleasedRemoteSubsetAcquisition(e,t){this.inboundRemoteSubsetAcquisitions.set(e,t),this.releasedRemoteSubsetAcquisitionTimes.set(e,Date.now())}pruneReleasedRemoteSubsetAcquisitions(){let e=Date.now()-Ln;for(let[t,n]of this.releasedRemoteSubsetAcquisitionTimes)n<e&&(this.releasedRemoteSubsetAcquisitionTimes.delete(t),this.inboundRemoteSubsetAcquisitions.delete(t))}};function Hn(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.v===1&&typeof t.dbName==`string`&&typeof t.collectionId==`string`&&typeof t.senderId==`string`&&typeof t.ts==`number`}function Un(e){if(!e||typeof e!=`object`)return!1;switch(e.type){case`rpc:ensureRemoteSubset:req`:case`rpc:releaseRemoteSubset:req`:case`rpc:ensurePersistedIndex:req`:case`rpc:applyLocalMutations:req`:case`rpc:applyCommittedTx:req`:case`rpc:reconcileCommittedTx:req`:case`rpc:pullSince:req`:return!0;default:return!1}}function Wn(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.txId==`string`&&Array.isArray(t.mutations)}function Gn(e){return new Promise(t=>setTimeout(t,e))}function Kn(e,t){return JSON.stringify([e,t])}function $(e,t){return JSON.stringify([e,t])}function qn(e,t,n){return JSON.stringify([e,t,n])}function Jn(e,t){let n=t instanceof Error?t.message:String(t);switch(e.type){case`rpc:ensureRemoteSubset:req`:return{type:`rpc:ensureRemoteSubset:res`,rpcId:e.rpcId,ok:!1,error:n,...t instanceof T?{retryable:!0}:{}};case`rpc:releaseRemoteSubset:req`:return{type:`rpc:releaseRemoteSubset:res`,rpcId:e.rpcId,ok:!1,error:n};case`rpc:ensurePersistedIndex:req`:return{type:`rpc:ensurePersistedIndex:res`,rpcId:e.rpcId,ok:!1,error:n};case`rpc:applyLocalMutations:req`:return t instanceof S?{type:`rpc:applyLocalMutations:res`,rpcId:e.rpcId,ok:!1,code:`PERSISTENCE_ERROR`,error:n,...Xn(t)}:{type:`rpc:applyLocalMutations:res`,rpcId:e.rpcId,ok:!1,code:`CONFLICT`,error:n};case`rpc:applyCommittedTx:req`:return t instanceof S?{type:`rpc:applyCommittedTx:res`,rpcId:e.rpcId,ok:!1,code:`PERSISTENCE_ERROR`,error:n,...Xn(t)}:{type:`rpc:applyCommittedTx:res`,rpcId:e.rpcId,ok:!1,code:`CONFLICT`,error:n};case`rpc:reconcileCommittedTx:req`:return{type:`rpc:reconcileCommittedTx:res`,rpcId:e.rpcId,ok:!1,code:t instanceof S?`PERSISTENCE_ERROR`:`UNDETERMINED`,error:n,...t instanceof S?Xn(t):{}};case`rpc:pullSince:req`:return{type:`rpc:pullSince:res`,rpcId:e.rpcId,ok:!1,error:n}}}function Yn(e){return e.type===`rpc:applyLocalMutations:req`||e.type===`rpc:applyCommittedTx:req`}function Xn(e){let t=typeof e.code==`string`||typeof e.code==`number`?e.code:void 0,n=typeof e.path==`string`||Array.isArray(e.path)&&e.path.every(e=>typeof e==`string`||typeof e==`number`)?e.path:void 0;return{...t===void 0?{}:{sourceCode:t},...n===void 0?{}:{path:n}}}var Zn=class extends Vn{constructor(e){super({...e,coordinatorName:`BrowserCollectionCoordinator`})}},Qn,$n=new WeakMap;function er(e){let t=$n.get(e);if(t)return t;let n={queue:Promise.resolve(),nextSavepointId:1};return $n.set(e,n),n}function tr(e){if(!(e.length>0))throw new y(`SQLiteDriver.transaction callback must accept the transaction driver argument`)}function nr(e){if(typeof e.execute!=`function`)throw new y(`Browser wa-sqlite database handle must provide execute(sql, params?)`)}Qn=We;var rr=class{constructor(e){this[Qn]={},this.closed=!1,nr(e.database),this.database=e.database,this.executionState=er(this.database)}exec(e){return this.enqueue(async()=>{await this.database.execute(e)})}query(e,t=[]){return this.enqueue(()=>this.database.execute(e,t))}run(e,t=[]){return this.enqueue(async()=>{await this.database.execute(e,t)})}transaction(e){try{tr(e)}catch(e){return Promise.reject(e)}return this.enqueue(async()=>{await this.database.execute(`BEGIN IMMEDIATE`);try{let t=await e(this.createTransactionDriver());return await this.database.execute(`COMMIT`),t}catch(e){try{await this.database.execute(`ROLLBACK`)}catch{}throw e}})}transactionWithDriver(e){return this.transaction(e)}async close(){this.closed||(this.closed=!0,typeof this.database.close==`function`&&await Promise.resolve(this.database.close()))}getDatabase(){return this.database}createTransactionDriver(){return{exec:e=>this.database.execute(e).then(()=>void 0),query:(e,t=[])=>this.database.execute(e,t),run:(e,t=[])=>this.database.execute(e,t).then(()=>void 0),transaction:e=>this.runNestedTransaction(e),transactionWithDriver:e=>this.runNestedTransaction(e)}}async runNestedTransaction(e){tr(e);let t=`tsdb_sp_${this.executionState.nextSavepointId}`;this.executionState.nextSavepointId++,await this.database.execute(`SAVEPOINT ${t}`);try{let n=await e(this.createTransactionDriver());return await this.database.execute(`RELEASE SAVEPOINT ${t}`),n}catch(e){throw await this.database.execute(`ROLLBACK TO SAVEPOINT ${t}`),await this.database.execute(`RELEASE SAVEPOINT ${t}`),e}}enqueue(e){let t=this.executionState.queue.then(e,e);return Object.defineProperty(t,We,{value:this[We]}),this.executionState.queue=t.then(()=>void 0,()=>void 0),t}};function ir(e){return e===`throw`?`sync-absent-error`:e}function ar(e,t){return e?ir(e):t===`sync-present`?`sync-present-reset`:`sync-absent-error`}function or(e,t){return`${e}|${t===void 0?`schema:default`:`schema:${t}`}`}function sr(e){return new rr({database:e.database})}function cr(e){return{appliedTxPruneMaxRows:e.appliedTxPruneMaxRows??1e3,appliedTxPruneMaxAgeSeconds:e.appliedTxPruneMaxAgeSeconds??86400,pullSinceReloadThreshold:e.pullSinceReloadThreshold,cacheGenerationClaimTtlMs:e.cacheGenerationClaimTtlMs,now:e.now}}function lr(e){let{coordinator:t,schemaMismatchPolicy:n}=e,r=sr(e),i=cr(e),a=t??new tt,o=new Map,s=(e,t)=>{let a=ar(n,e),s=or(a,t),c=o.get(s);if(c)return c;let l=An({...i,driver:r,schemaMismatchPolicy:a,...t===void 0?{}:{schemaVersion:t}});return o.set(s,l),l},c=(e,t,n)=>{let r=s(t,n);return a instanceof Zn&&(e===void 0?a.setAdapter(r):a.setAdapterForCollection(e,r)),{adapter:r,coordinator:a}},l=c(void 0,`sync-absent`,void 0);return a instanceof Zn&&a.setAdapter(l.adapter),{...l,resolvePersistenceForCollection:({collectionId:e,mode:t,schemaVersion:n})=>c(e,t,n),resolvePersistenceForMode:e=>c(void 0,e,void 0)}}function ur(e){return new Worker(``+new URL(`/assets/opfs-worker-accoEoax-B2IN8tCs.js`,``+import.meta.url).href,{name:e?.name})}var dr=`opfs`,fr=3e4,pr=2147483647,mr=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`OPFSWorkerRequestError`}};function hr(e){let t=e,n=t.navigator?.storage?.getDirectory,r=t.Worker;return typeof n==`function`&&typeof r==`function`}function gr(e,t){return e===`PERSISTENCE_UNAVAILABLE`?new D(t):e===`INVALID_CONFIG`?new y(t):new mr(e,t)}function _r(){let e=0,t=`opfs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return()=>(e++,`${t}-${e}`)}function vr(){if(typeof globalThis.Worker!=`function`)throw new D(`Web Worker support is required for browser OPFS persistence`);return new ur}function yr(e){let t=e.reason;return t instanceof Error?t:new DOMException(`Opening browser OPFS database was aborted`,`AbortError`)}async function br(e){let t=e.databaseName.trim();if(t.length===0)throw new y(`Browser wa-sqlite databaseName cannot be empty`);let n=e.timeoutMs??fr;if(!Number.isSafeInteger(n)||n<0||n>pr)throw new y(`Browser wa-sqlite timeoutMs must be an integer between 0 and ${pr}`);let r=e.signal;if(r?.aborted)throw yr(r);if(!hr(globalThis))throw new D(`Browser OPFS prerequisites are not available in this runtime`);let i=e.vfsName??dr,a=vr(),o=_r(),s=new Map,c=!1,l=()=>{c||(c=!0,globalThis.removeEventListener(`pagehide`,m),a.removeEventListener(`message`,d),a.removeEventListener(`error`,f),a.removeEventListener(`messageerror`,p),a.terminate())},u=e=>{for(let t of s.values())t.reject(e);s.clear()},d=e=>{let t=e.data,n=s.get(t.requestId);if(n){if(s.delete(t.requestId),t.ok){n.resolve(t.rows??[]);return}n.reject(gr(t.code,t.error))}},f=()=>{u(new D(`OPFS worker terminated unexpectedly`)),l()},p=()=>{u(new D(`OPFS worker message serialization failed`)),l()},m=()=>{u(new DOMException(`The page is closing its SQLite connection`,`AbortError`)),l()};a.addEventListener(`message`,d),a.addEventListener(`error`,f),a.addEventListener(`messageerror`,p),globalThis.addEventListener(`pagehide`,m);let ee=e=>{if(c)return Promise.reject(new y(`Browser OPFS worker connection is closed`));let t=o();return new Promise((n,r)=>{s.set(t,{resolve:e=>{n(e)},reject:r});try{let n={...e,requestId:t};a.postMessage(n)}catch(e){s.delete(t),r(new D(`Failed to send message to OPFS worker: ${e.message}`))}})},h,g=()=>{r&&(u(yr(r)),l())},_=()=>{u(new DOMException(`Opening browser OPFS database timed out after ${n} ms`,`TimeoutError`)),l()};try{let e=ee({type:`init`,databaseName:t,vfsName:i});r?.addEventListener(`abort`,g,{once:!0}),r?.aborted&&g(),n>0&&(h=setTimeout(_,n)),await e}catch(e){throw l(),e}finally{h!==void 0&&clearTimeout(h),r?.removeEventListener(`abort`,g)}return{execute:(e,t=[])=>ee({type:`execute`,sql:e,params:t}),close:async()=>{if(c)return;let e;try{await ee({type:`close`})}catch(t){e=t}finally{l()}if(e)throw e}}}export{Zn as BrowserCollectionCoordinator,Bt as DEFAULT_APPLIED_TX_PRUNE_MAX_AGE_SECONDS,zt as DEFAULT_APPLIED_TX_PRUNE_MAX_ROWS,w as DuplicateRemoteSubsetOwnerError,C as IndeterminateCommitError,S as PersistedCollectionDurabilityError,P as RemoteSubsetWireValueError,lr as createBrowserWASQLitePersistence,br as openBrowserWASQLiteOPFSDatabase,bt as persistedCollectionOptions};
|