github-stars-organizer 1.2.1 → 1.3.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/dist/app/assets/{backups-r4Hq-y_s.js → backups-DrK5WGqD.js} +1 -1
- package/dist/app/assets/badge-Drt9JvOu.js +1 -0
- package/dist/app/assets/{button-C0MQwO-R.js → button-r9cVFa0_.js} +3 -3
- package/dist/app/assets/coerce-Cxjr6MIU.js +1 -0
- package/dist/app/assets/{esm-Cyyp48ez.js → esm-CVXsiVX8.js} +1 -1
- package/dist/app/assets/explore-Da5fm3tF.js +33 -0
- package/dist/app/assets/{history-OZ9l4TiG.js → history-CN5yGwhZ.js} +1 -1
- package/dist/app/assets/index-B-eCk0oM.js +10 -0
- package/dist/app/assets/index-DIdY6bcj.css +2 -0
- package/dist/app/assets/list._listId-CNuYrPaQ.js +2 -0
- package/dist/app/assets/list._listId-DBB3l--n.js +1 -0
- package/dist/app/assets/{local-backups-BGSAd5Gu.js → local-backups-DLhiWDk4.js} +1 -1
- package/dist/app/assets/{local-sync-Dd3hEb9I.js → local-sync-DiQe8mhd.js} +1 -1
- package/dist/app/assets/registry-BKf8LDk2.js +4 -0
- package/dist/app/assets/routes-C0Cvc6Pi.js +2 -0
- package/dist/app/assets/routes-CY3o7jPt.js +3 -0
- package/dist/app/assets/{schemas-B0gCwksU.js → schemas-DVvZEnxp.js} +1 -1
- package/dist/app/assets/star-BPue5Y4t.js +7 -0
- package/dist/app/assets/{triangle-alert-Cgw2r-Xm.js → triangle-alert-BL8M65pd.js} +1 -1
- package/dist/app/index.html +10 -10
- package/dist/cli.js +475 -1
- package/package.json +1 -1
- package/dist/app/assets/badge-DWmLT6OI.js +0 -1
- package/dist/app/assets/coerce-D595RIhb.js +0 -1
- package/dist/app/assets/explore-Cizp4zKW.js +0 -33
- package/dist/app/assets/index-CTD9BpPN.js +0 -10
- package/dist/app/assets/index-DR-cW8P1.css +0 -2
- package/dist/app/assets/list._listId-C5TBL1sd.js +0 -2
- package/dist/app/assets/list._listId-Cq8rSqKM.js +0 -1
- package/dist/app/assets/registry-DZ4hp3Pl.js +0 -4
- package/dist/app/assets/routes-CqMycHWV.js +0 -2
- package/dist/app/assets/routes-DcRfe2TL.js +0 -3
- package/dist/app/assets/star-BoN7NVgv.js +0 -7
- /package/dist/app/assets/{sync-persistence-f8LlQoHO.js → sync-persistence-BJbWXISF.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
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}
|
|
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-BJbWXISF.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
2
|
WHEN 'bigint' THEN CAST(json_extract(value, ${i}) AS NUMERIC)
|
|
3
3
|
WHEN 'date' THEN json_extract(value, ${i})
|
|
4
4
|
WHEN 'string' THEN json_extract(value, ${i})
|