=2){const o=r.split(`.`),u=xl(t,o);if(u&&u.supports(`gt`)&&u.supports(`lt`)){let d,p,g=!0,y=!0;for(const{operation:v,value:w}of l)switch(v){case`gt`:(d===void 0||w>d)&&(d=w,g=!1);break;case`gte`:(d===void 0||w>d)&&(d=w,g=!0);break;case`lt`:(p===void 0||w0){const l=r.map(u=>u.matchingKeys);return{canOptimize:!0,matchingKeys:$x(l)}}return{canOptimize:!1,matchingKeys:new Set}}function Jx(n,t){if(n.type!==`func`||n.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const i=[];for(const r of n.args){const l=np(r,t);l.canOptimize&&i.push(l)}if(i.length>0){const r=i.map(o=>o.matchingKeys);return{canOptimize:!0,matchingKeys:Gx(r)}}return{canOptimize:!1,matchingKeys:new Set}}function Zx(n,t){if(n.type!==`func`||n.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const i=n.args[0],r=n.args[1];if(i.type===`ref`&&r.type===`val`&&Array.isArray(r.value)){const l=i.path,o=r.value,u=xl(t,l);if(u){if(u.supports(`in`))return{canOptimize:!0,matchingKeys:u.lookup(`in`,o)};if(u.supports(`eq`)){const d=new Set;for(const p of o){const g=u.lookup(`eq`,p);for(const y of g)d.add(y)}return{canOptimize:!0,matchingKeys:d}}}}return{canOptimize:!1,matchingKeys:new Set}}function Iv(n){return n.config.autoIndex===`eager`}function $c(n,t,i,r,l){if(Lv(t)||!Iv(i))return;const o=r??{...jv,...i.compareOptions};if(!Array.from(i.indexes.values()).find(d=>d.matchesField(t)&&d.matchesCompareOptions(o)))try{i.createIndex(d=>{let p=d;for(const g of t)p=p[g];return p},{name:`auto:${t.join(`.`)}`,options:l?{compareFn:l,compareOptions:o}:{}})}catch(d){console.warn(`${i.id?`[${i.id}] `:``}Failed to create auto-index for field path "${t.join(`.`)}":`,d)}}function Wx(n,t){if(!Iv(t))return;const i=Px(n);for(const{fieldName:r,fieldPath:l}of i)$c(r,l,t)}function Px(n){const t=[];function i(r){if(r.type!==`func`)return;const l=r;if(l.name===`and`){for(const g of l.args)i(g);return}if(![`eq`,`gt`,`gte`,`lt`,`lte`,`in`].includes(l.name)||l.args.length<1||l.args[0].type!==`ref`)return;const d=l.args[0].path;if(d.length===0)return;const p=d.join(`_`);t.push({fieldName:p,fieldPath:d})}return i(n),t}class t_ extends Map{constructor(t,i){super(i),this.defaultValue=t}get(t){return this.has(t)?super.get(t):this.defaultValue()}update(t,i){const r=this.get(t),l=i(r);return this.set(t,l),l}}const zh=3e4;function Nh(n,t){if(t.length<=zh)n.push(...t);else for(let i=0;i0)l=o;else return o}return r}class n_{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(t){if(typeof t!=`object`||t===null){const i=String(t);let r=0;for(let l=0;lt?1:0:typeof n==`string`?-1:1}function cl(n){return JSON.stringify(n,(t,i)=>typeof i==`bigint`?i.toString():i instanceof Date?i.toISOString():i)}const i_=Se(),r_=Se(),a_=Se(),l_=Se(),o_=Se();function Se(){return Math.random()*(2**31-1)>>>0}const Hv=new ArrayBuffer(8),c_=new DataView(Hv),$s=new Uint8Array(Hv);class _l{constructor(){this.hash=i_,this.length=0,this.carry=0,this.carryBytes=0}_mix(t){t=Math.imul(t,3432918353),t=t<<15|t>>>17,t=Math.imul(t,461845907),this.hash^=t,this.hash=this.hash<<13|this.hash>>>19,this.hash=Math.imul(this.hash,5)+3864292196}writeByte(t){this.carry|=(t&255)<<8*this.carryBytes,this.carryBytes++,this.length++,this.carryBytes===4&&(this._mix(this.carry>>>0),this.carry=0,this.carryBytes=0)}update(t){switch(typeof t){case`symbol`:{this.update(o_);const i=t.description;if(!i)return;for(let r=0;r>>8&255)}return}case`string`:this.update(r_);for(let i=0;i>>8&255)}return;case`number`:c_.setFloat64(0,t,!0),this.writeByte($s[0]),this.writeByte($s[1]),this.writeByte($s[2]),this.writeByte($s[3]),this.writeByte($s[4]),this.writeByte($s[5]),this.writeByte($s[6]),this.writeByte($s[7]);return;case`bigint`:{let i=t;for(i<0n?(i=-i,this.update(l_)):this.update(a_);i>0n;)this.writeByte(Number(i&0xffn)),i>>=8n;t===0n&&this.writeByte(0);return}default:throw new TypeError(`Unsupported input type: ${typeof t}`)}}digest(){if(this.carryBytes>0){let t=this.carry>>>0;t=Math.imul(t,3432918353),t=t<<15|t>>>17,t=Math.imul(t,461845907),this.hash^=t}return this.hash^=this.length,this.hash^=this.hash>>>16,this.hash=Math.imul(this.hash,2246822507),this.hash^=this.hash>>>13,this.hash=Math.imul(this.hash,3266489909),this.hash^=this.hash>>>16,this.hash>>>0}}const u_=Se(),f_=Se(),h_=Se(),d_=Se(),p_=Se(),g_=Se(),y_=Se(),m_=Se(),S_=Se(),v_=Se(),b_=Se(),w_=Se(),E_=Se(),C_=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function x_(n){const t=n[Symbol.toStringTag];return typeof t==`string`&&C_.has(t)}const __=128,ul=new WeakMap;function ke(n){const t=new _l;return qv(t,n),t.digest()}function T_(n){const t=ul.get(n);if(t!==void 0)return t;let i;if(n instanceof Date)i=A_(n);else if(typeof Buffer<`u`&&n instanceof Buffer||n instanceof Uint8Array)if(n.byteLength<=__)i=O_(n);else return yd(n);else{if(n instanceof File)return yd(n);if(x_(n))i=R_(n);else{let r=n,l=m_;n instanceof Array&&(l=S_),n instanceof Map&&(l=v_,r=[...n.entries()]),n instanceof Set&&(l=b_,r=[...n.entries()]),i=D_(r,l)}}return ul.set(n,i),i}function A_(n){const t=new _l;return t.update(y_),t.update(n.getTime()),t.digest()}function O_(n){const t=new _l;t.update(w_),t.update(n.byteLength);for(let i=0;i[t(i),r]))}filter(t){return new ee(this.#t.filter(([i,r])=>t(i)))}negate(){return new ee(this.#t.map(([t,i])=>[t,-i]))}concat(t){const i=[];return Nh(i,this.#t),Nh(i,t.getInner()),new ee(i)}consolidate(){if(this.#t.length>0){const t=this.#t[0]?.[0];if(Array.isArray(t)&&t.length===2)return this.#e()}return this.#n()}#e(){const t=new Map,i=new Map,r=o=>{if(o.length!==2)throw new Error(`Expected tuple of length 2`);const[u,d]=o;return`${jh.getStringId(u)}|${jh.getStringId(d)}`};for(const[o,u]of this.#t){if(!Array.isArray(o)||o.length!==2)return this.#n();const[d,p]=o;if(typeof d!=`string`&&typeof d!=`number`)return this.#n();let g;Array.isArray(p)&&p.length===2?g=r(p):g=jh.getStringId(p);const y=d+`|`+g;t.set(y,(t.get(y)||0)+u),i.has(y)||i.set(y,o)}const l=[];for(const[o,u]of t)u!==0&&l.push([i.get(o),u]);return new ee(l)}#n(){const t=new t_(()=>0),i=new Map;let r=!1,l=!1,o=!1;for(const[p,g]of this.#t)if(typeof p==`string`)r=!0;else if(typeof p==`number`)l=!0;else{o=!0;break}const u=o||r&&l;for(const[p,g]of this.#t){const y=u?ke(p):p;u&&!i.has(y)&&i.set(y,p),t.update(y,m=>m+g)}const d=[];for(const[p,g]of t.entries())if(g!==0){const y=u?i.get(p):p;d.push([y,g])}return new ee(d)}extend(t){const i=t instanceof ee?t.getInner():t;Nh(this.#t,i)}add(t,i){i!==0&&this.#t.push([t,i])}getInner(){return this.#t}}class U_{#t;constructor(t){this.#t=t}drain(){const t=[...this.#t].reverse();return this.#t.length=0,t}isEmpty(){return this.#t.length===0}}class Rn{#t=[];sendData(t){t instanceof ee||(t=new ee(t));for(const i of this.#t)i.unshift(t)}newReader(){const t=[];return this.#t.push(t),new U_(t)}}class Kv{constructor(t,i,r){this.id=t,this.inputs=i,this.output=r}hasPendingWork(){return this.inputs.some(t=>!t.isEmpty())}}class Di extends Kv{constructor(t,i,r){super(t,[i],r),this.id=t}inputMessages(){return this.inputs[0].drain()}}class z_ extends Kv{constructor(t,i,r,l){super(t,[i,r],l),this.id=t}inputAMessages(){return this.inputs[0].drain()}inputBMessages(){return this.inputs[1].drain()}}class sp extends Di{run(){for(const t of this.inputMessages())this.output.sendData(this.inner(t))}}class N_{#t=[];#e=0;#n=!1;constructor(){}#s(){if(this.#n)throw new Error(`Graph already finalized`)}getNextOperatorId(){return this.#s(),this.#e++}newInput(){this.#s();const t=new Rn;return new j_(this,t)}addOperator(t){this.#s(),this.#t.push(t)}finalize(){this.#s(),this.#n=!0}step(){if(!this.#n)throw new Error(`Graph not finalized`);for(const t of this.#t)t.run()}pendingWork(){return this.#t.some(t=>t.hasPendingWork())}run(){for(;this.pendingWork();)this.step()}}class Dn{#t;#e;constructor(t,i){this.#t=t,this.#e=i}connectReader(){return this.#e.newReader()}get writer(){return this.#e}get graph(){return this.#t}pipe(...t){return t.reduce((i,r)=>r(i),this)}}class j_ extends Dn{sendData(t){this.writer.sendData(t)}}class B_ extends Di{run(){const t=this.inputMessages();if(t.length===0)return;const i=new ee;for(const l of t)i.extend(l);const r=i.consolidate();r.getInner().length>0&&this.output.sendData(r)}}function Vv(){return n=>{const t=new Dn(n.graph,new Rn),i=new B_(n.graph.getNextOperatorId(),n.connectReader(),t.writer);return n.graph.addOperator(i),t}}const Qa=Symbol(`NO_PREFIX`);class lS extends Map{addValue(t,i){if(i===0)return this.size===0;const r=tl(t),l=this.get(r);if(ac(l)){const[o,u]=l;if(tl(o)!==r)throw new Error(`Mismatching prefixes, this should never happen`);if(o===t||ke(o)===ke(t)){const p=u+i;p===0?this.delete(r):this.set(r,[t,p])}else{const p=new Xa;p.set(ke(o),l),p.set(ke(t),[t,i]),this.set(r,p)}}else l===void 0?this.set(r,[t,i]):l.addValue(t,i)&&this.delete(r);return this.size===0}}class Xa extends Map{addValue(t,i){if(i===0)return this.size===0;const r=ke(t),l=this.get(r);if(l){const[,o]=l,u=o+i;u===0?this.delete(r):this.set(r,[t,u])}else this.set(r,[t,i]);return this.size===0}}class Fs{#t;#e=new Map;constructor(){this.#t=new Map}static fromMultiSets(t){const i=new Fs;for(const r of t)for(const[l,o]of r.getInner()){const[u,d]=l;i.addValue(u,[d,o])}return i}toString(t=!1){return`Index(${JSON.stringify([...this.entries()],void 0,t?2:void 0)})`}get size(){return this.#t.size}has(t){return this.#t.has(t)}hasPresence(t){return(this.#e.get(t)||0)!==0}getConsolidatedMultiplicity(t){return this.#e.get(t)||0}getPresenceKeys(){return this.#e.keys()}get(t){return[...this.getIterator(t)]}*getIterator(t){const i=this.#t.get(t);if(ac(i))yield i;else{if(i===void 0)return;if(i instanceof Xa)for(const r of i.values())yield r;else for(const r of i.values())if(ac(r))yield r;else for(const l of r.values())yield l}}*entries(){for(const t of this.#t.keys())for(const i of this.getIterator(t))yield[t,i]}*entriesIterators(){for(const t of this.#t.keys())yield[t,this.getIterator(t)]}addValue(t,i){const[r,l]=i;if(l===0)return;const o=(this.#e.get(t)||0)+l;o===0?this.#e.delete(t):this.#e.set(t,o);const u=this.#t.get(t);if(u===void 0){this.#t.set(t,i);return}if(ac(u)){this.#n(t,u,r,l);return}if(u instanceof Xa){const d=tl(r);if(d!==Qa){const p=new lS;p.set(Qa,u),p.set(d,i),this.#t.set(t,p)}else u.addValue(r,l)&&this.#t.delete(t)}else u.addValue(r,l)&&this.#t.delete(t)}#n(t,i,r,l){const[o,u]=i;if(o===r){const g=u+l;g===0?this.#t.delete(t):this.#t.set(t,[r,g]);return}const d=tl(r),p=tl(o);if(p===d&&(o===r||ke(o)===ke(r))){const g=u+l;g===0?this.#t.delete(t):this.#t.set(t,[r,g]);return}if(p===Qa&&d===Qa){const g=new Xa;g.set(ke(o),i),g.set(ke(r),[r,l]),this.#t.set(t,g)}else{const g=new lS;if(p===d){const y=new Xa;y.set(ke(o),i),y.set(ke(r),[r,l]),g.set(p,y)}else g.set(p,i),g.set(d,[r,l]);this.#t.set(t,g)}}append(t){for(const[i,r]of t.entries())this.addValue(i,r)}join(t){const i=[];if(this.size<=t.size)for(const[r,l]of this.entriesIterators()){if(!t.has(r))continue;const o=t.get(r);for(const[u,d]of l)for(const[p,g]of o)d!==0&&g!==0&&i.push([[r,[u,p]],d*g])}else for(const[r,l]of t.entriesIterators()){if(!this.has(r))continue;const o=this.get(r);for(const[u,d]of l)for(const[p,g]of o)g!==0&&d!==0&&i.push([[r,[p,u]],g*d])}return new ee(i)}}function tl(n){return Array.isArray(n)&&(typeof n[0]==`string`||typeof n[0]==`number`||typeof n[0]==`bigint`)?n[0]:Qa}function ac(n){return Array.isArray(n)}class L_ extends Di{#t=new Fs;#e=new Fs;#n;constructor(t,i,r,l){super(t,i,r),this.#n=l}run(){const t=new Set;for(const r of this.inputMessages())for(const[l,o]of r.getInner()){const[u,d]=l;this.#t.addValue(u,[d,o]),t.add(u)}const i=[];for(const r of t){const l=this.#t.get(r),o=this.#e.get(r),u=this.#n(l),d=new Map,p=new Map;for(const[g,y]of u){const m=d.get(g)??0;d.set(g,m+y)}for(const[g,y]of o){const m=p.get(g)??0;p.set(g,m+y)}for(const[g,y]of p)d.has(g)||(i.push([[r,g],-y]),this.#e.addValue(r,[g,-y]));for(const[g,y]of d)p.has(g)||y!==0&&(i.push([[r,g],y]),this.#e.addValue(r,[g,y]));for(const[g,y]of d){const m=p.get(g);if(m!==void 0){const v=y-m;v!==0&&(i.push([[r,g],v]),this.#e.addValue(r,[g,v]))}}}i.length>0&&this.output.sendData(new ee(i))}}function $v(n){return t=>{const i=new Dn(t.graph,new Rn),r=new L_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class I_ extends Di{#t;#e;constructor(t,i,r,l=o=>o){super(t,i,r),this.#t=l,this.#e=new Map}run(){const t=new Map;for(const r of this.inputMessages())for(const[l,o]of r.getInner()){const u=ke(this.#t(l)),p=(t.get(u)?.[0]??this.#e.get(u)??0)+o;t.set(u,[p,l])}const i=[];for(const[r,[l,o]]of t.entries()){const u=this.#e.get(r)??0;l===0?this.#e.delete(r):this.#e.set(r,l),u<=0&&l>0?i.push([[ke(this.#t(o)),o[1]],1]):u>0&&l<=0&&i.push([[ke(this.#t(o)),o[1]],-1])}i.length>0&&this.output.sendData(new ee(i))}}function H_(n=t=>t){return t=>{const i=new Dn(t.graph,new Rn),r=new I_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class q_ extends sp{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}inner(t){return t.filter(this.#t)}}function ps(n){return t=>{const i=new Dn(t.graph,new Rn),r=new q_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}const K_=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`;function _r(n,t,i){const r=i[0];if(t!=null&&n>=t)throw new Error(n+` >= `+t);if(n.slice(-1)===r||t&&t.slice(-1)===r)throw new Error(`trailing zero`);if(t){let u=0;for(;(n[u]||r)===t[u];)u++;if(u>0)return t.slice(0,u)+_r(n.slice(u),t.slice(u),i)}const l=n?i.indexOf(n[0]):0,o=t!=null?i.indexOf(t[0]):i.length;if(o-l>1){const u=Math.round(.5*(l+o));return i[u]}else return t&&t.length>1?t.slice(0,1):i[l]+_r(n.slice(1),null,i)}function Gv(n){if(n.length!==Yv(n[0]))throw new Error(`invalid integer part of order key: `+n)}function Yv(n){if(n>=`a`&&n<=`z`)return n.charCodeAt(0)-97+2;if(n>=`A`&&n<=`Z`)return 90-n.charCodeAt(0)+2;throw new Error(`invalid order key head: `+n)}function Ja(n){const t=Yv(n[0]);if(t>n.length)throw new Error(`invalid order key: `+n);return n.slice(0,t)}function oS(n,t){if(n===`A`+t[0].repeat(26))throw new Error(`invalid order key: `+n);const i=Ja(n);if(n.slice(i.length).slice(-1)===t[0])throw new Error(`invalid order key: `+n)}function cS(n,t){Gv(n);const[i,...r]=n.split(``);let l=!0;for(let o=r.length-1;l&&o>=0;o--){const u=t.indexOf(r[o])+1;u===t.length?r[o]=t[0]:(r[o]=t[u],l=!1)}if(l){if(i===`Z`)return`a`+t[0];if(i===`z`)return null;const o=String.fromCharCode(i.charCodeAt(0)+1);return o>`a`?r.push(t[0]):r.pop(),o+r.join(``)}else return i+r.join(``)}function V_(n,t){Gv(n);const[i,...r]=n.split(``);let l=!0;for(let o=r.length-1;l&&o>=0;o--){const u=t.indexOf(r[o])-1;u===-1?r[o]=t.slice(-1):(r[o]=t[u],l=!1)}if(l){if(i===`a`)return`Z`+t.slice(-1);if(i===`A`)return null;const o=String.fromCharCode(i.charCodeAt(0)-1);return o<`Z`?r.push(t.slice(-1)):r.pop(),o+r.join(``)}else return i+r.join(``)}function $_(n,t,i=K_){if(n!=null&&oS(n,i),t!=null&&oS(t,i),n!=null&&t!=null&&n>=t)throw new Error(n+` >= `+t);if(n==null){if(t==null)return`a`+i[0];const p=Ja(t),g=t.slice(p.length);if(p===`A`+i[0].repeat(26))return p+_r(``,g,i);if(p{const o=n(i,l);return o!==0?o:gd(t,r)}}class ip{#t=[];#e;#n;#s;constructor(t,i,r){this.#n=t,this.#s=t+i,this.#e=r}get size(){const t=this.#n,i=this.#s-this.#n,r=this.#t.length-t;return Math.max(0,Math.min(i,r))}move({offset:t,limit:i}){const r=this.#n,l=this.#s-this.#n,o=[this.#n,this.#s===1/0?this.#n+this.size:this.#s];this.#n=t??r,this.#s=this.#n+(i??l);const u=[this.#n,this.#s===1/0?Math.max(this.#n+this.size,o[1]):this.#s],{onlyInA:d,onlyInB:p}=s_(o,u),g=[];p.forEach(m=>{const v=this.#t[m];v&&g.push(v)});const y=[];return d.forEach(m=>{const v=this.#t[m];v&&y.push(v)}),{moveIns:g,moveOuts:y,changes:d.length+p.length>0}}insert(t){const i={moveIn:null,moveOut:null},r=this.#a(t),l=r===0?null:hS(this.#t[r-1]),o=r===this.#t.length?null:hS(this.#t[r]),u=$_(l,o),d=uS(t,u);if(this.#t.splice(r,0,d),rthis.#e(fS(i),fS(r)))}}class Qv{#t=new Map;#e;constructor(t){this.#e=t}get size(){return this.#e.size}get isEmpty(){return this.#t.size===0&&this.#e.size===0}processElement(t,i,r){const{oldMultiplicity:l,newMultiplicity:o}=this.#n(t,r);return l<=0&&o>0?this.#e.insert([t,i]):l>0&&o<=0?this.#e.delete([t,i]):{moveIn:null,moveOut:null}}move(t){if(!(this.#e instanceof ip))throw new Error(`Cannot move B+-tree implementation of TopK with fractional index`);return this.#e.move(t)}#n(t,i){if(i===0){const o=this.#t.get(t)??0;return{oldMultiplicity:o,newMultiplicity:o}}const r=this.#t.get(t)??0,l=r+i;return l===0?this.#t.delete(t):this.#t.set(t,l),{oldMultiplicity:r,newMultiplicity:l}}}function bc(n,t){if(n){const[[i,r],l]=n;t.push([[i,[r,l]],1])}}function wc(n,t){if(n){const[[i,r],l]=n;t.push([[i,[r,l]],-1])}}class G_ extends Di{#t=new Map;#e;#n;#s;#a;constructor(t,i,r,l,o){super(t,i,r),this.#e=o.groupKeyFn,this.#a=o.limit??1/0,this.#s=o.offset??0,this.#n=Fv(l),o.setSizeCallback?.(()=>this.#i()),o.setWindowFn?.(this.#p.bind(this))}createTopK(t,i,r){return new ip(t,i,r)}#i(){let t=0;for(const i of this.#t.values())t+=i.size;return t}#c(t){let i=this.#t.get(t);if(!i){const r=this.createTopK(this.#s,this.#a,this.#n);i=new Qv(r),this.#t.set(t,i)}return i}#l(t,i){i.isEmpty&&this.#t.delete(t)}#p({offset:t,limit:i}){t!==void 0&&(this.#s=t),i!==void 0&&(this.#a=i);const r=[];let l=!1;for(const o of this.#t.values()){const u=o.move({offset:this.#s,limit:this.#a});u.moveIns.forEach(d=>bc(d,r)),u.moveOuts.forEach(d=>wc(d,r)),u.changes&&(l=!0)}l&&this.output.sendData(new ee(r))}run(){const t=[];for(const i of this.inputMessages())for(const[r,l]of i.getInner()){const[o,u]=r;this.#d(o,u,l,t)}t.length>0&&this.output.sendData(new ee(t))}#d(t,i,r,l){const o=this.#e(t,i),u=this.#c(o),d=u.processElement(t,i,r);bc(d.moveIn,l),wc(d.moveOut,l),this.#l(o,u)}}function Y_(n,t){return i=>{const r=new Dn(i.graph,new Rn),l=new G_(i.graph.getNextOperatorId(),i.connectReader(),r.writer,n,t);return i.graph.addOperator(l),r}}class F_ extends z_{#t=new Fs;#e=new Fs;#n;constructor(t,i,r,l,o=`inner`){super(t,i,r,l),this.#n=o}run(){const t=Fs.fromMultiSets(this.inputAMessages()),i=Fs.fromMultiSets(this.inputBMessages());if(t.size===0&&i.size===0)return;const r=new ee;this.#n!==`anti`&&this.emitInnerResults(t,i,r),(this.#n===`left`||this.#n===`full`||this.#n===`anti`)&&this.emitLeftOuterResults(t,i,r),(this.#n===`right`||this.#n===`full`)&&this.emitRightOuterResults(t,i,r),this.#t.append(t),this.#e.append(i),r.getInner().length>0&&this.output.sendData(r)}emitInnerResults(t,i,r){t.size>0&&r.extend(t.join(this.#e)),i.size>0&&r.extend(this.#t.join(i)),t.size>0&&i.size>0&&r.extend(t.join(i))}emitLeftOuterResults(t,i,r){if(t.size>0)for(const[l,o]of t.entriesIterators()){const u=this.#e.getConsolidatedMultiplicity(l),d=i.getConsolidatedMultiplicity(l);if(u+d===0)for(const[g,y]of o)y!==0&&r.add([l,[g,null]],y)}if(i.size>0)for(const l of i.getPresenceKeys()){const o=this.#e.getConsolidatedMultiplicity(l),u=i.getConsolidatedMultiplicity(l);if(u===0)continue;const d=o+u;if(o===0==(d===0))continue;const p=o===0;for(const[g,y]of this.#t.getIterator(l))y!==0&&r.add([l,[g,null]],p?-y:+y)}}emitRightOuterResults(t,i,r){if(i.size>0)for(const[l,o]of i.entriesIterators()){const u=this.#t.getConsolidatedMultiplicity(l),d=t.getConsolidatedMultiplicity(l);if(u+d===0)for(const[g,y]of o)y!==0&&r.add([l,[null,g]],y)}if(t.size>0)for(const l of t.getPresenceKeys()){const o=this.#t.getConsolidatedMultiplicity(l),u=t.getConsolidatedMultiplicity(l);if(u===0)continue;const d=o+u;if(o===0==(d===0))continue;const p=o===0;for(const[g,y]of this.#e.getIterator(l))y!==0&&r.add([l,[null,g]],p?-y:+y)}}}function Xv(n,t=`inner`){return i=>{if(i.graph!==n.graph)throw new Error(`Cannot join streams from different graphs`);const r=new Dn(i.graph,new Rn),l=new F_(i.graph.getNextOperatorId(),i.connectReader(),n.connectReader(),r.writer,t);return i.graph.addOperator(l),r}}class Q_ extends sp{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}inner(t){return t.map(this.#t)}}function le(n){return t=>{const i=new Dn(t.graph,new Rn),r=new Q_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class X_ extends Di{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}run(){for(const t of this.inputMessages())this.#t(t),this.output.sendData(t)}}function md(n){return t=>{const i=new Dn(t.graph,new Rn),r=new X_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class J_ extends sp{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}inner(t){return this.#t(t),t}}function Z_(n){return t=>{const i=new Dn(t.graph,new Rn),r=new J_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class W_ extends Di{#t;constructor(t,i,r,l,o){super(t,i,r);const u=o.limit??1/0,d=o.offset??0,p=this.createTopK(d,u,Fv(l));this.#t=new Qv(p),o.setSizeCallback?.(()=>this.#t.size),o.setWindowFn?.(this.moveTopK.bind(this))}createTopK(t,i,r){return new ip(t,i,r)}moveTopK({offset:t,limit:i}){const r=[],l=this.#t.move({offset:t,limit:i});l.moveIns.forEach(o=>bc(o,r)),l.moveOuts.forEach(o=>wc(o,r)),l.changes&&this.output.sendData(new ee(r))}run(){const t=[];for(const i of this.inputMessages())for(const[r,l]of i.getInner()){const[o,u]=r;this.processElement(o,u,l,t)}t.length>0&&this.output.sendData(new ee(t))}processElement(t,i,r,l){const o=this.#t.processElement(t,i,r);bc(o.moveIn,l),wc(o.moveOut,l)}}function P_(n,t){const i=t||{};return r=>{const l=new Dn(r.graph,new Rn),o=new W_(r.graph.getNextOperatorId(),r.connectReader(),l.writer,n,i);return r.graph.addOperator(o),l}}function dS(n){return`pipe`in n}function pS(n,t={}){const i=Object.fromEntries(Object.entries(t).filter(([r,l])=>!dS(l)));return Object.fromEntries(Object.entries(t).filter(([r,l])=>dS(l))),r=>{const l=`__original_key__`;return r.pipe(le(d=>{const p=n(d),g=cl(p),y={};y[l]=p;for(const[m,v]of Object.entries(i))y[m]=v.preMap(d);return[g,y]})).pipe($v(d=>{let p=0;for(const[m,v]of d)p+=v;if(p<=0)return[];const g={},y=d[0]?.[0]?.[l];g[l]=y;for(const[m,v]of Object.entries(i)){const w=d.map(([b,E])=>[b[m],E]);g[m]=v.reduce(w)}return[[g,1]]})).pipe(le(([d,p])=>{const g=p[l],y={};Object.assign(y,g);for(const[m,v]of Object.entries(i))v.postMap?y[m]=v.postMap(p[m]):y[m]=p[m];return[d,y]}))}}function tT(n=t=>t){return{preMap:t=>n(t),reduce:t=>{let i=0;for(const[r,l]of t)i+=r*l;return i}}}function eT(n=t=>t){return{preMap:t=>n(t)==null?0:1,reduce:t=>{let i=0;for(const[r,l]of t)i+=r*l;return i}}}function nT(n=t=>t){return{preMap:t=>({sum:n(t),count:0}),reduce:t=>{let i=0,r=0;for(const[l,o]of t)i+=l.sum*o,r+=o;return{sum:i,count:r}},postMap:t=>t.sum/t.count}}function sT(n){const t=n??(i=>i);return{preMap:i=>t(i),reduce:i=>{let r;for(const[l,o]of i)(!r||l&&li);return{preMap:i=>t(i),reduce:i=>{let r;for(const[l,o]of i)(!r||l&&l>r)&&(r=l);return r}}}const rT={sum:tT,count:eT,avg:nT,min:sT,max:iT};function aT(n,t){const i=t.limit??1/0,r=t.offset??0,l=t.setSizeCallback,o=t.setWindowFn,u=t.groupKeyFn,d=t.comparator??((p,g)=>p===g?0:pp.pipe(Y_((g,y)=>d(n(g),n(y)),{limit:i,offset:r,setSizeCallback:l,setWindowFn:o,groupKeyFn:u}),Vv())}function lT(n,t,i){const r=i?.limit??1/0,l=i?.offset??0,o=i?.setSizeCallback,u=i?.setWindowFn,d=i?.comparator??((p,g)=>p===g?0:pp.pipe(n((g,y)=>d(t(g),t(y)),{limit:r,offset:l,setSizeCallback:o,setWindowFn:u}),Vv())}function oT(n,t){return lT(P_,n,t)}const Bh=`__virtual_synced__`,Lh=`__virtual_has_local__`;function gS(n){let t=!1,i=!0,r=!1;for(const[l,o]of Object.entries(n)){if(l===`$selected`)continue;const u=o,d=`$synced`in u,p=`$origin`in u;!d&&!p||(t=!0,u.$synced===!1&&(i=!1),u.$origin===`local`&&(r=!0))}return{synced:t?i:!0,hasLocal:r}}const{sum:cT,count:uT,avg:fT,min:hT,max:dT}=rT;function pT(n,t){const i=new Map,r=[...n];if(!t)return{selectToGroupByIndex:i,groupByExpressions:r};for(const[l,o]of Object.entries(t)){if(o.type===`agg`||Lr(o))continue;const u=r.findIndex(d=>Ec(o,d));if(u===-1)throw new Ex(l);i.set(l,u)}return{selectToGroupByIndex:i,groupByExpressions:r}}function yS(n,t,i,r,l,o,u){const d={[Bh]:{preMap:([,b])=>gS(b).synced,reduce:b=>{for(const[E,_]of b)if(!E&&_>0)return!1;return!0}},[Lh]:{preMap:([,b])=>gS(b).hasLocal,reduce:b=>{for(const[E,_]of b)if(E&&_>0)return!0;return!1}}};if(t.length===0){const b=d,E={},_={value:0};if(r){for(const[O,A]of Object.entries(r))if(A.type===`agg`)b[O]=Jo(A);else if(Lr(A)){const{transformed:M,extracted:G}=Sd(A,_);for(const[q,K]of Object.entries(G))b[q]=Jo(K);E[O]=ue(M)}}const j=u?([,O])=>({__singleGroup:!0,__correlationKey:O?.[u]?.__correlationKey}):()=>({__singleGroup:!0});if(n=n.pipe(pS(j,b)),n=n.pipe(le(([,O])=>{const M={...O.$selected||{}};if(r){for(const[X,at]of Object.entries(r))at.type===`agg`&&(M[X]=O[X]);mS(M,O,E)}const G=u?O.__correlationKey:void 0,q=G!==void 0?`single_group_${cl(G)}`:`single_group`,K={...O,$selected:M},W=O[Bh],et=O[Lh];return K.$synced=W??!0,K.$origin=et?`local`:`remote`,K.$key=q,K.$collectionId=o??K.$collectionId,u&&G!==void 0&&(K[u]={__correlationKey:G}),[q,K]})),i&&i.length>0)for(const O of i){const A=J0(O),M=Cc(A,r||{},`$selected`),G=ue(M);n=n.pipe(ps(([,q])=>{const K={$selected:q.$selected};return Ar(G(K))}))}if(l&&l.length>0)for(const O of l)n=n.pipe(ps(([,A])=>{const M={$selected:A.$selected};return Ar(O(M))}));return n}const p=pT(t,r),g=t.map(b=>ue(b)),y=([,b])=>{const E={...b};delete E.$selected;const _={};for(let j=0;j{const E=b.$selected||{},_={};if(r){for(const[K,W]of Object.entries(r))if(W.type===`agg`)_[K]=b[K];else if(!v[K]){const et=p.selectToGroupByIndex.get(K);et!==void 0?_[K]=b[`__key_${et}`]:_[K]=E[K]}mS(_,b,v)}else for(let K=0;K0)for(const b of i){const E=J0(b),_=Cc(E,r||{}),j=ue(_);n=n.pipe(ps(([,O])=>{const A={$selected:O.$selected};return j(A)}))}if(l&&l.length>0)for(const b of l)n=n.pipe(ps(([,E])=>{const _={$selected:E.$selected};return Ar(b(_))}));return n}function Ec(n,t){if(!n||!t||n.type!==t.type)return!1;switch(n.type){case`ref`:return!n.path||!t.path||n.path.length!==t.path.length?!1:n.path.every((i,r)=>i===t.path[r]);case`val`:return n.value===t.value;case`func`:return n.name===t.name&&n.args?.length===t.args?.length&&(n.args||[]).every((i,r)=>Ec(i,t.args[r]));case`agg`:return n.name===t.name&&n.args?.length===t.args?.length&&(n.args||[]).every((i,r)=>Ec(i,t.args[r]));default:return!1}}function Jo(n){const t=ue(n.args[0]),i=([,o])=>{const u=t(o);return typeof u==`number`?u:u!=null?Number(u):0},r=([,o])=>{const u=t(o);return typeof u==`number`||typeof u==`string`||typeof u==`bigint`||u instanceof Date?u:u!=null?Number(u):0},l=([,o])=>t(o);switch(n.name.toLowerCase()){case`sum`:return cT(i);case`count`:return uT(l);case`avg`:return fT(i);case`min`:return hT(r);case`max`:return dT(r);default:throw new Cx(n.name)}}function Cc(n,t,i=`$selected`){switch(n.type){case`agg`:{const r=n;for(const[l,o]of Object.entries(t))if(o.type===`agg`&&gT(r,o))return new Oe([i,l]);throw new xx(r.name)}case`func`:{const r=n,l=r.args.map(o=>Cc(o,t));return new Ve(r.name,l)}case`ref`:return n;case`val`:return n;default:throw new _x(n.type)}}function mS(n,t,i){for(const r of Object.keys(t))r.startsWith(`__agg_`)&&(n[r]=t[r]);for(const[r,l]of Object.entries(i))n[r]=l({$selected:n});for(const r of Object.keys(n))r.startsWith(`__agg_`)&&delete n[r]}function Lr(n){return Br(n)?n.type===`agg`?!0:n.type===`func`&&`args`in n?n.args.some(t=>Lr(t)):!1:!1}function Sd(n,t){if(n.type===`agg`){const i=`__agg_${t.value++}`;return{transformed:new Oe([`$selected`,i]),extracted:{[i]:n}}}if(n.type===`func`){const i={},r=n.args.map(l=>{const o=Sd(l,t);return Object.assign(i,o.extracted),o.transformed});return{transformed:new Ve(n.name,r),extracted:i}}return{transformed:n,extracted:{}}}function gT(n,t){return n.name===t.name&&n.args.length===t.args.length&&n.args.every((i,r)=>Ec(i,t.args[r]))}function yT(n,t,i,r,l,o,u,d,p,g){const y=i.map(E=>{const _=Cc(E.expression,r,`$selected`);return{compiledExpression:ue(_),compareOptions:vd(E,l)}}),m=E=>{const _=E;return i.length>1?y.map(j=>j.compiledExpression(_)):i.length===1?y[0].compiledExpression(_):null},v=(E,_)=>{if(i.length>1){const j=E,O=_;for(let A=0;A1?String(M.path[0]):n.from.alias}}if(j){const q=i.every(X=>X.expression.type===`ref`)?i.map(X=>{const at=X.expression,nt=ol(n,at,l);return ue(nt?new Oe(nt.path):X.expression,!0)}):void 0;b={alias:O,offset:p??0,limit:d,comparator:(X,at)=>{if(i.length===1){const nt=X&&j(X),bt=at&&j(at);return v(nt,bt)}if(q){const nt=bt=>bt&&q.map(Lt=>Lt(bt));return v(nt(X),nt(at))}return 0},valueExtractorForRawRow:X=>{if(i.length===1)return j(X);if(q)return q.map(at=>at(X))},firstColumnValueExtractor:j,index:E,orderBy:i};const et=_?.id??l.id;o[et]=b,w=X=>{o[et].dataNeeded=()=>{const at=X();return Math.max(0,b.limit-at)}}}}return g?t.pipe(aT(m,{limit:d,offset:p,comparator:v,setSizeCallback:w,groupKeyFn:g,setWindowFn:E=>{u(_=>{E(_),b&&(b.offset=_.offset??b.offset,b.limit=_.limit??b.limit)})}})):t.pipe(oT(m,{limit:d,offset:p,comparator:v,setSizeCallback:w,setWindowFn:E=>{u(_=>{E(_),b&&(b.offset=_.offset??b.offset,b.limit=_.limit??b.limit)})}}))}function vd(n,t){return n.compareOptions.stringSort!==void 0?n.compareOptions:{...t.compareOptions,direction:n.compareOptions.direction,nulls:n.compareOptions.nulls}}function mT(n,t={}){const i=r=>{const l=[];for(const[o,u]of n.entries())(r?.(u)??!0)&&l.push({type:`insert`,key:o,value:u});return l};if(t.limit!==void 0&&!t.orderBy)throw new Error(`limit cannot be used without orderBy`);if(t.orderBy){const r=t.where?el(t.where):void 0,l=vT(n,t.orderBy,t.limit,r,t.optimizedOnly);if(l===void 0)return;const o=[];for(const u of l){const d=n.get(u);d!==void 0&&o.push({type:`insert`,key:u,value:d})}return o}if(!t.where)return i();try{const r=t.where,l=Yx(r,n);if(l.canOptimize){const o=[];for(const u of l.matchingKeys){const d=n.get(u);d!==void 0&&o.push({type:`insert`,key:u,value:d})}return o}else{if(t.optimizedOnly)return;const o=el(r);return i(o)}}catch(r){console.warn(`${n.id?`[${n.id}] `:``}Error processing where clause, falling back to full scan:`,r);const l=el(t.where);return t.optimizedOnly?void 0:i(l)}}function el(n){const t=Bv(n);return i=>{try{const r=t(i);return Ar(r)}catch{return!1}}}function ST(n,t){const i=el(t.whereExpression);return r=>{const l=[];for(const o of r)if(o.type===`insert`)i(o.value)&&l.push(o);else if(o.type===`update`){const u=i(o.value),d=o.previousValue?i(o.previousValue):!1;u&&d?l.push(o):u&&!d?l.push({...o,type:`insert`}):!u&&d&&l.push({...o,type:`delete`,value:o.previousValue})}else i(o.value)&&l.push(o);(l.length>0||r.length===0)&&n(l)}}function vT(n,t,i,r,l){if(t.length===1){const p=t[0],g=p.expression;if(g.type===`ref`){const m=g.path,v=vd(p,n);$c(m[0],m,n,v);const w=xl(n,m,v);if(w&&w.supports(`gt`)){const b=E=>{const _=n.get(E);return _===void 0?!1:r?.(_)??!0};return w.takeFromStart(i??w.keyCount,b)}}}if(l)return;const o=[];for(const[p,g]of n.entries())(r?.(g)??!0)&&o.push({key:p,value:g});const u=(p,g)=>{for(const y of t){const m=Pa(y.compareOptions),v=SS(p.value,y.expression),w=SS(g.value,y.expression),b=m(v,w);if(b!==0)return b}return 0};o.sort(u);const d=o.map(p=>p.key);return i!==void 0?d.slice(0,i):d}function SS(n,t){if(t.type===`ref`){const i=t;let r=n;for(const l of i.path)r=r?.[l];return r}else return t.type===`val`?t.value:Bv(t)(n)}class vS{constructor(t){this.map=new Map,this.sortedKeys=[],this.comparator=t}indexOf(t,i){let r=0,l=this.sortedKeys.length;if(!this.comparator){for(;r0)r=o+1;else return o}return r}for(;r0)r=o+1;else{const g=gd(t,u);if(g<0)l=o;else if(g>0)r=o+1;else return o}}return r}set(t,i){if(this.map.has(t)){const l=this.map.get(t),o=this.indexOf(t,l);this.sortedKeys.splice(o,1)}const r=this.indexOf(t,i);return this.sortedKeys.splice(r,0,t),this.map.set(t,i),this}get(t){return this.map.get(t)}delete(t){if(this.map.has(t)){const i=this.map.get(t),r=this.indexOf(t,i);return this.sortedKeys.splice(r,1),this.map.delete(t)}return!1}has(t){return this.map.has(t)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(const t of this.sortedKeys)yield[t,this.map.get(t)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(const t of this.sortedKeys)yield this.map.get(t)}).call(this)}forEach(t){for(const i of this.sortedKeys)t(this.map.get(i),i,this.map)}}const lc=`__tanstack_db_direct`;class bT{constructor(t){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{let i=!1;for(const d of this.transactions.values())if(d.state===`persisting`){i=!0;break}const{committedSyncedTransactions:r,uncommittedSyncedTransactions:l,hasTruncateSync:o,hasImmediateSync:u}=this.pendingSyncedTransactions.reduce((d,p)=>(p.committed?(d.committedSyncedTransactions.push(p),p.truncate&&(d.hasTruncateSync=!0),p.immediate&&(d.hasImmediateSync=!0)):d.uncommittedSyncedTransactions.push(p),d),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!i||o||u){this.isCommittingSyncTransactions=!0;const d=new Map(this.rowOrigins),p=new Map(this.optimisticUpserts),g=new Set(this.optimisticDeletes),y=o?r.find(O=>O.truncate)?.optimisticSnapshot:null;let m,v;const w=new Set;for(const O of r){for(const A of O.operations)w.add(A.key);for(const[A]of O.rowMetadataWrites)w.add(A)}let b=this.preSyncVisibleState;if(b.size===0){b=new Map;for(const O of w){const A=this.get(O);A!==void 0&&b.set(O,A)}}const E=[],_=this.config.sync.rowUpdateMode||`partial`,j=new Map;for(const O of this.transactions.values())if(O.state===`completed`)for(const A of O.mutations)this.isThisCollection(A.collection)&&A.optimistic&&j.set(A.key,{type:A.type,value:A.modified});for(const O of r){if(O.truncate){const A=new Set([...this.syncedData.keys(),...y?.upserts.keys()||[]]);for(const M of A){if(y?.deletes.has(M))continue;const G=y?.upserts.get(M)||this.syncedData.get(M);G!==void 0&&E.push({type:`delete`,key:M,value:G})}m=new Set(this.pendingLocalChanges),v=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.clearOriginTrackingState();for(const M of w)b.delete(M);this._events.emit(`truncate`,{type:`truncate`,collection:this.collection})}for(const A of O.operations){const M=A.key;this.syncedKeys.add(M);const G=this.isLocalOnly||this.pendingLocalChanges.has(M)||this.pendingLocalOrigins.has(M)||m?.has(M)===!0||v?.has(M)===!0?`local`:`remote`;switch(A.type){case`insert`:this.syncedData.set(M,A.value),this.rowOrigins.set(M,G),this.pendingLocalChanges.delete(M),this.pendingLocalOrigins.delete(M),this.pendingOptimisticUpserts.delete(M),this.pendingOptimisticDeletes.delete(M),this.pendingOptimisticDirectUpserts.delete(M),this.pendingOptimisticDirectDeletes.delete(M);break;case`update`:{if(_===`partial`){const q=Object.assign({},this.syncedData.get(M),A.value);this.syncedData.set(M,q)}else this.syncedData.set(M,A.value);this.rowOrigins.set(M,G),this.pendingLocalChanges.delete(M),this.pendingLocalOrigins.delete(M),this.pendingOptimisticUpserts.delete(M),this.pendingOptimisticDeletes.delete(M),this.pendingOptimisticDirectUpserts.delete(M),this.pendingOptimisticDirectDeletes.delete(M);break}case`delete`:this.syncedData.delete(M),this.syncedMetadata.delete(M),this.rowOrigins.delete(M),this.pendingLocalChanges.delete(M),this.pendingLocalOrigins.delete(M),this.pendingOptimisticUpserts.delete(M),this.pendingOptimisticDeletes.delete(M),this.pendingOptimisticDirectUpserts.delete(M),this.pendingOptimisticDirectDeletes.delete(M);break}}for(const[A,M]of O.rowMetadataWrites){if(M.type===`delete`){this.syncedMetadata.delete(A);continue}this.syncedMetadata.set(A,M.value)}for(const[A,M]of O.collectionMetadataWrites){if(M.type===`delete`){this.syncedCollectionMetadata.delete(A);continue}this.syncedCollectionMetadata.set(A,M.value)}}if(o){const O=new Set;for(const G of r)for(const q of G.operations)(q.type===`insert`||q.type===`update`)&&O.add(q.key);const A=new Map(y.upserts),M=new Set(y.deletes);for(const[G,q]of A)if(!M.has(G))if(O.has(G)){let K=!1;for(let W=E.length-1;W>=0;W--){const et=E[W];if(et.key===G&&et.type===`insert`){et.value=q,K=!0;break}}K||E.push({type:`insert`,key:G,value:q})}else E.push({type:`insert`,key:G,value:q});if(E.length>0&&M.size>0){const G=[];for(const q of E)q.type===`insert`&&M.has(q.key)||G.push(q);E.length=0,E.push(...G)}this.lifecycle.status!==`ready`&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,o&&y){for(const[O,A]of y.upserts)this.optimisticUpserts.set(O,A);for(const O of y.deletes)this.optimisticDeletes.add(O)}for(const O of this.transactions.values())if(![`completed`,`failed`].includes(O.state)){for(const A of O.mutations)if(this.isThisCollection(A.collection)&&A.optimistic)switch(A.type){case`insert`:case`update`:this.optimisticUpserts.set(A.key,A.modified),this.optimisticDeletes.delete(A.key);break;case`delete`:this.optimisticUpserts.delete(A.key),this.optimisticDeletes.add(A.key);break}}for(const O of w){const A=b.get(O),M=this.get(O),G=this.getVirtualPropsSnapshotForState(O,{rowOrigins:d,optimisticUpserts:p,optimisticDeletes:g,completedOptimisticKeys:j}),q=this.getVirtualPropsSnapshotForState(O),K=G.$synced!==q.$synced||G.$origin!==q.$origin,W=A!==void 0?rS(A,O,this.collection.id,()=>G.$synced,()=>G.$origin):void 0,et=j.get(O);let X=!1;et&&(et.type===`delete`&&A!==void 0&&M===void 0&&Bn(et.value,A)||M!==void 0&&Bn(et.value,M))&&(X=!0);const at=K&&A!==void 0&&M!==void 0&&Bn(A,M);if(!(X&&!at))if(A===void 0&&M!==void 0){const nt=j.get(O);if(nt){const bt=nt.value,Lt=rS(bt,O,this.collection.id,()=>G.$synced,()=>G.$origin);E.push({type:`update`,key:O,value:M,previousValue:Lt})}else E.push({type:`insert`,key:O,value:M})}else A!==void 0&&M===void 0?E.push({type:`delete`,key:O,value:W??A}):A!==void 0&&M!==void 0&&(!Bn(A,M)||at)&&E.push({type:`update`,key:O,value:M,previousValue:W??A})}this.size=this.calculateSize(),E.length>0&&this.indexes.updateIndexes(E),this.changes.emitEvents(E,!0),this.pendingSyncedTransactions=l,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0)}},this.config=t,this.transactions=new vS((i,r)=>i.compareCreatedAt(r)),this.syncedData=new vS(t.compare)}setDeps(t){this.collection=t.collection,this.lifecycle=t.lifecycle,this.changes=t.changes,this.indexes=t.indexes,this._events=t.events}isRowSynced(t){return this.isLocalOnly?!0:!this.optimisticUpserts.has(t)&&!this.optimisticDeletes.has(t)}getRowOrigin(t){return this.isLocalOnly||this.optimisticUpserts.has(t)||this.optimisticDeletes.has(t)?`local`:this.rowOrigins.get(t)??`remote`}createVirtualPropsSnapshot(t,i){return{$synced:i?.$synced??this.isRowSynced(t),$origin:i?.$origin??this.getRowOrigin(t),$key:i?.$key??t,$collectionId:i?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(t,i){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(t,{$synced:!0,$origin:`local`});const r=i?.optimisticUpserts??this.optimisticUpserts,l=i?.optimisticDeletes??this.optimisticDeletes,o=r.has(t)||l.has(t)||i?.completedOptimisticKeys?.has(t)===!0;return this.createVirtualPropsSnapshot(t,{$synced:!o,$origin:o?`local`:(i?.rowOrigins??this.rowOrigins).get(t)??`remote`})}enrichWithVirtualPropsSnapshot(t,i){const r=t,l=r.$synced??i.$synced,o=r.$origin??i.$origin,u=r.$key??i.$key,d=r.$collectionId??i.$collectionId,p=this.virtualPropsCache.get(t);if(p&&p.synced===l&&p.origin===o&&p.key===u&&p.collectionId===d)return p.enriched;const g={...t,$synced:l,$origin:o,$key:u,$collectionId:d};return this.virtualPropsCache.set(t,{synced:l,origin:o,key:u,collectionId:d,enriched:g}),g}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(t,i){return this.enrichWithVirtualPropsSnapshot(t,this.createVirtualPropsSnapshot(i))}enrichChangeMessage(t){const{__virtualProps:i}=t,r=i?.value?this.enrichWithVirtualPropsSnapshot(t.value,i.value):this.enrichWithVirtualProps(t.value,t.key),l=t.previousValue?i?.previousValue?this.enrichWithVirtualPropsSnapshot(t.previousValue,i.previousValue):this.enrichWithVirtualProps(t.previousValue,t.key):void 0;return{key:t.key,type:t.type,value:r,previousValue:l,metadata:t.metadata}}getWithVirtualProps(t){const i=this.get(t);if(i!==void 0)return this.enrichWithVirtualProps(i,t)}get(t){const{optimisticDeletes:i,optimisticUpserts:r,syncedData:l}=this;if(!i.has(t))return r.has(t)?r.get(t):l.get(t)}has(t){const{optimisticDeletes:i,optimisticUpserts:r,syncedData:l}=this;return i.has(t)?!1:r.has(t)?!0:l.has(t)}*keys(){const{syncedData:t,optimisticDeletes:i,optimisticUpserts:r}=this;for(const l of t.keys())i.has(l)||(yield l);for(const l of r.keys())!t.has(l)&&!i.has(l)&&(yield l)}*values(){for(const t of this.keys()){const i=this.get(t);i!==void 0&&(yield i)}}*entries(){for(const t of this.keys()){const i=this.get(t);i!==void 0&&(yield[t,i])}}*[Symbol.iterator](){for(const[t,i]of this.entries())yield[t,i]}forEach(t){let i=0;for(const[r,l]of this.entries())t(l,r,i++)}map(t){const i=[];let r=0;for(const[l,o]of this.entries())i.push(t(o,l,r++));return i}isThisCollection(t){return t===this.collection}recomputeOptimisticState(t=!1){if(this.isCommittingSyncTransactions&&!t)return;const i=new Map(this.optimisticUpserts),r=new Set(this.optimisticDeletes),l=new Map(this.rowOrigins);for(const m of this.transactions.values()){const v=m.metadata[lc]===!0;if(m.state===`completed`){for(const w of m.mutations)if(this.isThisCollection(w.collection)&&(this.pendingLocalOrigins.add(w.key),!!w.optimistic))switch(w.type){case`insert`:case`update`:this.pendingOptimisticUpserts.set(w.key,w.modified),this.pendingOptimisticDeletes.delete(w.key),v?(this.pendingOptimisticDirectUpserts.add(w.key),this.pendingOptimisticDirectDeletes.delete(w.key)):(this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.delete(w.key));break;case`delete`:this.pendingOptimisticUpserts.delete(w.key),this.pendingOptimisticDeletes.add(w.key),v?(this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.add(w.key)):(this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.delete(w.key));break}}else if(m.state===`failed`)for(const w of m.mutations)this.isThisCollection(w.collection)&&(this.pendingLocalOrigins.delete(w.key),w.optimistic&&(this.pendingOptimisticUpserts.delete(w.key),this.pendingOptimisticDeletes.delete(w.key),this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.delete(w.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();const o=new Set;for(const m of this.pendingSyncedTransactions)for(const v of m.operations)o.add(v.key);const u=[];for(const[m,v]of this.pendingOptimisticUpserts)o.has(m)||this.pendingOptimisticDirectUpserts.has(m)?this.optimisticUpserts.set(m,v):u.push(m);for(const m of u)this.pendingOptimisticUpserts.delete(m),this.pendingLocalOrigins.delete(m);const d=[];for(const m of this.pendingOptimisticDeletes)o.has(m)||this.pendingOptimisticDirectDeletes.has(m)?this.optimisticDeletes.add(m):d.push(m);for(const m of d)this.pendingOptimisticDeletes.delete(m),this.pendingLocalOrigins.delete(m);const p=[];for(const m of this.transactions.values())[`completed`,`failed`].includes(m.state)||p.push(m);for(const m of p)for(const v of m.mutations)if(this.isThisCollection(v.collection)&&(this.pendingLocalChanges.add(v.key),v.optimistic))switch(v.type){case`insert`:case`update`:this.optimisticUpserts.set(v.key,v.modified),this.optimisticDeletes.delete(v.key);break;case`delete`:this.optimisticUpserts.delete(v.key),this.optimisticDeletes.add(v.key);break}this.size=this.calculateSize();const g=[];this.collectOptimisticChanges(i,r,l,g);const y=g.filter(m=>!!(!this.recentlySyncedKeys.has(m.key)||t));if(this.pendingSyncedTransactions.length>0&&!t){const m=new Set;for(const w of this.pendingSyncedTransactions)for(const b of w.operations)m.add(b.key);const v=y.filter(w=>!(w.type===`delete`&&m.has(w.key)&&!p.some(E=>E.mutations.some(_=>this.isThisCollection(_.collection)&&_.key===w.key))));v.length>0&&this.indexes.updateIndexes(v),this.changes.emitEvents(v,t)}else y.length>0&&this.indexes.updateIndexes(y),this.changes.emitEvents(y,t)}calculateSize(){const t=this.syncedData.size,i=Array.from(this.optimisticDeletes).filter(l=>this.syncedData.has(l)&&!this.optimisticUpserts.has(l)).length,r=Array.from(this.optimisticUpserts.keys()).filter(l=>!this.syncedData.has(l)).length;return t-i+r}collectOptimisticChanges(t,i,r,l){const o=new Set([...t.keys(),...this.optimisticUpserts.keys(),...i,...this.optimisticDeletes]);for(const u of o){const d=this.get(u),p=this.getPreviousValue(u,t,i),g=this.getVirtualPropsSnapshotForState(u,{rowOrigins:r,optimisticUpserts:t,optimisticDeletes:i}),y=this.getVirtualPropsSnapshotForState(u);p!==void 0&&d===void 0?l.push({type:`delete`,key:u,value:p,__virtualProps:{value:g}}):p===void 0&&d!==void 0?l.push({type:`insert`,key:u,value:d,__virtualProps:{value:y}}):p!==void 0&&d!==void 0&&p!==d&&l.push({type:`update`,key:u,value:d,previousValue:p,__virtualProps:{value:y,previousValue:g}})}}getPreviousValue(t,i,r){if(!r.has(t))return i.has(t)?i.get(t):this.syncedData.get(t)}scheduleTransactionCleanup(t){if(t.state===`completed`){this.transactions.delete(t.id);return}t.isPersisted.promise.then(()=>{this.transactions.delete(t.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;const t=new Set;for(const i of this.pendingSyncedTransactions)for(const r of i.operations)t.add(r.key);for(const i of t)this.recentlySyncedKeys.add(i);for(const i of t)if(!this.preSyncVisibleState.has(i)){const r=this.get(i);r!==void 0&&this.preSyncVisibleState.set(i,r)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}}function Jv(){const n=new Map;function t(i){const r=i.join(`.`);if(n.has(r))return n.get(r);const l=new Proxy({},{get(o,u,d){if(u===`__refProxy`)return!0;if(u===`__path`)return i;if(u===`__type`)return;if(typeof u==`symbol`)return Reflect.get(o,u,d);const p=[...i,String(u)];return t(p)},has(o,u){return u===`__refProxy`||u===`__path`||u===`__type`?!0:Reflect.has(o,u)},ownKeys(o){return Reflect.ownKeys(o)},getOwnPropertyDescriptor(o,u){return u===`__refProxy`||u===`__path`||u===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(o,u)}});return n.set(r,l),l}return t([])}function vi(n){const t=new Map;let i=0;function r(o){const u=o.join(`.`);if(t.has(u))return t.get(u);const d=new Proxy({},{get(p,g,y){if(g===`__refProxy`)return!0;if(g===`__path`)return o;if(g===`__type`)return;if(typeof g==`symbol`)return Reflect.get(p,g,y);const m=[...o,String(g)];return r(m)},has(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?!0:Reflect.has(p,g)},ownKeys(p){const g=++i,y=`__SPREAD_SENTINEL__${o.join(`.`)}__${g}`;return Object.prototype.hasOwnProperty.call(p,y)||Object.defineProperty(p,y,{enumerable:!0,configurable:!0,value:!0}),Reflect.ownKeys(p)},getOwnPropertyDescriptor(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(p,g)}});return t.set(u,d),d}return new Proxy({},{get(o,u,d){if(u===`__refProxy`)return!0;if(u===`__path`)return[];if(u===`__type`)return;if(typeof u==`symbol`)return Reflect.get(o,u,d);const p=String(u);if(n.includes(p))return r([p])},has(o,u){return u===`__refProxy`||u===`__path`||u===`__type`||typeof u==`string`&&n.includes(u)?!0:Reflect.has(o,u)},ownKeys(o){return[...n,`__refProxy`,`__path`,`__type`]},getOwnPropertyDescriptor(o,u){if(u===`__refProxy`||u===`__path`||u===`__type`)return{enumerable:!1,configurable:!0};if(typeof u==`string`&&n.includes(u))return{enumerable:!0,configurable:!0}}})}function bS(n){const t=vi(n),i=new Map;function r(o){const u=o.join(`.`);if(i.has(u))return i.get(u);const d=new Proxy({},{get(p,g,y){if(g===`__refProxy`)return!0;if(g===`__path`)return[`$selected`,...o];if(g===`__type`)return;if(typeof g==`symbol`)return Reflect.get(p,g,y);const m=[...o,String(g)];return r(m)},has(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?!0:Reflect.has(p,g)},ownKeys(p){return Reflect.ownKeys(p)},getOwnPropertyDescriptor(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(p,g)}});return i.set(u,d),d}const l=r([]);return new Proxy(t,{get(o,u,d){return u===`$selected`?l:Reflect.get(o,u,d)},has(o,u){return u===`$selected`?!0:Reflect.has(o,u)},ownKeys(o){return[...Reflect.ownKeys(o),`$selected`]},getOwnPropertyDescriptor(o,u){return u===`$selected`?{enumerable:!0,configurable:!0,value:l}:Reflect.getOwnPropertyDescriptor(o,u)}})}function ne(n){return oc(n)?new Oe(n.__path):n&&typeof n==`object`&&`type`in n&&(n.type===`func`||n.type===`ref`||n.type===`val`||n.type===`agg`)?n:new Ue(n)}function oc(n){return n&&typeof n==`object`&&n.__refProxy===!0}function bd(n,t){return new Ve(`eq`,[ne(n),ne(t)])}function wd(n,t){return new Ve(`gt`,[ne(n),ne(t)])}function wT(n,t){return new Ve(`gte`,[ne(n),ne(t)])}function Ed(n,t){return new Ve(`lt`,[ne(n),ne(t)])}function Cd(n,t,...i){const r=[n,t,...i];return new Ve(`and`,r.map(l=>ne(l)))}function ET(n,t,...i){const r=[n,t,...i];return new Ve(`or`,r.map(l=>ne(l)))}function CT(n,t){return new Ve(`in`,[ne(n),ne(t)])}class xT{constructor(t){this.query=t}}class _T{constructor(t){this.query=t}}class Zv{constructor(){this.listeners=new Map}on(t,i){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(i),()=>{this.listeners.get(t)?.delete(i)}}once(t,i){const r=this.on(t,l=>{i(l),r()});return r}off(t,i){this.listeners.get(t)?.delete(i)}waitFor(t,i){return new Promise((r,l)=>{let o;const u=this.on(t,d=>{o&&(clearTimeout(o),o=void 0),r(d),u()});i&&(o=setTimeout(()=>{o=void 0,u(),l(new Error(`Timeout waiting for event ${String(t)}`))},i))})}emitInner(t,i){this.listeners.get(t)?.forEach(r=>{try{r(i)}catch(l){queueMicrotask(()=>{throw l})}})}clearListeners(){this.listeners.clear()}}function TT(n,t){if(t.length===0||n.length===0)return;if(n.length===1){const{expression:r,compareOptions:l}=n[0];return(l.direction===`asc`?wd:Ed)(r,new Ue(t[0]))}const i=[];for(let r=0;rCd(y,m)))}}return i.length===1?i[0]:i.reduce((r,l)=>ET(r,l))}class AT extends Zv{constructor(t,i,r){super(),this.collection=t,this.callback=i,this.options=r,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.loadedSubsets=[],this.sentKeys=new Set,this.limitedSnapshotRowCount=0,this._status=`ready`,this.pendingLoadSubsetPromises=new Set,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches=new Set,r.onUnsubscribe&&this.on(`unsubscribed`,o=>r.onUnsubscribe(o)),r.whereExpression&&Wx(r.whereExpression,this.collection);const l=o=>{i(o),this.trackSentKeys(o)};this.callback=l,this.filteredCallback=r.whereExpression?ST(this.callback,r):this.callback,this.truncateCleanup=this.collection.on(`truncate`,()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){const t=[...this.loadedSubsets],i=this.collection._sync.syncLoadSubsetFn!==null;if(t.length===0||!i){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[];return}this.isBufferingForTruncate=!0,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[],queueMicrotask(()=>{if(this.isBufferingForTruncate){for(const r of t){const l=this.collection._sync.loadSubset(r);this.loadedSubsets.push(r),this.trackLoadSubsetPromise(l),l instanceof Promise&&(this.pendingTruncateRefetches.add(l),l.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(l),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;const t=this.truncateBuffer.flat();t.length>0&&this.filteredCallback(t),this.truncateBuffer=[]}setOrderByIndex(t){this.orderByIndex=t}hasOrderByIndex(){return this.orderByIndex!==void 0}setStatus(t){if(this._status===t)return;const i=this._status;this._status=t,this.emitInner(`status:change`,{type:`status:change`,subscription:this,previousStatus:i,status:t});const r=`status:${t}`;this.emitInner(r,{type:r,subscription:this,previousStatus:i,status:t})}trackLoadSubsetPromise(t){t instanceof Promise&&(this.pendingLoadSubsetPromises.add(t),this.setStatus(`loadingSubset`),t.finally(()=>{this.pendingLoadSubsetPromises.delete(t),this.pendingLoadSubsetPromises.size===0&&this.setStatus(`ready`)}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(t){const i=this.filterAndFlipChanges(t);this.isBufferingForTruncate?i.length>0&&this.truncateBuffer.push(i):this.filteredCallback(i)}requestSnapshot(t){if(this.loadedInitialState)return!1;const i={where:this.options.whereExpression,optimizedOnly:t?.optimizedOnly??!1};if(t){if(`where`in t){const p=t.where;if(i.where){const g=i.where,y=Cd(g,p);i.where=y}else i.where=p}}else this.loadedInitialState=!0;const r={where:i.where,subscription:this,orderBy:t?.orderBy,limit:t?.limit},l=this.collection._sync.loadSubset(r);t?.onLoadSubsetResult?.(l),this.loadedSubsets.push(r),(t?.trackLoadSubsetPromise??!0)&&this.trackLoadSubsetPromise(l);const u=this.collection.currentStateAsChanges(i);if(u===void 0)return!1;const d=u.filter(p=>!this.sentKeys.has(p.key));for(const p of d)this.sentKeys.add(p.key);return this.snapshotSent=!0,this.callback(d),!0}requestLimitedSnapshot({orderBy:t,limit:i,minValues:r,offset:l,trackLoadSubsetPromise:o=!0,onLoadSubsetResult:u}){if(!i)throw new Error(`limit is required`);if(!this.orderByIndex)throw new Error(`Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.`);const d=r!==void 0&&r.length>0,g=r?.[0],y=this.orderByIndex,m=this.options.whereExpression,v=m?el(m):void 0,w=et=>{if(et!==void 0&&this.sentKeys.has(et))return!1;const X=this.collection.get(et);return X===void 0?!1:v?.(X)??!0};let b=g;const E=[];let _=[];if(d){const{expression:et}=t[0],X=this.collection.currentStateAsChanges({where:bd(et,new Ue(g))});if(X){const at=X.map(bt=>bt.key).filter(bt=>!this.sentKeys.has(bt)&&w(bt));_.push(...at);const nt=y.take(i-_.length,g,w);_.push(...nt)}else _=y.take(i,g,w)}else _=y.takeFromStart(i,w);const j=()=>Math.max(i-E.length,0),O=()=>_.length===0,A=t[0].expression,M=A.type===`ref`?ue(new Oe(A.path),!0):null;for(;j()>0&&!O();){const et=new Set;for(const X of _){const at=this.collection.get(X);E.push({type:`insert`,key:X,value:at}),b=M?M(at):at,et.add(X)}_=y.take(j(),b,w)}const G=this.limitedSnapshotRowCount;for(const et of E)this.sentKeys.add(et.key);this.callback(E),this.limitedSnapshotRowCount+=E.length,E.length>0&&(this.lastSentKey=E[E.length-1].key);let q;if(r!==void 0&&r.length>0){const et=TT(t,r);if(et){const{expression:X}=t[0],at=r[0];let nt;if(at instanceof Date){const bt=new Date(at.getTime()+1);nt=Cd(wT(X,new Ue(at)),Ed(X,new Ue(bt)))}else nt=bd(X,new Ue(at));q={whereFrom:et,whereCurrent:nt,lastKey:this.lastSentKey}}}const K={where:m,limit:i,orderBy:t,cursor:q,offset:l??G,subscription:this},W=this.collection._sync.loadSubset(K);u?.(W),this.loadedSubsets.push(K),o&&this.trackLoadSubsetPromise(W)}filterAndFlipChanges(t){if(this.loadedInitialState||this.skipFiltering)return t;const i=this.isBufferingForTruncate,r=[];for(const l of t){let o=l;if(this.sentKeys.has(l.key)){if(l.type===`insert`)continue;l.type===`delete`&&this.sentKeys.delete(l.key)}else{if(l.type===`update`)o={...l,type:`insert`,previousValue:void 0};else if(l.type===`delete`&&!i)continue;this.sentKeys.add(l.key)}r.push(o)}return r}trackSentKeys(t){if(!(this.loadedInitialState||this.skipFiltering)){for(const i of t)i.type===`delete`?this.sentKeys.delete(i.key):this.sentKeys.add(i.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){this.truncateCleanup?.(),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear();for(const t of this.loadedSubsets)this.collection._sync.unloadSubset(t);this.loadedSubsets=[],this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this}),this.clearListeners()}}class OT{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1}setDeps(t){this.lifecycle=t.lifecycle,this.sync=t.sync,this.events=t.events,this.collection=t.collection,this.state=t.state}emitEmptyReadyEvent(){for(const t of this.changeSubscriptions)t.emitEvents([])}enrichChangeWithVirtualProps(t){return this.state.enrichChangeMessage(t)}emitEvents(t,i=!1){if(this.shouldBatchEvents&&!i){this.batchedEvents.push(...t);return}let r=t;if(i&&(this.batchedEvents.length>0&&(r=[...this.batchedEvents,...t]),this.batchedEvents=[],this.shouldBatchEvents=!1),r.length===0)return;const l=r.map(o=>this.enrichChangeWithVirtualProps(o));for(const o of this.changeSubscriptions)o.emitEvents(l)}subscribeChanges(t,i={}){if(this.addSubscriber(),i.where&&i.whereExpression)throw new Error(`Cannot specify both 'where' and 'whereExpression' options. Use one or the other.`);const{where:r,...l}=i;let o=l.whereExpression;if(r){const d=Jv(),p=r(d);o=ne(p)}const u=new AT(this.collection,t,{...l,whereExpression:o,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(u)}});return i.onStatusChange&&u.on(`status:change`,i.onStatusChange),i.includeInitialState?u.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:i.orderBy,limit:i.limit,onLoadSubsetResult:i.onLoadSubsetResult}):i.includeInitialState===!1&&u.markAllStateAsSeen(),this.changeSubscriptions.add(u),u}addSubscriber(){const t=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer(),(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync(),this.events.emitSubscribersChange(this.activeSubscribersCount,t)}removeSubscriber(){const t=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new UC;this.events.emitSubscribersChange(this.activeSubscribersCount,t)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}}const RT=n=>setTimeout(()=>{n({didTimeout:!0,timeRemaining:()=>50})},0),DT=n=>{clearTimeout(n)},MT=typeof window<`u`&&`requestIdleCallback`in window?(n,t)=>window.requestIdleCallback(n,t):(n,t)=>RT(n),Ih=typeof window<`u`&&`cancelIdleCallback`in window?n=>window.cancelIdleCallback(n):DT,Wv=class fs{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return fs.instance||(fs.instance=new fs),fs.instance}schedule(t,i,r){const l=Date.now()+i;this.tasks.set(t,{executeAt:l,callback:r}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(t){this.tasks.delete(t)}updateTimeout(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let t=1/0;for(const r of this.tasks.values())r.executeAtthis.process(),i)}process(){this.timeoutId=null;const t=Date.now();for(const[i,r]of this.tasks.entries())if(t>=r.executeAt){this.tasks.delete(i);try{r.callback()}catch(l){console.error(`Error in CleanupQueue task:`,l)}}this.tasks.size>0&&this.updateTimeout()}static resetInstance(){fs.instance&&(fs.instance.timeoutId!==null&&clearTimeout(fs.instance.timeoutId),fs.instance=null)}};Wv.instance=null;let Hh=Wv;class kT{constructor(t,i){this.status=`idle`,this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.config=t,this.id=i}setDeps(t){this.indexes=t.indexes,this.events=t.events,this.changes=t.changes,this.sync=t.sync,this.state=t.state}validateStatusTransition(t,i){if(t===i)return;if(!{idle:[`loading`,`error`,`cleaned-up`],loading:[`ready`,`error`,`cleaned-up`],ready:[`cleaned-up`,`error`],error:[`cleaned-up`,`idle`],"cleaned-up":[`loading`,`error`]}[t].includes(i))throw new MC(t,i,this.id)}setStatus(t,i=!1){if(t===`ready`&&!i)throw new Cl(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,t);const r=this.status;this.status=t,this.events.emitStatusChange(t,r)}validateCollectionUsable(t){switch(this.status){case`error`:throw new DC(t,this.id);case`cleaned-up`:this.sync.startSync();break}}markReady(){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`){if(this.setStatus(`ready`,!0),!this.hasBeenReady){this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0);const t=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],t.forEach(i=>i())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){const t=this.config.gcTime??3e5;t<=0||!Number.isFinite(t)||Hh.getInstance().schedule(this,t,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Hh.getInstance().cancel(this),this.idleCallbackId!==null&&(Ih(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Ih(this.idleCallbackId),this.idleCallbackId=MT(t=>{this.changes.activeSubscribersCount===0?this.performCleanup(t)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(t){if(!t||t.timeRemaining()>0||t.didTimeout){this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Hh.getInstance().cancel(this),this.hasBeenReady=!1;const r=[...this.onFirstReadyCallbacks];return this.onFirstReadyCallbacks=[],r.forEach(l=>{try{l()}catch(o){console.error(`${this.config.id?`[${this.config.id}] `:``}Error in onFirstReady callback during cleanup:`,o)}}),this.setStatus(`cleaned-up`),this.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(t){if(this.hasBeenReady){t();return}this.onFirstReadyCallbacks.push(t)}cleanup(){this.idleCallbackId!==null&&(Ih(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const rp=Symbol(`liveQueryInternal`);class UT{constructor(t,i){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.config=t,this.id=i,this.syncMode=t.syncMode??`eager`}setDeps(t){this.collection=t.collection,this.state=t.state,this.lifecycle=t.lifecycle,this._events=t.events}startSync(){if(!(this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`)){this.lifecycle.setStatus(`loading`);try{const t=zT(this.config.sync.sync({collection:this.collection,begin:i=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:i?.immediate})},write:i=>{const r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!r)throw new Dh;if(r.committed)throw new Mh;let l;`key`in i?l=i.key:l=this.config.getKey(i.value),this.state.pendingLocalChanges.has(l)&&this.state.pendingLocalOrigins.add(l);let o=i.type;if(i.type===`insert`){const d=this.state.syncedData.has(l),p=r.deletedKeys.has(l),g=r.truncate===!0;if(d&&!p&&!g){const y=this.state.syncedData.get(l);if(y!==void 0&&Bn(y,i.value))o=`update`;else{const w=this.config.utils[rp];throw new BC(l,this.id,{hasCustomGetKey:w?.hasCustomGetKey??!1,hasJoins:w?.hasJoins??!1,hasDistinct:w?.hasDistinct??!1})}}}const u={...i,type:o,key:l};r.operations.push(u),o===`delete`?(r.deletedKeys.add(l),r.rowMetadataWrites.set(l,{type:`delete`})):o===`insert`?u.metadata!==void 0?r.rowMetadataWrites.set(l,{type:`set`,value:u.metadata}):r.rowMetadataWrites.set(l,{type:`delete`}):u.metadata!==void 0&&r.rowMetadataWrites.set(l,{type:`set`,value:u.metadata})},commit:()=>{const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!i)throw new WC;if(i.committed)throw new PC;i.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!i)throw new Dh;if(i.committed)throw new Mh;i.operations=[],i.deletedKeys.clear(),i.rowMetadataWrites.clear(),i.truncate=!0,i.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi()}));if(this.syncCleanupFn=t?.cleanup??null,this.syncLoadSubsetFn=t?.loadSubset??null,this.syncUnloadSubsetFn=t?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new Ai(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(t){throw this.lifecycle.setStatus(`error`),t}}}getActivePendingSyncTransaction(){const t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new Dh;if(t.committed)throw new Mh;return t}createSyncMetadataApi(){return{row:{get:t=>{const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],r=i?.rowMetadataWrites.get(t);if(r)return r.type===`delete`?void 0:r.value;if(!i?.truncate)return this.state.syncedMetadata.get(t)},set:(t,i)=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:`set`,value:i})},delete:t=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:`delete`})}},collection:{get:t=>{const r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(t);return r?r.type===`delete`?void 0:r.value:this.state.syncedCollectionMetadata.get(t)},set:(t,i)=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:`set`,value:i})},delete:t=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:`delete`})},list:t=>{const i=new Map(this.state.syncedCollectionMetadata),r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(r)for(const[l,o]of r.collectionMetadataWrites)o.type===`delete`?i.delete(l):i.set(l,o.value);return Array.from(i.entries()).filter(([l])=>t?l.startsWith(t):!0).map(([l,o])=>({key:l,value:o}))}}}}preload(){return this.preloadPromise?this.preloadPromise:(this.syncMode===`on-demand`&&console.warn(`${this.id?`[${this.id}] `:``}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`),this.preloadPromise=new Promise((t,i)=>{if(this.lifecycle.status===`ready`){t();return}if(this.lifecycle.status===`error`){i(new kC);return}if(this.lifecycle.onFirstReady(()=>{t()}),this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`)try{this.startSync()}catch(r){i(r);return}}),this.preloadPromise)}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(t){const i=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(t),i&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:`start`}),t.finally(()=>{const r=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(t);this.pendingLoadSubsetPromises.delete(t),r&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:`end`})})}loadSubset(t){if(this.syncMode===`eager`)return!0;if(this.syncLoadSubsetFn){const i=this.syncLoadSubsetFn(t);if(i instanceof Promise)return this.trackLoadPromise(i),i}return!0}unloadSubset(t){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(t)}cleanup(){try{this.syncCleanupFn&&(this.syncCleanupFn(),this.syncCleanupFn=null)}catch(t){queueMicrotask(()=>{if(t instanceof Error){const i=new nS(this.id,t);throw i.cause=t,i.stack=t.stack,i}else throw new nS(this.id,t)})}this.preloadPromise=null}}function zT(n){if(typeof n==`function`)return{cleanup:n};if(typeof n==`object`)return n}const wS=1;function cc(n,t){return n===t?0:nGs(r)??null);if(n instanceof Date)return{__type:`date`,value:n.toISOString()};if(n instanceof Set)return{__type:`set`,values:Array.from(n).map(l=>Gs(l)??null).sort((l,o)=>cc(bi(l),bi(o)))};if(n instanceof Map)return{__type:`map`,entries:Array.from(n.entries()).map(([l,o])=>({key:Gs(l)??null,value:Gs(o)??null})).sort((l,o)=>cc(bi(l.key),bi(o.key)))};if(n instanceof RegExp)return{__type:`regexp`,value:n.toString()};const t={},i=Object.entries(n).sort(([r],[l])=>cc(r,l));for(const[r,l]of i){const o=Gs(l);o!==void 0&&(t[r]=o)}return t}function bi(n){return n===null?`null`:Array.isArray(n)?`[${n.map(bi).join(`,`)}]`:typeof n!=`object`?JSON.stringify(n):`{${Object.keys(n).sort((r,l)=>cc(r,l)).map(r=>`${JSON.stringify(r)}:${bi(n[r])}`).join(`,`)}}`}function jT(n,t,i,r,l){const o=NT(r),u=Gs(t)??null,d=Gs(l),g=Gs({signatureVersion:wS,expression:u,options:d??null})??null,y=bi(g);return{signatureVersion:wS,signature:y,indexId:n,name:i,expression:t,resolver:o,...d===void 0?{}:{options:d}}}function xd(n){if(n===null||typeof n!=`object`)return n;if(Array.isArray(n))return n.map(i=>xd(i));const t={};for(const[i,r]of Object.entries(n))t[i]=xd(r);return t}function BT(n){return JSON.parse(JSON.stringify(n))}class LT{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(t){this.state=t.state,this.lifecycle=t.lifecycle,this.defaultIndexType=t.defaultIndexType,this.events=t.events}createIndex(t,i={}){this.lifecycle.validateCollectionUsable(`createIndex`);const r=++this.indexCounter,l=Jv(),o=t(l),u=ne(o),d=i.indexType??this.defaultIndexType;if(!d)throw new Ai(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
+ import { BasicIndex } from '@tanstack/db'
+ createCollection({ defaultIndexType: BasicIndex, ... })`);const p=new d(r,u,i.name,i.options);p.build(this.state.entries()),this.indexes.set(r,p);const g=jT(r,u,i.name,d,i.options);return this.indexMetadata.set(r,g),this.events.emitIndexAdded(g),p}removeIndex(t){this.lifecycle.validateCollectionUsable(`removeIndex`);const i=typeof t==`number`?t:t.id,r=this.indexes.get(i);if(!r||typeof t!=`number`&&r!==t)return!1;this.indexes.delete(i);const l=this.indexMetadata.get(i);return this.indexMetadata.delete(i),l&&this.events.emitIndexRemoved(l),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((t,i)=>t.indexId-i.indexId).map(t=>({...t,expression:BT(t.expression),resolver:{...t.resolver},...t.options===void 0?{}:{options:xd(t.options)}}))}updateIndexes(t){for(const i of this.indexes.values())for(const r of t)switch(r.type){case`insert`:i.add(r.key,r.value);break;case`update`:r.previousValue?i.update(r.key,r.previousValue,r.value):i.add(r.key,r.value);break;case`delete`:i.remove(r.key,r.value);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}}var IT={};const HT=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),qT=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),KT=new Set([`set`,`delete`,`clear`,`add`]),VT=new Set([`entries`,`keys`,`values`,`forEach`]);function ap(n){return n!==null&&typeof n==`object`&&!(n instanceof Date)&&!(n instanceof RegExp)&&!Xs(n)}function $T(n,t,i,r){if(HT.has(n))return function(...l){const o=l[0];if(typeof o!=`function`)return t.apply(i.copy_,l);const u=(g,y)=>{if(ap(g)){const m={tracker:i,prop:String(y)},{proxy:v}=r(g,m);return v}return g},d=function(g,y,m){const v=u(g,y);return o.call(this,v,y,m)};if(n===`reduce`||n===`reduceRight`){const g=function(y,m,v,w){const b=u(m,v);return o.call(this,y,b,v,w)};return t.apply(i.copy_,[g,...l.slice(1)])}const p=t.apply(i.copy_,[d,...l.slice(1)]);if((n===`find`||n===`findLast`)&&p&&typeof p==`object`){const g=i.copy_.indexOf(p);if(g!==-1)return u(p,g)}return n===`filter`&&Array.isArray(p)?p.map(g=>{const y=i.copy_.indexOf(g);return y!==-1?u(g,y):g}):p}}function GT(n,t){return function(){const i=n.copy_;let r=0;return{next(){if(r>=i.length)return{done:!0,value:void 0};const l=i[r];let o=l;if(ap(l)){const u={tracker:n,prop:String(r)},{proxy:d}=t(l,u);o=d}return r++,{done:!1,value:o}},[Symbol.iterator](){return this}}}}function ES(n,t,i){return function(...r){const l=n.apply(t.copy_,r);return i(t),l}}function YT(n,t,i,r,l,o,u){if(VT.has(n)||t===Symbol.iterator)return function(...p){const g=i.apply(l.copy_,p);if(n===`forEach`){const m=p[0];if(typeof m==`function`){const v=function(w,b,E){const _=m.call(this,w,b,E);return u(l),_};return i.apply(r,[v,...p.slice(1)])}}if(n===`entries`||n===`values`||n===Symbol.iterator.toString()||t===Symbol.iterator){const m=g,v=new Map;if(n===`values`&&r instanceof Map)for(const[b,E]of l.copy_.entries())v.set(E,b);const w=new Map;if(r instanceof Set)for(const b of l.copy_.values())w.set(b,b);return{next(){const b=m.next();if(!b.done&&b.value&&typeof b.value==`object`){if(n===`entries`&&Array.isArray(b.value)&&b.value.length===2){if(b.value[1]&&typeof b.value[1]==`object`){const E=b.value[0],_={tracker:l,prop:E,updateMap:O=>{l.copy_ instanceof Map&&l.copy_.set(E,O)}},{proxy:j}=o(b.value[1],_);b.value[1]=j}}else if(n===`values`||n===Symbol.iterator.toString()||t===Symbol.iterator)if(n===`values`&&r instanceof Map){const E=v.get(b.value);if(E!==void 0){const _={tracker:l,prop:E,updateMap:O=>{l.copy_ instanceof Map&&l.copy_.set(E,O)}},{proxy:j}=o(b.value,_);b.value=j}}else if(r instanceof Set){const E=b.value,_={tracker:l,prop:E,updateSet:O=>{l.copy_ instanceof Set&&(l.copy_.delete(E),l.copy_.add(O),w.set(E,O))}},{proxy:j}=o(b.value,_);b.value=j}else{const E=Symbol(`iterator-value`),{proxy:_}=o(b.value,{tracker:l,prop:E});b.value=_}}return b},[Symbol.iterator](){return this}}}return g}}function Tt(...n){const t=typeof window<`u`&&typeof localStorage<`u`;t&&localStorage.getItem(`DEBUG`)===`true`?console.log(`[proxy]`,...n):!t&&typeof process<`u`&&IT.DEBUG===`true`&&console.log(`[proxy]`,...n)}function ds(n,t=new WeakMap){if(n==null||typeof n!=`object`)return n;if(t.has(n))return t.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(Array.isArray(n)){const l=[];return t.set(n,l),n.forEach((o,u)=>{l[u]=ds(o,t)}),l}if(ArrayBuffer.isView(n)&&!(n instanceof DataView)){const l=Object.getPrototypeOf(n).constructor,o=new l(n.length);t.set(n,o);for(let u=0;u{l.set(u,ds(o,t))}),l}if(n instanceof Set){const l=new Set;return t.set(n,l),n.forEach(o=>{l.add(ds(o,t))}),l}if(Xs(n))return n;const i={};t.set(n,i);for(const l in n)Object.prototype.hasOwnProperty.call(n,l)&&(i[l]=ds(n[l],t));const r=Object.getOwnPropertySymbols(n);for(const l of r)i[l]=ds(n[l],t);return i}let CS=0;function FT(){return CS+=1,CS}function lp(n,t){const i=new Map;function r(m,v){if(Tt(`Object ID:`,m.constructor.name),i.has(m))return i.get(m);{const w=lp(m,v);return i.set(m,w),w}}const l=new Map,o={copy_:ds(n),originalObject:ds(n),proxyCount:FT(),modified:!1,assigned_:{},parent:t,target:n};Tt(`createChangeProxy called for target`,n,o.proxyCount);function u(m){m.modified||(m.modified=!0),m.parent&&(Tt(`propagating change to parent`),`updateMap`in m.parent?m.parent.updateMap(m.copy_):`updateSet`in m.parent?m.parent.updateSet(m.copy_):(m.parent.tracker.copy_[m.parent.prop]=m.copy_,m.parent.tracker.assigned_[m.parent.prop]=!0),u(m.parent.tracker))}function d(m){if(Tt(`checkIfReverted called with assigned keys:`,Object.keys(m.assigned_)),Object.keys(m.assigned_).length===0&&Object.getOwnPropertySymbols(m.assigned_).length===0)return Tt(`No assigned properties, returning true`),!0;for(const w in m.assigned_)if(m.assigned_[w]===!0){const b=m.copy_[w],E=m.originalObject[w];if(Tt(`Checking property ${String(w)}, current:`,b,`original:`,E),!Bn(b,E))return Tt(`Property ${String(w)} is different, returning false`),!1}else if(m.assigned_[w]===!1)return Tt(`Property ${String(w)} was deleted, returning false`),!1;const v=Object.getOwnPropertySymbols(m.assigned_);for(const w of v)if(m.assigned_[w]===!0){const b=m.copy_[w],E=m.originalObject[w];if(!Bn(b,E))return Tt(`Symbol property is different, returning false`),!1}else if(m.assigned_[w]===!1)return Tt(`Symbol property was deleted, returning false`),!1;return Tt(`All properties match original values, returning true`),!0}function p(m,v){Tt(`checkParentStatus called for child prop:`,v);const w=d(m);Tt(`Parent checkIfReverted returned:`,w),w&&(Tt(`Parent is fully reverted, clearing tracking`),m.modified=!1,m.assigned_={},m.parent&&(Tt(`Continuing up the parent chain`),p(m.parent.tracker,m.parent.prop)))}function g(m){if(Tt(`createObjectProxy`,m),l.has(m))return Tt(`proxyCache found match`),l.get(m);const v=new Proxy(m,{get(w,b){Tt(`get`,w,b);const E=o.copy_[b]??o.originalObject[b],_=o.originalObject[b];if(Tt(`value (at top of proxy get)`,E),Object.getOwnPropertyDescriptor(w,b)?.get)return E;if(typeof E==`function`){if(Array.isArray(w)){const O=b.toString();if(qT.has(O))return ES(E,o,u);const A=$T(O,E,o,r);if(A)return A;if(b===Symbol.iterator)return GT(o,r)}if(w instanceof Map||w instanceof Set){const O=b.toString();if(KT.has(O))return ES(E,o,u);const A=YT(O,b,E,w,o,r,u);if(A)return A}return E.bind(w)}if(ap(E)){const O={tracker:o,prop:String(b)},{proxy:A}=r(_,O);return l.set(E,A),A}return E},set(w,b,E){const _=o.copy_[b];if(Tt(`set called for property ${String(b)}, current:`,_,`new:`,E),Bn(_,E))Tt(`Value unchanged, not tracking`);else{const j=o.originalObject[b],O=Bn(E,j);if(Tt(`value:`,E,`original:`,j,`isRevertToOriginal:`,O),O){Tt(`Reverting property ${String(b)} to original value`),delete o.assigned_[b.toString()],Tt(`Updating copy with original value for ${String(b)}`),o.copy_[b]=ds(j),Tt(`Checking if all properties reverted`);const A=d(o);Tt(`All reverted:`,A),A?(Tt(`All properties reverted, clearing tracking`),o.modified=!1,o.assigned_={},t&&(Tt(`Updating parent for property:`,t.prop),p(t.tracker,t.prop))):(Tt(`Some properties still changed, keeping modified flag`),o.modified=!0)}else Tt(`Setting new value for property ${String(b)}`),o.copy_[b]=E,o.assigned_[b.toString()]=!0,Tt(`Marking object and ancestors as modified`,o),u(o)}return!0},defineProperty(w,b,E){const _=Reflect.defineProperty(w,b,E);return _&&`value`in E&&(o.copy_[b]=ds(E.value),o.assigned_[b.toString()]=!0,u(o)),_},getOwnPropertyDescriptor(w,b){return Reflect.getOwnPropertyDescriptor(w,b)},preventExtensions(w){return Reflect.preventExtensions(w)},isExtensible(w){return Reflect.isExtensible(w)},deleteProperty(w,b){Tt(`deleteProperty`,w,b);const E=typeof b==`symbol`?b.toString():b;if(E in w){const _=E in o.originalObject,j=Reflect.deleteProperty(w,b);return j&&(_?(o.assigned_[E]=!1,u(o)):(delete o.assigned_[E],Object.keys(o.assigned_).length===0&&Object.getOwnPropertySymbols(o.assigned_).length===0?o.modified=!1:o.modified=!0)),j}return!0}});return l.set(m,v),v}return{proxy:g(o.copy_),getChanges:()=>{if(Tt(`getChanges called, modified:`,o.modified),Tt(o),!o.modified)return Tt(`Object not modified, returning empty object`),{};if(typeof o.copy_!=`object`||Array.isArray(o.copy_)||Object.keys(o.assigned_).length===0)return o.copy_;const m={};for(const v in o.copy_)o.assigned_[v]===!0&&v in o.copy_&&(m[v]=o.copy_[v]);return Tt(`Returning copy:`,m),m}}}function QT(n){const t=n.map(i=>lp(i));return{proxies:t.map(i=>i.proxy),getChanges:()=>t.map(i=>i.getChanges())}}function XT(n,t){const{proxy:i,getChanges:r}=lp(n);return t(i),r()}function JT(n,t){const{proxies:i,getChanges:r}=QT(n);return t(i),r()}function ZT(){let n,t,i=!0;return{promise:new Promise((l,o)=>{n=u=>{i=!1,l(u)},t=u=>{i=!1,o(u)}}),resolve:n,reject:t,isPending:()=>i}}function WT(n){return typeof n==`object`&&n!==null&&typeof n.hasPendingGraphRun==`function`}class PT{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(t){let i=this.contexts.get(t);return i||(i={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(t,i)),i}schedule({contextId:t,jobId:i,dependencies:r,run:l}){if(typeof t>`u`){l();return}const o=this.getOrCreateContext(t);if(o.jobs.has(i)||o.queue.push(i),o.jobs.set(i,l),r){const u=new Set(r);u.delete(i),o.dependencies.set(i,u)}else o.dependencies.has(i)||o.dependencies.set(i,new Set);o.completed.delete(i)}flush(t){const i=this.contexts.get(t);if(!i)return;const{queue:r,jobs:l,dependencies:o,completed:u}=i;for(;r.length>0;){let d=!1;const p=r.length;for(let g=0;gi(t))}onClear(t){return this.clearListeners.add(t),()=>this.clearListeners.delete(t)}hasPendingJobs(t){const i=this.contexts.get(t);return!!i&&i.jobs.size>0}clearJob(t,i){const r=this.contexts.get(t);r&&(r.jobs.delete(i),r.dependencies.delete(i),r.completed.delete(i),r.queue=r.queue.filter(l=>l!==i),r.jobs.size===0&&this.contexts.delete(t))}}const xc=new PT,_c=[];let fl=[],tA=0;function eA(n,t){switch(`${n.type}-${t.type}`){case`insert-update`:return{...n,type:`insert`,original:{},modified:t.modified,changes:{...n.changes,...t.changes},key:n.key,globalKey:n.globalKey,metadata:t.metadata??n.metadata,syncMetadata:{...n.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt};case`insert-delete`:return null;case`update-delete`:return t;case`update-update`:return{...t,original:n.original,changes:{...n.changes,...t.changes},metadata:t.metadata??n.metadata,syncMetadata:{...n.syncMetadata,...t.syncMetadata}};case`delete-delete`:case`insert-insert`:return t;default:{const i=`${n.type}-${t.type}`;throw new Error(`Unhandled mutation combination: ${i}`)}}}function Za(n){const t=new rA(n);return _c.push(t),t}function uc(){if(fl.length>0)return fl.slice(-1)[0]}function nA(n){xc.clear(n.id),fl.push(n)}function sA(n){try{xc.flush(n.id)}finally{fl=fl.filter(t=>t.id!==n.id)}}function iA(n){const t=_c.findIndex(i=>i.id===n.id);t!==-1&&_c.splice(t,1)}let rA=class{constructor(t){if(typeof t.mutationFn>`u`)throw new FC;this.id=t.id??crypto.randomUUID(),this.mutationFn=t.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=ZT(),this.autoCommit=t.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=tA++,this.metadata=t.metadata??{}}setState(t){this.state=t,(t===`completed`||t===`failed`)&&iA(this)}mutate(t){if(this.state!==`pending`)throw new XC;nA(this);try{t()}finally{sA(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(t){for(const i of t){const r=this.mutations.findIndex(l=>l.globalKey===i.globalKey);if(r>=0){const l=this.mutations[r],o=eA(l,i);o===null?this.mutations.splice(r,1):this.mutations[r]=o}else this.mutations.push(i)}}rollback(t){const i=t?.isSecondaryRollback??!1;if(this.state===`completed`)throw new JC;if(this.setState(`failed`),!i){const r=new Set;this.mutations.forEach(l=>r.add(l.globalKey));for(const l of _c)l.state===`pending`&&l.mutations.some(o=>r.has(o.globalKey))&&l.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){const t=new Set;for(const i of this.mutations)t.has(i.collection.id)||(i.collection._state.onTransactionStateChange(),i.collection._state.pendingSyncedTransactions.length>0&&i.collection._state.commitPendingTransactions(),t.add(i.collection.id))}async commit(){if(this.state!==`pending`)throw new ZC;if(this.setState(`persisting`),this.mutations.length===0)return this.setState(`completed`),this.isPersisted.resolve(this),this;try{await this.mutationFn({transaction:this}),this.setState(`completed`),this.touchCollection(),this.isPersisted.resolve(this)}catch(t){const i=t instanceof Error?t:new Error(String(t));throw this.error={message:i.message,error:i},this.rollback(),i}return this}compareCreatedAt(t){const i=this.createdAt.getTime()-t.createdAt.getTime();return i!==0?i:this.sequenceNumber-t.sequenceNumber}};class aA{constructor(t,i){this.insert=(r,l)=>{this.lifecycle.validateCollectionUsable(`insert`);const o=this.state,u=uc();if(!u&&!this.config.onInsert)throw new $C;const d=Array.isArray(r)?r:[r],p=[],g=new Set;if(d.forEach(y=>{const m=this.validateData(y,`insert`),v=this.config.getKey(m);if(this.state.has(v)||g.has(v))throw new jC(v);g.add(v);const w=this.generateGlobalKey(v,y),b={mutationId:crypto.randomUUID(),original:{},modified:m,changes:Object.fromEntries(Object.keys(y).map(E=>[E,m[E]])),globalKey:w,key:v,metadata:l?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:l?.optimistic??!0,type:`insert`,createdAt:new Date,updatedAt:new Date,collection:this.collection};p.push(b)}),u)return u.applyMutations(p),o.transactions.set(u.id,u),o.scheduleTransactionCleanup(u),o.recomputeOptimisticState(!0),u;{const y=Za({metadata:{[lc]:!0},mutationFn:async m=>await this.config.onInsert({transaction:m.transaction,collection:this.collection})});return y.applyMutations(p),this.markPendingLocalOrigins(p),y.commit().catch(()=>{}),o.transactions.set(y.id,y),o.scheduleTransactionCleanup(y),o.recomputeOptimisticState(!0),y}},this.delete=(r,l)=>{const o=this.state;this.lifecycle.validateCollectionUsable(`delete`);const u=uc();if(!u&&!this.config.onDelete)throw new YC;if(Array.isArray(r)&&r.length===0)throw new KC;const d=Array.isArray(r)?r:[r],p=[];for(const y of d){if(!this.state.has(y))throw new VC(y);const m=this.generateGlobalKey(y,this.state.get(y)),v={mutationId:crypto.randomUUID(),original:this.state.get(y),modified:this.state.get(y),changes:this.state.get(y),globalKey:m,key:y,metadata:l?.metadata,syncMetadata:o.syncedMetadata.get(y)||{},optimistic:l?.optimistic??!0,type:`delete`,createdAt:new Date,updatedAt:new Date,collection:this.collection};p.push(v)}if(u)return u.applyMutations(p),o.transactions.set(u.id,u),o.scheduleTransactionCleanup(u),o.recomputeOptimisticState(!0),u;const g=Za({autoCommit:!0,metadata:{[lc]:!0},mutationFn:async y=>this.config.onDelete({transaction:y.transaction,collection:this.collection})});return g.applyMutations(p),this.markPendingLocalOrigins(p),g.commit().catch(()=>{}),o.transactions.set(g.id,g),o.scheduleTransactionCleanup(g),o.recomputeOptimisticState(!0),g},this.id=i,this.config=t}setDeps(t){this.lifecycle=t.lifecycle,this.state=t.state,this.collection=t.collection}ensureStandardSchema(t){if(t&&`~standard`in t)return t;throw new RC}validateData(t,i,r){if(!this.config.schema)return t;const l=this.ensureStandardSchema(this.config.schema);if(i===`update`&&r){const u=this.state.get(r);if(u&&t&&typeof t==`object`&&typeof u==`object`){const d=Object.assign({},u,t),p=l[`~standard`].validate(d);if(p instanceof Promise)throw new P0;if(`issues`in p&&p.issues){const v=p.issues.map(w=>({message:w.message,path:w.path?.map(b=>String(b))}));throw new W0(i,v)}const g=p.value,y=Object.keys(t);return Object.fromEntries(y.map(v=>[v,g[v]]))}}const o=l[`~standard`].validate(t);if(o instanceof Promise)throw new P0;if(`issues`in o&&o.issues){const u=o.issues.map(d=>({message:d.message,path:d.path?.map(p=>String(p))}));throw new W0(i,u)}return o.value}generateGlobalKey(t,i){if(typeof t!=`string`&&typeof t!=`number`)throw typeof t>`u`?new zC(i):new NC(t,i);return`KEY::${this.id}/${t}`}markPendingLocalOrigins(t){for(const i of t)this.state.pendingLocalOrigins.add(i.key)}update(t,i,r){if(typeof t>`u`)throw new LC;const l=this.state;this.lifecycle.validateCollectionUsable(`update`);const o=uc();if(!o&&!this.config.onUpdate)throw new GC;const u=Array.isArray(t),d=u?t:[t];if(u&&d.length===0)throw new IC;const p=typeof i==`function`?i:r,g=typeof i==`function`?{}:i,y=d.map(b=>{const E=this.state.get(b);if(!E)throw new HC(b);return E});let m;u?m=JT(y,p):m=[XT(y[0],p)];const v=d.map((b,E)=>{const _=m[E];if(!_||Object.keys(_).length===0)return null;const j=y[E],O=this.validateData(_,`update`,b),A=Object.assign({},j,O),M=this.config.getKey(j),G=this.config.getKey(A);if(M!==G)throw new qC(M,G);const q=this.generateGlobalKey(G,A);return{mutationId:crypto.randomUUID(),original:j,modified:A,changes:Object.fromEntries(Object.keys(_).map(K=>[K,A[K]])),globalKey:q,key:b,metadata:g.metadata,syncMetadata:l.syncedMetadata.get(b)||{},optimistic:g.optimistic??!0,type:`update`,createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(v.length===0){const b=Za({mutationFn:async()=>{}});return b.commit().catch(()=>{}),l.scheduleTransactionCleanup(b),b}if(o)return o.applyMutations(v),l.transactions.set(o.id,o),l.scheduleTransactionCleanup(o),l.recomputeOptimisticState(!0),o;const w=Za({metadata:{[lc]:!0},mutationFn:async b=>this.config.onUpdate({transaction:b.transaction,collection:this.collection})});return w.applyMutations(v),this.markPendingLocalOrigins(v),w.commit().catch(()=>{}),l.transactions.set(w.id,w),l.scheduleTransactionCleanup(w),l.recomputeOptimisticState(!0),w}}class lA extends Zv{constructor(){super()}setDeps(t){this.collection=t.collection}emit(t,i){this.emitInner(t,i)}emitStatusChange(t,i){this.emit(`status:change`,{type:`status:change`,collection:this.collection,previousStatus:i,status:t});const r=`status:${t}`;this.emit(r,{type:r,collection:this.collection,previousStatus:i,status:t})}emitSubscribersChange(t,i){this.emit(`subscribers:change`,{type:`subscribers:change`,collection:this.collection,previousSubscriberCount:i,subscriberCount:t})}emitIndexAdded(t){this.emit(`index:added`,{type:`index:added`,collection:this.collection,index:t})}emitIndexRemoved(t){this.emit(`index:removed`,{type:`index:removed`,collection:this.collection,index:t})}cleanup(){this.clearListeners()}}function op(n){const t=new cp(n);return n.utils?t.utils=n.utils:t.utils={},t}class cp{constructor(t){if(this.utils={},this.deferDataRefresh=null,this.insert=(i,r)=>this._mutations.insert(i,r),this.delete=(i,r)=>this._mutations.delete(i,r),!t)throw new AC;if(!t.sync)throw new OC;if(t.id?this.id=t.id:this.id=crypto.randomUUID(),this.config={...t,autoIndex:t.autoIndex??`off`},this.config.autoIndex===`eager`&&!t.defaultIndexType)throw new Ai(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
+ import { BasicIndex } from '@tanstack/db'
+ createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);this._changes=new OT,this._events=new lA,this._indexes=new LT,this._lifecycle=new kT(t,this.id),this._mutations=new aA(t,this.id),this._state=new bT(t),this._sync=new UT(t,this.id),this.comparisonOpts=oA(t),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:t.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),t.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}onFirstReady(t){return this._lifecycle.onFirstReady(t)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}preload(){return this._sync.preload()}get(t){return this._state.getWithVirtualProps(t)}has(t){return this._state.has(t)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(const t of this._state.keys()){const i=this.get(t);i!==void 0&&(yield i)}}*entries(){for(const t of this._state.keys()){const i=this.get(t);i!==void 0&&(yield[t,i])}}*[Symbol.iterator](){yield*this.entries()}forEach(t){let i=0;for(const[r,l]of this.entries())t(l,r,i++)}map(t){const i=[];let r=0;for(const[l,o]of this.entries())i.push(t(o,l,r++));return i}getKeyFromItem(t){return this.config.getKey(t)}createIndex(t,i={}){return this._indexes.createIndex(t,i)}removeIndex(t){return this._indexes.removeIndex(t)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(t,i,r){return this._mutations.validateData(t,i,r)}get compareOptions(){return{...this.comparisonOpts}}update(t,i,r){return this._mutations.update(t,i,r)}get state(){const t=new Map;for(const[i,r]of this.entries())t.set(i,r);return t}stateWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(t={}){return mT(this,t)}subscribeChanges(t,i={}){return this._changes.subscribeChanges(t,i)}on(t,i){return this._events.on(t,i)}once(t,i){return this._events.once(t,i)}off(t,i){this._events.off(t,i)}waitFor(t,i){return this._events.waitFor(t,i)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}}function oA(n){if(n.defaultStringCollation){const t=n.defaultStringCollation;return{stringSort:t.stringSort??`locale`,locale:t.stringSort===`locale`?t.locale:void 0,localeOptions:t.stringSort===`locale`?t.localeOptions:void 0}}else return{stringSort:`locale`}}function cA(n){return!!n&&(typeof n==`object`||typeof n==`function`)&&typeof n.then==`function`}function uA(n){const{mutationFn:t,onMutate:i,...r}=n;return l=>{const o=Za({...r,mutationFn:async u=>await t(l,u)});return o.mutate(()=>{const u=i(l);if(cA(u))throw new QC}),o}}function fA(n){const t=hA(n);let i=n,r,l=0;const o=10;for(;leb(u)),l=nb(r),o=Pv(n);for(const[u,d]of l.singleSource)dA(n,u)&&!o.has(u)&&t.set(u,d);return t}function dA(n,t){if(n.from.alias===t)return n.from.type===`collectionRef`;if(n.join){for(const i of n.join)if(i.from.alias===t)return i.from.type===`collectionRef`}return!1}function Pv(n){const t=new Set;if(n.join){const i=n.from.alias;for(const r of n.join){const l=r.from.alias;(r.type===`left`||r.type===`full`)&&t.add(l),(r.type===`right`||r.type===`full`)&&t.add(i)}}return t}function _d(n){const t={...n,from:n.from.type===`queryRef`?new Sn(_d(n.from.query),n.from.alias):n.from,join:n.join?.map(i=>({...i,from:i.from.type===`queryRef`?new Sn(_d(i.from.query),i.from.alias):i.from}))};return pA(t)}function pA(n){if(!n.where||n.where.length===0)return n;if(!n.join||n.join.length===0){if(n.where.length>1){const d=Ad(n.where),p=Tc(d);return{...n,where:[p]}}return n}const t=n.where.filter(d=>!Z0(d)),r=Ad(t).map(d=>eb(d)),l=nb(r),o=yA(n,l),u=n.where.filter(d=>Z0(d));return u.length>0&&(o.where=[...o.where||[],...u]),o}function tb(n){return{...n,from:Td(n.from),join:n.join?.map(t=>({...t,from:Td(t.from)}))}}function Td(n){if(n.type===`collectionRef`)return n;const t=tb(n.query);if(gA(t)){const i=Td(t.from);return i.type===`collectionRef`?new jr(i.collection,n.alias):new Sn(i.query,n.alias)}return new Sn(t,n.alias)}function gA(n){return(!n.where||n.where.length===0)&&!n.select&&(!n.groupBy||n.groupBy.length===0)&&(!n.having||n.having.length===0)&&(!n.orderBy||n.orderBy.length===0)&&(!n.join||n.join.length===0)&&n.limit===void 0&&n.offset===void 0&&!n.fnSelect&&(!n.fnWhere||n.fnWhere.length===0)&&(!n.fnHaving||n.fnHaving.length===0)}function Ad(n){const t=[];for(const i of n){const r=Wd(i);t.push(...up(r))}return t}function up(n){if(n.type===`func`&&n.name===`and`){const t=[];for(const i of n.args)t.push(...up(i));return t}else return[n]}function eb(n){const t=new Set;let i=!1;function r(l){switch(l.type){case`ref`:if(l.path&&l.path.length>0){const o=l.path[0];o&&(t.add(o),l.path.length===1&&(i=!0))}break;case`func`:l.args&&l.args.forEach(r);break;case`val`:break;case`agg`:l.args&&l.args.forEach(r);break}}return r(n),{expression:n,touchedSources:t,hasNamespaceOnlyRef:i}}function nb(n){const t=new Map,i=[];for(const o of n)if(o.touchedSources.size===1&&!o.hasNamespaceOnlyRef){const u=Array.from(o.touchedSources)[0];t.has(u)||t.set(u,[]),t.get(u).push(o.expression)}else(o.touchedSources.size>1||o.hasNamespaceOnlyRef)&&i.push(o.expression);const r=new Map;for(const[o,u]of t)r.set(o,Tc(u));const l=i.length>0?Tc(i):void 0;return{singleSource:r,multiSource:l}}function yA(n,t){const i=new Set,r=Pv(n),l=new Map;for(const[m,v]of t.singleSource)r.has(m)||l.set(m,v);const o=xS(n.from,l,i),u=n.join?n.join.map(m=>({...m,from:xS(m.from,l,i)})):void 0,d=[];t.multiSource&&d.push(t.multiSource);const p=r.size>0;for(const[m,v]of t.singleSource)i.has(m)?p&&d.push(_C(v)):d.push(v);const g=d.length>1?[Tc(d.flatMap(m=>up(Wd(m))))]:d;return{select:n.select,groupBy:n.groupBy?[...n.groupBy]:void 0,having:n.having?[...n.having]:void 0,orderBy:n.orderBy?[...n.orderBy]:void 0,limit:n.limit,offset:n.offset,distinct:n.distinct,fnSelect:n.fnSelect,fnWhere:n.fnWhere?[...n.fnWhere]:void 0,fnHaving:n.fnHaving?[...n.fnHaving]:void 0,from:o,join:u,where:g.length>0?g:[]}}function Tr(n){return{from:n.from.type===`collectionRef`?new jr(n.from.collection,n.from.alias):new Sn(Tr(n.from.query),n.from.alias),select:n.select,join:n.join?n.join.map(t=>({type:t.type,left:t.left,right:t.right,from:t.from.type===`collectionRef`?new jr(t.from.collection,t.from.alias):new Sn(Tr(t.from.query),t.from.alias)})):void 0,where:n.where?[...n.where]:void 0,groupBy:n.groupBy?[...n.groupBy]:void 0,having:n.having?[...n.having]:void 0,orderBy:n.orderBy?[...n.orderBy]:void 0,limit:n.limit,offset:n.offset,fnSelect:n.fnSelect,fnWhere:n.fnWhere?[...n.fnWhere]:void 0,fnHaving:n.fnHaving?[...n.fnHaving]:void 0}}function xS(n,t,i){const r=t.get(n.alias);if(!r)return n.type===`collectionRef`?new jr(n.collection,n.alias):new Sn(Tr(n.query),n.alias);if(n.type===`collectionRef`){const u={from:new jr(n.collection,n.alias),where:[r]};return i.add(n.alias),new Sn(u,n.alias)}if(!EA(n.query,r,n.alias))return new Sn(Tr(n.query),n.alias);if(xA(n.query,r,n.alias))return new Sn(Tr(n.query),n.alias);const l=n.query.where||[],o={...Tr(n.query),where:[...l,r]};return i.add(n.alias),new Sn(o,n.alias)}function mA(n,t,i){return n.select?sb(n.select)||CA(n.select,t,i):!1}function SA(n){return n.groupBy&&n.groupBy.length>0}function vA(n){return n.having&&n.having.length>0}function bA(n){return n.orderBy&&n.orderBy.length>0&&(n.limit!==void 0||n.offset!==void 0)}function wA(n){return n.fnSelect||n.fnWhere&&n.fnWhere.length>0||n.fnHaving&&n.fnHaving.length>0}function EA(n,t,i){return!(mA(n,t,i)||SA(n)||vA(n)||bA(n)||wA(n))}function sb(n){for(const t of Object.values(n))if(typeof t==`object`){const i=t;if(i.type===`agg`||!(`type`in i)&&sb(i))return!0}return!1}function fp(n){const t=[];if(n==null||typeof n!=`object`)return t;switch(n.type){case`ref`:t.push(n);break;case`func`:case`agg`:for(const i of n.args??[])t.push(...fp(i));break}return t}function CA(n,t,i){const r=new Set;for(const[o,u]of Object.entries(n))o.startsWith(`__SPREAD_SENTINEL__`)||u instanceof Oe||r.add(o);const l=fp(t);for(const o of l){const u=o.path;if(!Array.isArray(u)||u.length<2)continue;const d=u[0],p=u[1];if(d===i&&r.has(p))return!0}return!1}function xA(n,t,i){const r=fp(t);if(r.every(o=>o.path[0]!==i))return!1;if(n.fnSelect)return!0;const l=n.select;if(!l)return!1;for(const o of r){const u=o.path;if(u.length<2||u[0]!==i)continue;const d=l[u[1]];if(!d)continue;if(!(d instanceof Oe)||d.path.length<2)return!0;const[p,g]=d.path;if(p!==i&&p!==n.from.alias||g!==u[1])return!0}return!1}function Tc(n){if(n.length===0)throw new Ax;return n.length===1?n[0]:new Ve(`and`,n)}function _A(n,t,i,r,l,o,u,d,p,g,y,m,v,w,b,E,_,j,O){let A=n;for(const M of t)A=TA(A,M,i,r,l,o,u,d,p,g,y,m,v,w,b,E,_,j,O);return A}function TA(n,t,i,r,l,o,u,d,p,g,y,m,v,w,b,E,_,j,O){const A=t.from.type===`collectionRef`,{alias:M,input:G,collectionId:q}=OA(t.from,o,p,g,y,m,v,w,u,d,E,_,j,O);i[M]=G,A&&(_[M]=q);const K=p[r],W=p[q];if(!K)throw new eS(r);if(!W)throw new eS(q);const{activeSource:et,lazySource:X}=DA(t.type,K,W),at=Object.keys(i),{mainExpr:nt,joinedExpr:bt}=AA(t.left,t.right,at,M),Lt=ue(nt),dt=ue(bt);let k=n.pipe(le(([Z,it])=>[xr(Lt(it)),[Z,it]])),I=G.pipe(le(([Z,it])=>{const ft={[M]:it};return[xr(dt(ft)),[Z,ft]]}));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new gx(t.type);if(et){const Z=et===`main`?t.from:b.from,it=Z.type===`queryRef`&&(Z.query.limit||Z.query.offset),ft=nt.type===`func`||bt.type===`func`;if(!it&&!ft){const T=et===`main`?M:l;m.add(T);const B=et===`main`?k:I,Q=ol(b,et===`main`?bt:nt,X),ot=Q.collection,st=Q.path[0];st&&$c(st,Q.path,ot);const mt=B.pipe(Z_(Ut=>{const wt=j[T]||T,an=g[wt];if(!an)throw new Ox(wt,T,X.id,Object.keys(g));if(an.hasLoadedInitialState())return;const $e=Ut.getInner().map(([[Te]])=>Te),Ps=new Oe(Q.path);an.requestSnapshot({where:CT(Ps,$e),optimizedOnly:!0})||an.requestSnapshot()}));et===`main`?k=mt:I=mt}}return k.pipe(Xv(I,t.type),RA(t.type))}function AA(n,t,i,r){const l=i.filter(d=>d!==r),o=Od(n),u=Od(t);if(o&&l.includes(o)&&u===r)return{mainExpr:n,joinedExpr:t};if(o===r&&u&&l.includes(u))return{mainExpr:t,joinedExpr:n};throw!o||!u?new mx:o===u?new yx(o):l.includes(o)?u!==r?new vx(r):new bx:new Sx(o)}function Od(n){switch(n.type){case`ref`:return n.path[0]||null;case`func`:{const t=new Set;for(const i of n.args){const r=Od(i);r&&t.add(r)}return t.size===1?Array.from(t)[0]:null}default:return null}}function OA(n,t,i,r,l,o,u,d,p,g,y,m,v,w){switch(n.type){case`collectionRef`:{const b=t[n.alias];if(!b)throw new Nv(n.alias,n.collection.id,Object.keys(t));return m[n.alias]=n.collection.id,{alias:n.alias,input:b,collectionId:n.collection.id}}case`queryRef`:{const b=g.get(n.query)||n.query,E=y(b,t,i,r,l,o,u,d,p,g);Object.assign(m,E.aliasToCollectionId),Object.assign(v,E.aliasRemapping);const _=g.has(n.query),j=n.query.from.alias;if(!(!_&&n.alias===j))for(const[q,K]of E.sourceWhereClauses)w.set(q,K);const A=Object.keys(E.aliasToCollectionId).find(q=>E.aliasToCollectionId[q]===E.collectionId);A&&A!==n.alias&&(v[n.alias]=A);const G=E.pipeline.pipe(le(q=>{const[K,[W,et]]=q;return[K,W]}));return{alias:n.alias,input:G,collectionId:E.collectionId}}default:throw new wx(n.type)}}function RA(n){return function(t){return t.pipe(ps(i=>{const[r,[l,o]]=i,u=l?.[1],d=o?.[1];return n===`inner`?!!(u&&d):n===`left`?!!u:n===`right`?!!d:!0}),le(i=>{const[r,[l,o]]=i,u=l?.[0],d=l?.[1],p=o?.[0],g=o?.[1],y={};return d&&Object.assign(y,d),g&&Object.assign(y,g),[`[${u},${p}]`,y]}))}}function DA(n,t,i){switch(n){case`left`:return{activeSource:`main`,lazySource:i};case`right`:return{activeSource:`joined`,lazySource:t};case`inner`:return t.sizeUA(l,r)))}function NA(n){return n.type===`agg`}function jA(n){return n&&typeof n==`object`&&!Br(n)}function ib(n,t,i){for(const[r,l]of Object.entries(t)){if(r.startsWith(`__SPREAD_SENTINEL__`)){const u=r.slice(19),d=u.lastIndexOf(`__`),p=d>=0?u.slice(0,d):u,g=l&&typeof l==`object`&&`type`in l&&l.type===`ref`;if(p.includes(`.`)||g){const y=[...n],m=g?l:new Oe(p.split(`.`)),v=ue(m);i.push({kind:`merge`,targetPath:y,source:v})}else{const y=p,m=[...n];i.push({kind:`merge`,targetPath:m,source:v=>v[y]})}continue}const o=l;if(o&&o.type===`includesSubquery`){i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>null});continue}if(jA(o)){ib([...n,r],o,i);continue}if(NA(o)||Lr(o))i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>null});else{if(o===void 0||!Br(o)){i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>o});continue}if(o instanceof Ue){const u=o.value;i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>u})}else i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:ue(o)})}}}const Or=Symbol(`includesRouting`);function Ac(n,t,i,r,l,o,u,d,p=new WeakMap,g=new WeakMap,y,m){const v=p.get(n);if(v)return v;Dd(n);const{optimizedQuery:w,sourceWhereClauses:b}=fA(n);let E=w;g.set(E,n),kd(E,n,g);const _={...t},j={},O={},A={},{alias:M,input:G,collectionId:q}=LA(E.from,_,i,r,l,o,u,d,p,g,j,O,b);A[M]=G;let K=G;if(y&&m){const dt=m.path.slice(1);K=G.pipe(le(([Z,it])=>[KA(it,dt),[Z,it]])).pipe(Xv(y,`inner`)).pipe(ps(([Z,[it]])=>it!=null),le(([Z,[it,ft]])=>{const[T,B]=it,Y={...B,__correlationKey:Z};return ft!=null&&(Y.__parentContext=ft),[ft!=null?`${String(T)}::${JSON.stringify(ft)}`:T,Y]})),A[M]=K}let W=K.pipe(le(([dt,k])=>{const{__parentContext:I,...Z}=k,it={[M]:Z};return I&&(Object.assign(it,I),it.__parentContext=I),[dt,it]}));if(E.join&&E.join.length>0&&(W=_A(W,E.join,A,q,M,_,p,g,i,r,l,o,u,d,n,Ac,j,O,b)),E.where&&E.where.length>0)for(const dt of E.where){const k=Wd(dt),I=ue(k);W=W.pipe(ps(([Z,it])=>Ar(I(it))))}if(E.fnWhere&&E.fnWhere.length>0)for(const dt of E.fnWhere)W=W.pipe(ps(([k,I])=>Ar(dt(I))));const et=[],X=[];if(E.select){const dt=HA(E.select);dt.length>0&&(E={...E,select:{...E.select}});for(const{key:k,subquery:I}of dt){const Z=ue(I.correlationField);let it;if(I.parentProjection&&I.parentProjection.length>0){const B=I.parentProjection.map(Y=>({alias:Y.path[0],field:Y.path.slice(1),compiled:ue(Y)}));it=W.pipe(le(([Y,Q])=>{const ot={};for(const st of B){ot[st.alias]||(ot[st.alias]={});const mt=st.compiled(Q);let Ut=ot[st.alias];for(let wt=0;wt[Z(Y),null]));it=it.pipe($v(B=>B.map(([Y,Q])=>[Y,Q>0?1:0])));const ft=I.parentFilters&&I.parentFilters.length>0?{...I.query,where:[...I.query.where||[],...I.parentFilters]}:I.query,T=Ac(ft,_,i,r,l,o,u,d,p,g,it,I.childCorrelationField);if(Object.assign(j,T.aliasToCollectionId),Object.assign(O,T.aliasRemapping),et.push({pipeline:T.pipeline,fieldName:I.fieldName,correlationField:I.correlationField,childCorrelationField:I.childCorrelationField,hasOrderBy:!!(I.query.orderBy&&I.query.orderBy.length>0),childCompilationResult:T,parentProjection:I.parentProjection,materialization:I.materialization,scalarField:I.scalarField}),I.parentProjection&&I.parentProjection.length>0){const B=I.parentProjection.map(Q=>({alias:Q.path[0],field:Q.path.slice(1),compiled:ue(Q)})),Y=Z;X.push({fieldName:I.fieldName,getRouting:Q=>{const ot={};for(const st of B){ot[st.alias]||(ot[st.alias]={});const mt=st.compiled(Q);let Ut=ot[st.alias];for(let wt=0;wt({correlationKey:Z(B),parentContext:null})});qA(E.select,k)}}if(E.distinct&&!E.fnSelect&&!E.select)throw new rx;if(E.fnSelect&&E.groupBy&&E.groupBy.length>0)throw new ax;E.fnSelect?W=W.pipe(le(([dt,k])=>{const I=E.fnSelect(k);return[dt,{...k,$selected:I}]})):E.select?W=zA(W,E.select):W=W.pipe(le(([dt,k])=>{const I=!E.join&&!E.groupBy?k[M]:k;return[dt,{...k,$selected:I}]})),X.length>0&&(W=W.pipe(le(([dt,k])=>{const I={};for(const{fieldName:Z,getRouting:it}of X)I[Z]=it(k);return k.$selected[Or]=I,[dt,k]})));const at=y?M:void 0;if(E.groupBy&&E.groupBy.length>0?W=yS(W,E.groupBy,E.having,E.select,E.fnHaving,q,at):E.select&&Object.values(E.select).some(k=>k.type===`agg`||Lr(k))&&(W=yS(W,[],E.having,E.select,E.fnHaving,q,at)),E.having&&(!E.groupBy||E.groupBy.length===0)&&!(E.select?Object.values(E.select).some(k=>k.type===`agg`):!1))throw new ox;if(E.fnHaving&&E.fnHaving.length>0&&(!E.groupBy||E.groupBy.length===0))for(const dt of E.fnHaving)W=W.pipe(ps(([k,I])=>dt(I)));if(E.distinct&&(W=W.pipe(H_(([dt,k])=>k.$selected))),E.orderBy&&E.orderBy.length>0){const dt=y&&(E.limit!==void 0||E.offset!==void 0)?(ft,T)=>{const B=T?.[M]?.__correlationKey,Y=T?.__parentContext;return Y!=null?JSON.stringify([B,Y]):B}:void 0,Z=yT(n,W,E.orderBy,E.select||{},i[q],u,d,E.limit,E.offset,dt).pipe(le(([ft,[T,B]])=>{const Y=T.$selected,Q=_S(Md(Y),T);if(y){const ot=T[M]?.__correlationKey,st=T.__parentContext??null;return delete Q.__correlationKey,delete Q.__parentContext,[ft,[Q,B,ot,st]]}return[ft,[Q,B]]})),it={collectionId:q,pipeline:Z,sourceWhereClauses:b,aliasToCollectionId:j,aliasRemapping:O,includes:et.length>0?et:void 0};return p.set(n,it),it}else if(E.limit!==void 0||E.offset!==void 0)throw new cx;const bt=W.pipe(le(([dt,k])=>{const I=k.$selected,Z=_S(Md(I),k);if(y){const it=k[M]?.__correlationKey,ft=k.__parentContext??null;return delete Z.__correlationKey,delete Z.__parentContext,[dt,[Z,void 0,it,ft]]}return[dt,[Z,void 0]]})),Lt={collectionId:q,pipeline:bt,sourceWhereClauses:b,aliasToCollectionId:j,aliasRemapping:O,includes:et.length>0?et:void 0};return p.set(n,Lt),Lt}function BA(n){const t=new Set;if(n.from.type===`collectionRef`&&t.add(n.from.alias),n.join)for(const i of n.join)i.from.type===`collectionRef`&&t.add(i.from.alias);return t}function Dd(n,t=new Set){const i=BA(n);for(const l of i)if(t.has(l))throw new ux(l,Array.from(t));const r=new Set([...t,...i]);if(n.from.type===`queryRef`&&Dd(n.from.query,r),n.join)for(const l of n.join)l.from.type===`queryRef`&&Dd(l.from.query,r)}function LA(n,t,i,r,l,o,u,d,p,g,y,m,v){switch(n.type){case`collectionRef`:{const w=t[n.alias];if(!w)throw new Nv(n.alias,n.collection.id,Object.keys(t));return y[n.alias]=n.collection.id,{alias:n.alias,input:w,collectionId:n.collection.id}}case`queryRef`:{const w=g.get(n.query)||n.query,b=Ac(w,t,i,r,l,o,u,d,p,g);Object.assign(y,b.aliasToCollectionId),Object.assign(m,b.aliasRemapping);const E=g.has(n.query),_=n.query.from.alias;if(!(!E&&n.alias===_))for(const[G,q]of b.sourceWhereClauses)v.set(G,q);const O=Object.keys(b.aliasToCollectionId).find(G=>b.aliasToCollectionId[G]===b.collectionId);O&&O!==n.alias&&(m[n.alias]=O);const M=b.pipeline.pipe(le(G=>{const[q,[K,W]]=G,et=Md(K);return[q,et]}));return{alias:n.alias,input:M,collectionId:b.collectionId}}default:throw new fx(n.type)}}function IA(n){return n instanceof Ue||n&&typeof n==`object`&&`type`in n&&n.type===`val`}function Md(n){return IA(n)?n.value:n}function _S(n,t){if(!n||typeof n!=`object`)return n;let i=!1;for(const r of pd)if(n[r]==null&&r in t){i=!0;break}if(!i)return n;for(const r of pd)n[r]==null&&r in t&&(n[r]=t[r]);return n}function kd(n,t,i){if(n.from.type===`queryRef`&&t.from.type===`queryRef`&&(i.set(n.from.query,t.from.query),kd(n.from.query,t.from.query,i)),n.join&&t.join)for(let r=0;r1)return new Oe(r.slice(1));if(r.length===1&&r[0]!==void 0)return new Oe([r[0]])}return new Oe(Array.isArray(r)?r:[String(r)])}else{const r=[];for(const l of n.args){const o=hp(l,t);r.push(o)}return new Ve(n.name,r)}}function dp(n,t){return n.map(r=>{const l=hp(r.expression,t);return{...r,expression:l}})}const lb=new WeakMap;function VA(n){return n.utils?.[rp]?.getBuilder?.()}function $A(n,t){lb.set(n,t)}function GA(n){return lb.get(n)}class Zt{constructor(t={}){this.query={},this.query={...t}}_createRefForSource(t,i){let r;try{r=Object.keys(t)}catch{const d=t===null?`null`:`undefined`;throw new Qo(i,d)}if(Array.isArray(t))throw new Qo(i,`array`);if(r.length!==1)throw r.length===0?new Qo(i,`empty object`):r.every(d=>!isNaN(Number(d)))?new Qo(i,`string`):new tx(i);const l=r[0],o=t[l];let u;if(o instanceof cp)u=new jr(o,l);else if(o instanceof Zt){const d=o._getQuery();if(!d.from)throw new ex(i);u=new Sn(d,l)}else throw new nx(l);return[l,u]}from(t){const[,i]=this._createRefForSource(t,`from clause`);return new Zt({...this.query,from:i})}join(t,i,r=`left`){const[l,o]=this._createRefForSource(t,`join clause`),d=[...this._getCurrentAliases(),l],p=vi(d),g=i(p);let y,m;if(g.type===`func`&&g.name===`eq`&&g.args.length===2)y=g.args[0],m=g.args[1];else throw new sx;const v={from:o,type:r,left:y,right:m},w=this.query.join||[];return new Zt({...this.query,join:[...w,v]})}leftJoin(t,i){return this.join(t,i,`left`)}rightJoin(t,i){return this.join(t,i,`right`)}innerJoin(t,i){return this.join(t,i,`inner`)}fullJoin(t,i){return this.join(t,i,`full`)}where(t){const i=this._getCurrentAliases(),r=vi(i),l=t(r),o=oc(l)?ne(l):l;if(!Br(o))throw new tS(TS(o));const u=this.query.where||[];return new Zt({...this.query,where:[...u,o]})}having(t){const i=this._getCurrentAliases(),r=this.query.select||this.query.fnSelect?bS(i):vi(i),l=t(r),o=oc(l)?ne(l):l;if(!Br(o))throw new tS(TS(o));const u=this.query.having||[];return new Zt({...this.query,having:[...u,o]})}select(t){const i=this._getCurrentAliases(),r=vi(i);let l=t(r);oc(l)&&l.__path.length===1&&(l={[`__SPREAD_SENTINEL__${l.__path[0]}__0`]:!0});const o=cb(l,i);return new Zt({...this.query,select:o,fnSelect:void 0})}orderBy(t,i=`asc`){const r=this._getCurrentAliases(),l=this.query.select||this.query.fnSelect?bS(r):vi(r),o=t(l),u=typeof i==`string`?{direction:i,nulls:`first`}:{direction:i.direction??`asc`,nulls:i.nulls??`first`,stringSort:i.stringSort,locale:i.stringSort===`locale`?i.locale:void 0,localeOptions:i.stringSort===`locale`?i.localeOptions:void 0},d=y=>({expression:ne(y),compareOptions:u}),p=Array.isArray(o)?o.map(y=>d(y)):[d(o)],g=this.query.orderBy||[];return new Zt({...this.query,orderBy:[...g,...p]})}groupBy(t){const i=this._getCurrentAliases(),r=vi(i),l=t(r),o=Array.isArray(l)?l.map(d=>ne(d)):[ne(l)],u=this.query.groupBy||[];return new Zt({...this.query,groupBy:[...u,...o]})}limit(t){return new Zt({...this.query,limit:t})}offset(t){return new Zt({...this.query,offset:t})}distinct(){return new Zt({...this.query,distinct:!0})}findOne(){return new Zt({...this.query,singleResult:!0})}_getCurrentAliases(){const t=[];if(this.query.from&&t.push(this.query.from.alias),this.query.join)for(const i of this.query.join)t.push(i.from.alias);return t}get fn(){const t=this;return{select(i){return new Zt({...t.query,select:void 0,fnSelect:i})},where(i){return new Zt({...t.query,fnWhere:[...t.query.fnWhere||[],i]})},having(i){return new Zt({...t.query,fnHaving:[...t.query.fnHaving||[],i]})}}}_getQuery(){if(!this.query.from)throw new ix;return this.query}}function TS(n){return n===null?`null`:n===void 0?`undefined`:typeof n==`object`?`object`:typeof n}function YA(n){return n===void 0?ne(null):n instanceof zv||n instanceof Ve||n instanceof Oe||n instanceof Ue?n:ne(n)}function ob(n){return n!==null&&typeof n==`object`&&!Br(n)&&!n.__refProxy}function cb(n,t=[]){if(!ob(n))return YA(n);const i={};for(const[r,l]of Object.entries(n)){if(typeof r==`string`&&r.startsWith(`__SPREAD_SENTINEL__`)){i[r]=l;continue}if(l instanceof Zt){i[r]=qh(l,r,t,`collection`);continue}if(l instanceof xT){if(!(l.query instanceof Zt))throw new Error(`toArray() must wrap a subquery builder`);i[r]=qh(l.query,r,t,`array`);continue}if(l instanceof _T){if(!(l.query instanceof Zt))throw new Error(`concat(toArray(...)) must wrap a subquery builder`);i[r]=qh(l.query,r,t,`concat`);continue}i[r]=cb(l,t)}return i}function pp(n){const t=[];switch(n.type){case`ref`:t.push(n);break;case`func`:for(const i of n.args??[])t.push(...pp(i));break}return t}function FA(n,t){const i=typeof n==`object`&&`expression`in n?n.expression:n;return pp(i).some(r=>r.path[0]!=null&&t.includes(r.path[0]))}function qh(n,t,i,r){const l=n._getQuery(),o=[l.from.alias];if(l.join)for(const A of l.join)o.push(A.from.alias);let u,d,p=-1,g=-1;if(l.where)for(let A=0;A=2){for(let q=0;q eq(child.parentId, parent.id))`);const y=[...l.where];if(g>=0){const A=y[p],G=(typeof A==`object`&&`expression`in A?A.expression:A).args.filter((q,K)=>K!==g);if(G.length===1){const q=typeof A==`object`&&`expression`in A&&A.residual;y[p]=q?{expression:G[0],residual:!0}:G[0]}else{const q=new Ve(`and`,G),K=typeof A==`object`&&`expression`in A&&A.residual;y[p]=K?{expression:q,residual:!0}:q}}else y.splice(p,1);const m=[],v=[];for(const A of y)FA(A,i)?v.push(A):m.push(A);let w;if(v.length>0){const A=new Set;w=[];for(const M of v){const G=typeof M==`object`&&`expression`in M?M.expression:M;for(const q of pp(G))q.path[0]!=null&&i.includes(q.path[0])&&!A.has(q.path.join(`.`))&&(A.add(q.path.join(`.`)),w.push(q))}}const b={...l,where:m.length>0?m:void 0},E=b.select,_=E===void 0||ob(E);let j=b,O;if(r===`concat`&&(E===void 0||_))throw new Error(`concat(toArray(...)) for "${t}" requires the subquery to select a scalar value`);if(!_){if(r===`collection`)throw new Error(`Includes subquery for "${t}" must select an object when materializing as a Collection`);O=xC,j={...b,select:{[O]:E}}}return new Ti(j,u,d,t,v.length>0?v:void 0,w,r,O)}function AS(n,t,i,r){if(n.type===`ref`&&t.type===`ref`){const l=n.path[0],o=t.path[0];if(l&&o&&i.includes(l)&&r.includes(o))return{parentRef:n,childRef:t};if(l&&o&&i.includes(o)&&r.includes(l))return{parentRef:t,childRef:n}}}function QA(n){const t=n(new Zt);return ub(t)}function ub(n){return n._getQuery()}function XA(n){const t={};function i(o){o.type===`collectionRef`?t[o.collection.id]=o.collection:o.type===`queryRef`&&r(o.query)}function r(o){if(o.from&&i(o.from),o.join&&Array.isArray(o.join))for(const u of o.join)u.from&&i(u.from);o.select&&l(o.select)}function l(o){for(const[u,d]of Object.entries(o))typeof u==`string`&&u.startsWith(`__SPREAD_SENTINEL__`)||(d instanceof Ti?r(d.query):gp(d)&&l(d))}return r(n),t}function fb(n){const t=n.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`queryRef`)return fb(t.query);throw new Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(n)}`)}function JA(n){const t=new Map;function i(o){if(o)if(o.type===`collectionRef`){const{id:u}=o.collection,d=t.get(u);d?d.add(o.alias):t.set(u,new Set([o.alias]))}else o.type===`queryRef`&&l(o.query)}function r(o){for(const[u,d]of Object.entries(o))typeof u==`string`&&u.startsWith(`__SPREAD_SENTINEL__`)||(d instanceof Ti?l(d.query):gp(d)&&r(d))}function l(o){if(o){if(i(o.from),o.join)for(const u of o.join)i(u.from);o.select&&r(o.select)}}return l(n),t}function gp(n){return!(n===null||typeof n!=`object`||n instanceof Ti||`type`in n&&typeof n.type==`string`||n.__refProxy)}function ZA(n){const t=typeof n.query==`function`?QA(n.query):ub(n.query);if(t.select&&!gp(t.select))throw new lx;return t}function WA(n,t,i){const r=[];for(const l of t){const o=i(l.value);l.type===`insert`?r.push([[o,l.value],1]):l.type===`update`?(r.push([[o,l.previousValue],-1]),r.push([[o,l.value],1])):r.push([[o,l.value],-1])}return r.length!==0&&n.sendData(new ee(r)),r.length}function*PA(n){for(const t of n)t.type===`update`?(yield{type:`delete`,key:t.key,value:t.previousValue},yield{type:`insert`,key:t.key,value:t.value}):yield t}function tO(n,t){const i=[];for(const r of n){if(r.type===`insert`){if(t.has(r.key))continue;t.add(r.key)}else r.type===`delete`&&t.delete(r.key);i.push(r)}return i}function eO(n,t,i,r){let l=t,o=!1;for(const u of n){if(u.type===`delete`)continue;const d=!i.has(u.key);l===void 0||r(l,u.value)<0?(l=u.value,o=!0):d&&(o=!0)}return{biggest:l,shouldResetLoadKey:o}}function nO(n,t){const{orderBy:i,limit:r,offset:l}=n,o=r!==void 0&&l!==void 0?r+l:r,u=i?dp(i,t):void 0,d=u?.every(p=>{const g=p.expression;if(g.type!==`ref`)return!1;const y=g.path;return Array.isArray(y)&&y.length===1})??!1;return{orderBy:d?u:void 0,limit:d?o:void 0}}function sO(n,t,i,r,l){const{orderBy:o,valueExtractorForRawRow:u,offset:d}=n,p=t?u(t):void 0;let g;p!==void 0&&(g=Array.isArray(p)?p:[p]);const y=cl({minValues:g??null,offset:d,limit:l});if(i===y)return;const m=dp(o,r);return{minValues:g,normalizedOrderBy:m,loadRequestKey:y}}const OS=Symbol.for(`@tanstack/db.collection-config-builder`);class iO{constructor(t,i,r,l){this.alias=t,this.collectionId=i,this.collection=r,this.collectionConfigBuilder=l,this.biggest=void 0,this.subscriptionLoadingPromises=new Map,this.sentToD2Keys=new Set}subscribe(){const t=this.getWhereClauseForAlias();if(t){const i=hp(t,this.alias);return this.subscribeToChanges(i)}return this.subscribeToChanges()}subscribeToChanges(t){const i=this.getOrderByInfo(),r=d=>{d instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(d)},l=d=>{const p=d.subscription;if(d.status===`loadingSubset`)this.ensureLoadingPromise(p);else{const g=this.subscriptionLoadingPromises.get(p);g&&(this.subscriptionLoadingPromises.delete(p),g.resolve())}};let o;if(i)o=this.subscribeToOrderedChanges(t,i,l,r);else{const d=!this.collectionConfigBuilder.isLazyAlias(this.alias);o=this.subscribeToMatchingChanges(t,d,l)}o.status===`loadingSubset`&&this.ensureLoadingPromise(o);const u=()=>{const d=this.subscriptionLoadingPromises.get(o);d&&(this.subscriptionLoadingPromises.delete(o),d.resolve()),o.unsubscribe()};return this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(u),o}sendChangesToPipeline(t,i){const r=Array.isArray(t)?t:[...t],l=tO(r,this.sentToD2Keys),o=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],d=WA(o,l,this.collection.config.getKey)>0?i:void 0;this.collectionConfigBuilder.scheduleGraphRun(d,{alias:this.alias})}subscribeToMatchingChanges(t,i,r){const l=p=>{this.sendChangesToPipeline(p)},o=nO(this.collectionConfigBuilder.query,this.alias),u=i?p=>{p instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(p)}:void 0;return this.collection.subscribeChanges(l,{...i&&{includeInitialState:i},whereExpression:t,onStatusChange:r,orderBy:o.orderBy,limit:o.limit,onLoadSubsetResult:u})}subscribeToOrderedChanges(t,i,r,l){const{orderBy:o,offset:u,limit:d,index:p}=i,g=E=>{E instanceof Promise&&(this.pendingOrderedLoadPromise=E,E.finally(()=>{this.pendingOrderedLoadPromise===E&&(this.pendingOrderedLoadPromise=void 0)})),l(E)};this.orderedLoadSubsetResult=g;const y={},m=E=>{const _=Array.isArray(E)?E:[...E];this.trackSentValues(_,i.comparator);const j=PA(_);this.sendChangesToPipelineWithTracking(j,y.current)},v=this.collection.subscribeChanges(m,{whereExpression:t,onStatusChange:r});y.current=v;const w=this.collection.on(`truncate`,()=>{this.biggest=void 0,this.lastLoadRequestKey=void 0,this.pendingOrderedLoadPromise=void 0,this.sentToD2Keys.clear()});v.on(`unsubscribed`,()=>{w()});const b=dp(o,this.alias);return p?(v.setOrderByIndex(p),v.requestLimitedSnapshot({limit:u+d,orderBy:b,trackLoadSubsetPromise:!1,onLoadSubsetResult:g})):v.requestSnapshot({orderBy:b,limit:u+d,trackLoadSubsetPromise:!1,onLoadSubsetResult:g}),v}loadMoreIfNeeded(t){const i=this.getOrderByInfo();if(!i)return!0;const{dataNeeded:r}=i;if(!r||this.pendingOrderedLoadPromise)return!0;const l=r();return l>0&&this.loadNextItems(l,t),!0}sendChangesToPipelineWithTracking(t,i){if(!this.getOrderByInfo()){this.sendChangesToPipeline(t);return}const l=i;l[OS]??=this.loadMoreIfNeeded.bind(this,i),this.sendChangesToPipeline(t,l[OS])}loadNextItems(t,i){const r=this.getOrderByInfo();if(!r)return;const l=sO(r,this.biggest,this.lastLoadRequestKey,this.alias,t);l&&(this.lastLoadRequestKey=l.loadRequestKey,i.requestLimitedSnapshot({orderBy:l.normalizedOrderBy,limit:t,minValues:l.minValues,trackLoadSubsetPromise:!1,onLoadSubsetResult:this.orderedLoadSubsetResult}))}getWhereClauseForAlias(){const t=this.collectionConfigBuilder.sourceWhereClausesCache;if(t)return t.get(this.alias)}getOrderByInfo(){const t=this.collectionConfigBuilder.optimizableOrderByCollections[this.collectionId];if(t&&t.alias===this.alias)return t}trackSentValues(t,i){const r=eO(t,this.biggest,this.sentToD2Keys,i);this.biggest=r.biggest,r.shouldResetLoadKey&&(this.lastLoadRequestKey=void 0)}ensureLoadingPromise(t){if(this.subscriptionLoadingPromises.has(t))return;let i;const r=new Promise(l=>{i=l});this.subscriptionLoadingPromises.set(t,{resolve:i}),this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(r)}}let rO=0;class aO{constructor(t){this.config=t,this.compiledAliasToCollectionId={},this.resultKeys=new WeakMap,this.orderByIndices=new WeakMap,this.isGraphRunning=!1,this.runCount=0,this.isInErrorState=!1,this.aliasDependencies={},this.builderDependencies=new Set,this.pendingGraphRuns=new Map,this.subscriptions={},this.lazySourcesCallbacks={},this.lazySources=new Set,this.optimizableOrderByCollections={},this.id=t.id||`live-query-${++rO}`,this.query=ZA({query:t.query}),this.collections=XA(this.query);const i=JA(this.query);this.collectionByAlias={};for(const[r,l]of i.entries()){const o=this.collections[r];if(o)for(const u of l)this.collectionByAlias[u]=o}this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=hb(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??fb(this.query).compareOptions,this.compileBasePipeline()}hasJoins(t){return!!(t.join&&t.join.length>0||t.from.type===`queryRef`&&this.hasJoins(t.from.query))}getConfig(){return{id:this.id,getKey:this.config.getKey||(t=>this.resultKeys.get(t)),sync:this.getSyncConfig(),compare:this.compare,defaultStringCollation:this.compareOptions,gcTime:this.config.gcTime||5e3,schema:this.config.schema,onInsert:this.config.onInsert,onUpdate:this.config.onUpdate,onDelete:this.config.onDelete,startSync:this.config.startSync,singleResult:this.query.singleResult,utils:{getRunCount:this.getRunCount.bind(this),setWindow:this.setWindow.bind(this),getWindow:this.getWindow.bind(this),[rp]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(t){if(!this.windowFn)throw new Dx;return this.currentWindow=t,this.windowFn(t),this.maybeRunGraphFn?.(),this.liveQueryCollection?.isLoadingSubset?new Promise(i=>{const r=this.liveQueryCollection.on(`loadingSubset:change`,l=>{l.isLoadingSubset||(r(),i())})}):!0}getWindow(){if(!(!this.windowFn||!this.currentWindow))return{offset:this.currentWindow.offset??0,limit:this.currentWindow.limit??0}}getCollectionIdForAlias(t){const i=this.compiledAliasToCollectionId[t];if(i)return i;const r=this.collectionByAlias[t];if(r)return r.id;throw new Error(`Unknown source alias "${t}"`)}isLazyAlias(t){return this.lazySources.has(t)}maybeRunGraph(t){if(!this.isGraphRunning){if(!this.currentSyncConfig||!this.currentSyncState)throw new Error(`maybeRunGraph called without active sync session. This should not happen.`);this.isGraphRunning=!0;try{const{begin:i,commit:r}=this.currentSyncConfig,l=this.currentSyncState;if(this.isInErrorState)return;if(l.subscribedToAllCollections){let o=!1;for(;l.graph.pendingWork();)l.graph.run(),l.flushPendingChanges?.(),t?.(),o=!0;o||t?.(),l.messagesCount===0&&(i(),r()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(t,i){const r=i?.contextId??uc()?.id,l=i?.jobId??this,o=(()=>{if(i?.dependencies)return i.dependencies;const p=new Set(this.builderDependencies);if(i?.alias){const g=this.aliasDependencies[i.alias];if(g)for(const y of g)p.add(y)}return p.delete(this),Array.from(p)})();if(r)for(const p of o)typeof p.scheduleGraphRun==`function`&&p.scheduleGraphRun(void 0,{contextId:r});if(!this.currentSyncConfig||!this.currentSyncState)throw new Error(`scheduleGraphRun called without active sync session. This should not happen.`);let u=r?this.pendingGraphRuns.get(r):void 0;u||(u={loadCallbacks:new Set},r&&this.pendingGraphRuns.set(r,u)),t&&u.loadCallbacks.add(t);const d=r?void 0:u;xc.schedule({contextId:r,jobId:l,dependencies:o,run:()=>this.executeGraphRun(r,d)})}clearPendingGraphRun(t){this.pendingGraphRuns.delete(t)}hasPendingGraphRun(t){return this.pendingGraphRuns.has(t)}executeGraphRun(t,i){const r=i??(t?this.pendingGraphRuns.get(t):void 0);if(t&&this.pendingGraphRuns.delete(t),!r||!this.currentSyncConfig||!this.currentSyncState)return;this.incrementRunCount();const l=()=>{let o=!0,u;if(r.loadCallbacks.forEach(d=>{try{o=d()&&o}catch(p){o=!1,u??=p}}),u)throw u;return o};this.maybeRunGraph(l)}getSyncConfig(){return{rowUpdateMode:`full`,sync:this.syncFn.bind(this)}}incrementRunCount(){this.runCount++}getRunCount(){return this.runCount}syncFn(t){this.liveQueryCollection=t.collection,this.currentSyncConfig=t;const i={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},r=this.extendPipelineWithChangeProcessing(t,i);this.currentSyncState=r,this.unsubscribeFromSchedulerClears=xc.onClear(u=>{this.clearPendingGraphRun(u)});const l=t.collection.on(`loadingSubset:change`,u=>{u.isLoadingSubset||this.updateLiveQueryStatus(t)});i.unsubscribeCallbacks.add(l);const o=this.subscribeToAllCollections(t,r);return this.maybeRunGraphFn=()=>this.scheduleGraphRun(o),this.scheduleGraphRun(o),()=>{i.unsubscribeCallbacks.forEach(u=>u()),this.currentSyncConfig=void 0,this.currentSyncState=void 0,this.pendingGraphRuns.clear(),this.graphCache=void 0,this.inputsCache=void 0,this.pipelineCache=void 0,this.sourceWhereClausesCache=void 0,this.includesCache=void 0,this.lazySources.clear(),this.optimizableOrderByCollections={},this.lazySourcesCallbacks={},Object.keys(this.subscriptions).forEach(u=>delete this.subscriptions[u]),this.compiledAliasToCollectionId={},this.unsubscribeFromSchedulerClears?.(),this.unsubscribeFromSchedulerClears=void 0}}compileBasePipeline(){this.graphCache=new N_,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(r=>[r,this.graphCache.newInput()]));const t=Ac(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,r=>{this.windowFn=r});this.pipelineCache=t.pipeline,this.sourceWhereClausesCache=t.sourceWhereClauses,this.compiledAliasToCollectionId=t.aliasToCollectionId,this.includesCache=t.includes;const i=Object.keys(this.compiledAliasToCollectionId).filter(r=>!Object.hasOwn(this.inputsCache,r));if(i.length>0)throw new Rx(i)}maybeCompileBasePipeline(){return(!this.graphCache||!this.inputsCache||!this.pipelineCache)&&this.compileBasePipeline(),{graph:this.graphCache,inputs:this.inputsCache,pipeline:this.pipelineCache}}extendPipelineWithChangeProcessing(t,i){const{begin:r,commit:l}=t,{graph:o,inputs:u,pipeline:d}=this.maybeCompileBasePipeline();let p=new Map;d.pipe(md(y=>{const m=y.getInner();i.messagesCount+=m.length,m.reduce(dO,p)}));const g=this.setupIncludesOutput(this.includesCache,i);return i.flushPendingChanges=()=>{const y=p.size>0,m=fO(g);if(!y&&!m)return;let v=p;if(this.config.getKey){const w=new Map;for(const[,b]of p){const E=this.config.getKey(b.value),_=w.get(E);_?(_.inserts+=b.inserts,_.deletes+=b.deletes,b.inserts>0&&(_.value=b.value,b.orderByIndex!==void 0&&(_.orderByIndex=b.orderByIndex))):w.set(E,{...b})}v=w}y&&(r(),v.forEach(this.applyChanges.bind(this,t)),l()),p=new Map,Ud(g,t.collection,this.id,y?v:null,t)},o.finalize(),i.graph=o,i.inputs=u,i.pipeline=d,i}setupIncludesOutput(t,i){return!t||t.length===0?[]:t.map(r=>{const l={fieldName:r.fieldName,childCorrelationField:r.childCorrelationField,hasOrderBy:r.hasOrderBy,materialization:r.materialization,scalarField:r.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return r.pipeline.pipe(md(o=>{const u=o.getInner();i.messagesCount+=u.length;for(const[[d,p],g]of u){const[y,m,v,w]=p,b=Ir(v,w);let E=l.pendingChildChanges.get(b);E||(E=new Map,l.pendingChildChanges.set(b,E));const _=E.get(d)||{deletes:0,inserts:0,value:y,orderByIndex:m};g<0?_.deletes+=Math.abs(g):g>0&&(_.inserts+=g,_.value=y),E.set(d,_)}})),r.childCompilationResult.includes&&(l.nestedSetups=db(r.childCompilationResult.includes,i),l.nestedRoutingIndex=new Map,l.nestedRoutingReverseIndex=new Map),l})}applyChanges(t,i,r){const{write:l,collection:o}=t,{deletes:u,inserts:d,value:p,orderByIndex:g}=i;if(this.resultKeys.set(p,r),g!==void 0&&this.orderByIndices.set(p,g),d&&u===0)l({value:p,type:`insert`});else if(d>u||d===u&&o.has(o.getKeyFromItem(p)))l({value:p,type:`update`});else if(u>0)l({value:p,type:`delete`});else throw new Error(`Could not apply changes: ${JSON.stringify(i)}. This should never happen.`)}handleSourceStatusChange(t,i,r){const{status:l}=r;if(l===`error`){this.transitionToError(`Source collection '${i}' entered error state`);return}if(l===`cleaned-up`){this.transitionToError(`Source collection '${i}' was manually cleaned up while live query '${this.id}' depends on it. Live queries prevent automatic GC, so this was likely a manual cleanup() call.`);return}this.updateLiveQueryStatus(t)}updateLiveQueryStatus(t){const{markReady:i}=t;if(this.isInErrorState)return;const r=this.currentSyncState?.subscribedToAllCollections,l=this.allCollectionsReady(),o=this.liveQueryCollection?.isLoadingSubset;r&&l&&!o&&i()}transitionToError(t){this.isInErrorState=!0,console.error(`[Live Query Error] ${t}`),this.liveQueryCollection?._lifecycle.setStatus(`error`)}allCollectionsReady(){return Object.values(this.collections).every(t=>t.isReady())}subscribeToAllCollections(t,i){const r=Object.entries(this.compiledAliasToCollectionId);if(r.length===0)throw new Error(`Compiler returned no alias metadata for query '${this.id}'. This should not happen; please report.`);const l=r.map(([u,d])=>{const p=this.collectionByAlias[u]??this.collections[d],g=GA(p);g&&g!==this?(this.aliasDependencies[u]=[g],this.builderDependencies.add(g)):this.aliasDependencies[u]=[];const y=new iO(u,d,p,this),m=p.on(`status:change`,b=>{this.handleSourceStatusChange(t,d,b)});i.unsubscribeCallbacks.add(m);const v=y.subscribe();return this.subscriptions[u]=v,y.loadMoreIfNeeded.bind(y,v)}),o=()=>(l.map(u=>u()),!0);return i.subscribedToAllCollections=!0,o}}function hb(n){return(t,i)=>{const r=n.get(t),l=n.get(i);return r&&l?rl?1:0:0}}function RS(n){return n.materialization!==`collection`}function DS(n,t){if(!t)return n.materialization===`array`?[]:n.materialization===`concat`?``:void 0;if(n.materialization===`collection`)return t.collection;const i=[...t.collection.toArray],r=n.scalarField?i.map(l=>l?.[n.scalarField]):i;return n.materialization===`array`?r:r.map(l=>String(l??``)).join(``)}function db(n,t){return n.map(i=>{const r=new Map;i.pipeline.pipe(md(o=>{const u=o.getInner();t.messagesCount+=u.length;for(const[[d,p],g]of u){const[y,m,v,w]=p,b=Ir(v,w);let E=r.get(b);E||(E=new Map,r.set(b,E));const _=E.get(d)||{deletes:0,inserts:0,value:y,orderByIndex:m};g<0?_.deletes+=Math.abs(g):g>0&&(_.inserts+=g,_.value=y),E.set(d,_)}}));const l={compilationResult:i,buffer:r};return i.childCompilationResult.includes&&(l.nestedSetups=db(i.childCompilationResult.includes,t)),l})}function lO(n){return n.map(t=>{const i={fieldName:t.compilationResult.fieldName,childCorrelationField:t.compilationResult.childCorrelationField,hasOrderBy:t.compilationResult.hasOrderBy,materialization:t.compilationResult.materialization,scalarField:t.compilationResult.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return t.nestedSetups&&(i.nestedSetups=t.nestedSetups,i.nestedRoutingIndex=new Map,i.nestedRoutingReverseIndex=new Map),i})}function oO(n){const t=new Set;if(!n.nestedSetups)return t;for(let i=0;i0&&(w.value=m.value,m.orderByIndex!==void 0&&(w.orderByIndex=m.orderByIndex))):v.set(y,{...m})}t.add(d),l.push(o)}for(const o of l)r.buffer.delete(o)}return t}function cO(n,t,i){if(n.nestedSetups){for(const r of n.nestedSetups)for(const[,l]of i)if(l.inserts>0){const o=l.value[Or]?.[r.compilationResult.fieldName],u=o?.correlationKey,d=o?.parentContext??null,p=Ir(u,d);if(u!=null){n.nestedRoutingIndex.set(p,t);let g=n.nestedRoutingReverseIndex.get(t);g||(g=new Set,n.nestedRoutingReverseIndex.set(t,g)),g.add(p)}}else if(l.deletes>0&&l.inserts===0){const o=l.value[Or]?.[r.compilationResult.fieldName],u=o?.correlationKey,d=o?.parentContext??null,p=Ir(u,d);if(u!=null){n.nestedRoutingIndex.delete(p);const g=n.nestedRoutingReverseIndex.get(t);g&&(g.delete(p),g.size===0&&n.nestedRoutingReverseIndex.delete(t))}}}}function uO(n,t){if(!n.nestedRoutingReverseIndex)return;const i=n.nestedRoutingReverseIndex.get(t);if(i){for(const r of i)n.nestedRoutingIndex.delete(r);n.nestedRoutingReverseIndex.delete(t)}}function pb(n){for(const t of n)if(t.buffer.size>0||t.nestedSetups&&pb(t.nestedSetups))return!0;return!1}function Ir(n,t){return t==null?n:JSON.stringify([n,t])}function MS(n,t,i,r,l){const o=new WeakMap,u=r?new WeakMap:null;let d=null;const p=u?hb(u):void 0,y={collection:op({id:`__child-collection:${n}-${t}-${cl(i)}`,getKey:m=>o.get(m),compare:p,sync:{rowUpdateMode:`full`,sync:m=>(d=m,()=>{d=null})},startSync:!0}),get syncMethods(){return d},resultKeys:o,orderByIndices:u};return l&&(y.includesStates=lO(l)),y}function Ud(n,t,i,r,l){for(const o of n){if(r){for(const[y,m]of r)if(m.inserts>0){const v=m.value,w=v[Or]?.[o.fieldName],b=w?.correlationKey,E=w?.parentContext??null,_=Ir(b,E);if(b!=null){if(!o.childRegistry.has(_)){const M=MS(i,o.fieldName,_,o.hasOrderBy,o.nestedSetups);o.childRegistry.set(_,M)}let j=o.correlationToParentKeys.get(_);j||(j=new Set,o.correlationToParentKeys.set(_,j)),j.add(y);const O=DS(o,o.childRegistry.get(_));v[o.fieldName]=O;const A=t.get(y);A&&A!==v&&(A[o.fieldName]=O)}}}const u=RS(o)?new Set(o.pendingChildChanges.keys()):null,d=new Map;if(o.pendingChildChanges.size>0){for(const[y,m]of o.pendingChildChanges){let v=o.childRegistry.get(y);if(v||(v=MS(i,o.fieldName,y,o.hasOrderBy,o.nestedSetups),o.childRegistry.set(y,v)),o.materialization===`collection`&&hO(t,o.fieldName,y,o.correlationToParentKeys,v.collection),v.syncMethods){v.syncMethods.begin();for(const[w,b]of m)v.resultKeys.set(b.value,w),v.orderByIndices&&b.orderByIndex!==void 0&&v.orderByIndices.set(b.value,b.orderByIndex),b.inserts>0&&b.deletes===0?v.syncMethods.write({value:b.value,type:`insert`}):b.inserts>b.deletes||b.inserts===b.deletes&&v.syncMethods.collection.has(v.syncMethods.collection.getKeyFromItem(b.value))?v.syncMethods.write({value:b.value,type:`update`}):b.deletes>0&&v.syncMethods.write({value:b.value,type:`delete`});v.syncMethods.commit()}cO(o,y,m),d.set(y,{entry:v,childChanges:m})}o.pendingChildChanges.clear()}const p=oO(o);for(const[,{entry:y,childChanges:m}]of d)y.includesStates&&Ud(y.includesStates,y.collection,y.collection.id,m,y.syncMethods);for(const y of p){if(d.has(y))continue;const m=o.childRegistry.get(y);m?.includesStates&&Ud(m.includesStates,m.collection,m.collection.id,null,m.syncMethods)}const g=RS(o)?new Set([...u||[],...p]):null;if(l&&g&&g.size>0){const y=[];for(const m of g){const v=o.correlationToParentKeys.get(m);if(!v)continue;const w=o.childRegistry.get(m);for(const b of v){const E=t.get(b);if(E){const _=l.collection.getKeyFromItem(E),j={...E};E[o.fieldName]=DS(o,w),y.push({type:`update`,key:_,value:E,previousValue:j})}}}y.length>0&&t._changes.emitEvents(y,!0)}if(r){for(const[y,m]of r)if(m.deletes>0&&m.inserts===0){const v=m.value[Or]?.[o.fieldName],w=v?.correlationKey,b=v?.parentContext??null,E=Ir(w,b);if(w!=null){const _=o.correlationToParentKeys.get(E);_&&(_.delete(y),_.size===0&&(uO(o,E),o.childRegistry.delete(E),o.correlationToParentKeys.delete(E)))}}}}if(r)for(const[,o]of r)delete o.value[Or]}function fO(n){for(const t of n)if(t.pendingChildChanges.size>0||t.nestedSetups&&pb(t.nestedSetups))return!0;return!1}function hO(n,t,i,r,l){const o=r.get(i);if(o)for(const u of o){const d=n.get(u);d&&(d[t]=l)}}function dO(n,[[t,i],r]){const[l,o]=i,u=n.get(t)||{deletes:0,inserts:0,value:l,orderByIndex:o};return r<0?u.deletes+=Math.abs(r):r>0&&(u.inserts+=r,u.value=l,o!==void 0&&(u.orderByIndex=o)),n.set(t,u),n}function kS(n){return new aO(n).getConfig()}function Kh(n){if(typeof n==`function`){const i=kS({query:n});return US(i)}else{const t=n,i=kS(t);return t.utils&&(i.utils={...i.utils,...t.utils}),US(i)}}function US(n){const t=op(n),i=VA(n);return i&&$A(t,i),t}var Zo={exports:{}},Vh,zS;function pO(){if(zS)return Vh;zS=1;function n(t){var i=new t,r=i;function l(){var u=i;return u.next?i=u.next:(i=new t,r=i),u.next=null,u}function o(u){r.next=u,r=u}return{get:l,release:o}}return Vh=n,Vh}var NS;function gO(){if(NS)return Zo.exports;NS=1;var n=pO();function t(o,u,d){if(typeof o==`function`&&(d=u,u=o,o=null),!(d>=1))throw new Error(`fastqueue concurrency must be equal to or greater than 1`);var p=n(r),g=null,y=null,m=0,v=null,w={push:M,drain:i,saturated:i,pause:E,paused:!1,get concurrency(){return d},set concurrency(X){if(!(X>=1))throw new Error(`fastqueue concurrency must be equal to or greater than 1`);if(d=X,!w.paused)for(;g&&m=d||w.paused?y?(y.next=nt,y=nt):(g=nt,y=nt,w.saturated()):(m++,u.call(o,nt.value,nt.worked))}function G(X,at){var nt=p.get();nt.context=o,nt.release=q,nt.value=X,nt.callback=at||i,nt.errorHandler=v,m>=d||w.paused?g?(nt.next=g,g=nt):(g=nt,y=nt,w.saturated()):(m++,u.call(o,nt.value,nt.worked))}function q(X){X&&p.release(X);var at=g;at&&m<=d?w.paused?m--:(y===g&&(y=null),g=at.next,at.next=null,u.call(o,at.value,at.worked),y===null&&w.empty()):--m===0&&w.drain()}function K(){g=null,y=null,w.drain=i}function W(){g=null,y=null,w.drain(),w.drain=i}function et(X){v=X}}function i(){}function r(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var o=this;this.worked=function(d,p){var g=o.callback,y=o.errorHandler,m=o.value;o.value=null,o.callback=i,o.errorHandler&&y(d,m),g.call(o.context,d,p),o.release(o)}}function l(o,u,d){typeof o==`function`&&(d=u,u=o,o=null);function p(E,_){u.call(this,E).then(function(j){_(null,j)},_)}var g=t(o,p,d),y=g.push,m=g.unshift;return g.push=v,g.unshift=w,g.drained=b,g;function v(E){var _=new Promise(function(j,O){y(E,function(A,M){if(A){O(A);return}j(M)})});return _.catch(i),_}function w(E){var _=new Promise(function(j,O){m(E,function(A,M){if(A){O(A);return}j(M)})});return _.catch(i),_}function b(){var E=new Promise(function(_){process.nextTick(function(){if(g.idle())_();else{var j=g.drain;g.drain=function(){typeof j==`function`&&j(),_(),g.drain=j}}})});return E}}return Zo.exports=t,Zo.exports.promise=l,Zo.exports}var yO=gO();const gb=fC(yO),Tn=`Stream-Next-Offset`,Gc=`Stream-Cursor`,Yc=`Stream-Up-To-Date`,Ln=`Stream-Closed`,$h=`Stream-Seq`,mO=`Stream-TTL`,SO=`Stream-Expires-At`,jS=`Producer-Id`,Wo=`Producer-Epoch`,BS=`Producer-Seq`,vO=`Producer-Expected-Seq`,bO=`Producer-Received-Seq`,Gh=`offset`,Po=`live`,wO=`stream-sse-data-encoding`;var Js=class yb extends Error{status;text;json;headers;constructor(t,i,r,l,o,u){super(u||`HTTP Error ${t} at ${o}: ${i??JSON.stringify(r)}`),this.url=o,this.name=`FetchError`,this.status=t,this.text=i,this.json=r,this.headers=l}static async fromResponse(t,i){const r=t.status,l=Object.fromEntries([...t.headers.entries()]);let o,u;const d=t.headers.get(`content-type`);if(!t.bodyUsed&&t.body!==null)if(d&&d.includes(`application/json`))try{u=await t.json()}catch{o=await t.text()}else o=await t.text();return new yb(r,o,u,l,i)}},yp=class extends Error{constructor(){super(`Fetch with backoff aborted`),this.name=`FetchBackoffAbortError`}},Wt=class zd extends Error{status;code;details;constructor(t,i,r,l){super(t),this.name=`DurableStreamError`,this.code=i,this.status=r,this.details=l}static async fromResponse(t,i){const r=t.status;let l;const o=t.headers.get(`content-type`);if(!t.bodyUsed&&t.body!==null)if(o&&o.includes(`application/json`))try{l=await t.json()}catch{l=await t.text()}else l=await t.text();const u=LS(r),d=`Durable stream error at ${i}: ${t.statusText||r}`;return new zd(d,u,r,l)}static fromFetchError(t){const i=LS(t.status);return new zd(t.message,i,t.status,t.json??t.text)}};function LS(n){switch(n){case 400:return`BAD_REQUEST`;case 401:return`UNAUTHORIZED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 409:return`CONFLICT_SEQ`;case 429:return`RATE_LIMITED`;case 503:return`BUSY`;default:return`UNKNOWN`}}var EO=class extends Error{constructor(){super(`Invalid stream options: missing required url parameter`),this.name=`MissingStreamUrlError`}},mb=class extends Wt{code=`STREAM_CLOSED`;status=409;streamClosed=!0;finalOffset;constructor(n,t){super(`Cannot append to closed stream`,`STREAM_CLOSED`,409,n),this.name=`StreamClosedError`,this.finalOffset=t}},CO=class extends Error{constructor(){super(`Invalid signal option. It must be an instance of AbortSignal.`),this.name=`InvalidSignalError`}};const xO=[429,503],mp={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function _O(n){if(!n)return 0;const t=Number(n);if(Number.isFinite(t)&&t>0)return t*1e3;const i=Date.parse(n);if(!isNaN(i)){const r=i-Date.now();return Math.max(0,Math.min(r,36e5))}return 0}function Sb(n,t=mp){const{initialDelay:i,maxDelay:r,multiplier:l,debug:o=!1,onFailedAttempt:u,maxRetries:d=1/0}=t;return async(...p)=>{const g=p[0],y=p[1];let m=i,v=0;for(;;)try{const w=await n(...p);if(w.ok)return w;throw await Js.fromResponse(w,g.toString())}catch(w){if(u?.(),y?.signal?.aborted)throw new yp;if(w instanceof Js&&!xO.includes(w.status)&&w.status>=400&&w.status<500)throw w;{if(v++,v>d)throw o&&console.log(`Max retries reached (${v}/${d}), giving up`),w;const b=w instanceof Js?_O(w.headers[`retry-after`]):0,E=Math.random()*m,_=Math.min(E,r),j=Math.max(b,_);if(o){const O=b>0?`server+client`:`client`;console.log(`Retry attempt #${v} after ${j}ms (${O}, serverMin=${b}ms, clientBackoff=${_}ms)`)}await new Promise(O=>setTimeout(O,j)),m=Math.min(m*l,r)}}}}const TO=[201,204,205];function AO(n){return async(...t)=>{const i=t[0],r=await n(...t);try{if(r.status<200||TO.includes(r.status))return r;const l=await r.arrayBuffer();return new Response(l,{status:r.status,statusText:r.statusText,headers:r.headers})}catch(l){throw t[1]?.signal?.aborted?new yp:new Js(r.status,void 0,void 0,Object.fromEntries([...r.headers.entries()]),i.toString(),l instanceof Error?l.message:typeof l==`string`?l:`failed to read body`)}}}function OO(n){return typeof Symbol<`u`&&typeof Symbol.asyncIterator==`symbol`&&typeof n[Symbol.asyncIterator]==`function`}function RO(n){if(typeof Symbol>`u`||typeof Symbol.asyncIterator!=`symbol`||typeof n[Symbol.asyncIterator]==`function`)return;const t=function(){const i=this.getReader();let r=!1,l=0;return{async next(){if(r)return{done:!0,value:void 0};l++;try{const{value:u,done:d}=await i.read();return d?(r=!0,i.releaseLock(),{done:!0,value:void 0}):{done:!1,value:u}}catch(u){r=!0;try{i.releaseLock()}catch{}throw u}finally{l--}},async return(u){if(l>0)throw new TypeError(`Cannot close a readable stream reader when it has pending read requests`);r=!0;const d=i.cancel(u);return i.releaseLock(),await d,{done:!0,value:void 0}},async throw(u){if(l>0)throw new TypeError(`Cannot close a readable stream reader when it has pending read requests`);r=!0;const d=i.cancel(u);throw i.releaseLock(),await d,u},[Symbol.asyncIterator](){return this}}};try{Object.defineProperty(n,Symbol.asyncIterator,{configurable:!0,writable:!0,value:t})}catch{return}try{Object.defineProperty(n,`values`,{configurable:!0,writable:!0,value:t})}catch{}}function Yh(n){return OO(n)||RO(n),n}async function*IS(n,t){const i=n.getReader(),r=new TextDecoder;let l=``,o={data:[]};try{for(;!t?.aborted;){const{done:d,value:p}=await i.read();if(d)break;l+=r.decode(p,{stream:!0}),l=l.replace(/\r\n/g,`
+`).replace(/\r/g,`
+`);const g=l.split(`
+`);l=g.pop()??``;for(const y of g)if(y===``){if(o.type&&o.data.length>0){const m=o.data.join(`
+`);if(o.type===`data`)yield{type:`data`,data:m};else if(o.type===`control`)try{const v=JSON.parse(m);yield{type:`control`,streamNextOffset:v.streamNextOffset,streamCursor:v.streamCursor,upToDate:v.upToDate,streamClosed:v.streamClosed}}catch(v){const w=m.length>100?m.slice(0,100)+`...`:m;throw new Wt(`Failed to parse SSE control event: ${v instanceof Error?v.message:String(v)}. Data: ${w}`,`PARSE_ERROR`)}}o={data:[]}}else if(y.startsWith(`event:`)){const m=y.slice(6);o.type=m.startsWith(` `)?m.slice(1):m}else if(y.startsWith(`data:`)){const m=y.slice(5);o.data.push(m.startsWith(` `)?m.slice(1):m)}}const u=r.decode();if(u&&(l+=u),l&&o.type&&o.data.length>0){const d=o.data.join(`
+`);if(o.type===`data`)yield{type:`data`,data:d};else if(o.type===`control`)try{const p=JSON.parse(d);yield{type:`control`,streamNextOffset:p.streamNextOffset,streamCursor:p.streamCursor,upToDate:p.upToDate,streamClosed:p.streamClosed}}catch(p){const g=d.length>100?d.slice(0,100)+`...`:d;throw new Wt(`Failed to parse SSE control event: ${p instanceof Error?p.message:String(p)}. Data: ${g}`,`PARSE_ERROR`)}}}finally{i.releaseLock()}}var Sp=class{shouldContinueLive(n,t){return!(n&&this.upToDate||t===!1||this.streamClosed)}},vb=class Nd extends Sp{offset;cursor;upToDate;streamClosed;constructor(t){super(),this.offset=t.offset,this.cursor=t.cursor,this.upToDate=t.upToDate,this.streamClosed=t.streamClosed}shouldUseSse(){return!1}withResponseMetadata(t){return new Nd({offset:t.offset??this.offset,cursor:t.cursor??this.cursor,upToDate:t.upToDate,streamClosed:this.streamClosed||t.streamClosed})}withSSEControl(t){const i=this.streamClosed||(t.streamClosed??!1);return new Nd({offset:t.streamNextOffset,cursor:t.streamCursor||this.cursor,upToDate:t.streamClosed??!1?!0:t.upToDate??this.upToDate,streamClosed:i})}pause(){return new vp(this)}},Fh=class Er extends Sp{offset;cursor;upToDate;streamClosed;consecutiveShortConnections;connectionStartTime;constructor(t){super(),this.offset=t.offset,this.cursor=t.cursor,this.upToDate=t.upToDate,this.streamClosed=t.streamClosed,this.consecutiveShortConnections=t.consecutiveShortConnections??0,this.connectionStartTime=t.connectionStartTime}shouldUseSse(){return!0}withResponseMetadata(t){return new Er({offset:t.offset??this.offset,cursor:t.cursor??this.cursor,upToDate:t.upToDate,streamClosed:this.streamClosed||t.streamClosed,consecutiveShortConnections:this.consecutiveShortConnections,connectionStartTime:this.connectionStartTime})}withSSEControl(t){const i=this.streamClosed||(t.streamClosed??!1);return new Er({offset:t.streamNextOffset,cursor:t.streamCursor||this.cursor,upToDate:t.streamClosed??!1?!0:t.upToDate??this.upToDate,streamClosed:i,consecutiveShortConnections:this.consecutiveShortConnections,connectionStartTime:this.connectionStartTime})}startConnection(t){return new Er({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed,consecutiveShortConnections:this.consecutiveShortConnections,connectionStartTime:t})}handleConnectionEnd(t,i,r){if(this.connectionStartTime===void 0)return{action:`healthy`,state:this};const l=t-this.connectionStartTime;if(l=r.maxShortConnections?{action:`fallback`,state:new vb({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed})}:{action:`reconnect`,state:new Er({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed,consecutiveShortConnections:o,connectionStartTime:this.connectionStartTime}),backoffAttempt:o}}return l>=r.minConnectionDuration?{action:`healthy`,state:new Er({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed,consecutiveShortConnections:0,connectionStartTime:this.connectionStartTime})}:{action:`healthy`,state:this}}pause(){return new vp(this)}},vp=class jd extends Sp{#t;constructor(t){super(),this.#t=t}get offset(){return this.#t.offset}get cursor(){return this.#t.cursor}get upToDate(){return this.#t.upToDate}get streamClosed(){return this.#t.streamClosed}shouldUseSse(){return this.#t.shouldUseSse()}withResponseMetadata(t){const i=this.#t.withResponseMetadata(t);return new jd(i)}withSSEControl(t){const i=this.#t.withSSEControl(t);return new jd(i)}pause(){return this}resume(){return{state:this.#t,justResumed:!0}}};const HS=`PAUSE_STREAM`;var DO=class{url;contentType;live;startOffset;#t;#e;#n;#s;#a;#i;#c;#l;#p;#d;#h;#f;#g;#y=!1;#x=null;#o=`active`;#u;#w;#m;#S;#v;#E;#O;constructor(n){this.url=n.url,this.contentType=n.contentType,this.live=n.live,this.startOffset=n.startOffset;const t={offset:n.initialOffset,cursor:n.initialCursor,upToDate:n.initialUpToDate,streamClosed:n.initialStreamClosed};this.#i=n.startSSE?new Fh(t):new vb(t),this.#t=n.firstResponse.headers,this.#e=n.firstResponse.status,this.#n=n.firstResponse.statusText,this.#s=n.firstResponse.ok,this.#a=!1,this.#c=n.isJsonMode,this.#l=n.abortController,this.#p=n.fetchNext,this.#d=n.startSSE,this.#v={minConnectionDuration:n.sseResilience?.minConnectionDuration??1e3,maxShortConnections:n.sseResilience?.maxShortConnections??3,backoffBaseDelay:n.sseResilience?.backoffBaseDelay??100,backoffMaxDelay:n.sseResilience?.backoffMaxDelay??5e3,logWarnings:n.sseResilience?.logWarnings??!0},this.#E=n.encoding,this.#g=new Promise((i,r)=>{this.#h=i,this.#f=r}),this.#O=this.#I(n.firstResponse),this.#l.signal.addEventListener(`abort`,()=>{this.#u?.abort(this.#l.signal.reason),this.#S?.(),this.#m=void 0,this.#S=void 0},{once:!0}),this.#R()}#R(){if(typeof document==`object`&&typeof document.hidden==`boolean`&&typeof document.addEventListener==`function`){const n=()=>{document.hidden?this.#D():this.#T()};document.addEventListener(`visibilitychange`,n),this.#w=()=>{typeof document==`object`&&document.removeEventListener(`visibilitychange`,n)},document.hidden&&this.#D()}}#D(){this.#o===`active`&&(this.#o=`pause-requested`,this.#i=this.#i.pause(),this.#m=new Promise(n=>{this.#S=n}),this.#u?.abort(HS))}#T(){if(this.#o===`paused`||this.#o===`pause-requested`){if(this.#l.signal.aborted)return;this.#i instanceof vp&&(this.#i=this.#i.resume().state),this.#o=`active`,this.#S?.(),this.#m=void 0,this.#S=void 0}}get headers(){return this.#t}get status(){return this.#e}get statusText(){return this.#n}get ok(){return this.#s}get isLoading(){return this.#a}get offset(){return this.#i.offset}get cursor(){return this.#i.cursor}get upToDate(){return this.#i.upToDate}get streamClosed(){return this.#i.streamClosed}#A(){if(!this.#c)throw new Wt(`JSON methods are only valid for JSON-mode streams. Content-Type is "${this.contentType}" and json hint was not set.`,`BAD_REQUEST`)}#r(){this.#w?.(),this.#h()}#_(n){this.#w?.(),this.#f(n)}#b(n){if(this.#x!==null)throw new Wt(`Cannot call ${n}() - this StreamResponse is already being consumed via ${this.#x}()`,`ALREADY_CONSUMED`);this.#x=n}#M(){return this.#i.shouldContinueLive(this.#y,this.live)}#j(n){this.#i=this.#i.withResponseMetadata({offset:n.headers.get(Tn)||void 0,cursor:n.headers.get(Gc)||void 0,upToDate:n.headers.has(Yc),streamClosed:n.headers.get(Ln)?.toLowerCase()===`true`}),this.#t=n.headers,this.#e=n.status,this.#n=n.statusText,this.#s=n.ok}#U(n){this.#i=this.#i.withSSEControl(n)}#z(){this.#i instanceof Fh||(this.#i=new Fh({offset:this.#i.offset,cursor:this.#i.cursor,upToDate:this.#i.upToDate,streamClosed:this.#i.streamClosed})),this.#i=this.#i.startConnection(Date.now())}async#k(){if(!this.#i.shouldUseSse()||!this.#M()||!this.#d)return null;const n=this.#i.handleConnectionEnd(Date.now(),this.#l.signal.aborted,this.#v);if(this.#i=n.state,n.action===`fallback`)return this.#v.logWarnings&&console.warn(`[Durable Streams] SSE connections are closing immediately (possibly due to proxy buffering or misconfiguration). Falling back to long polling. Your proxy must support streaming SSE responses (not buffer the complete response). Configuration: Nginx add 'X-Accel-Buffering: no', Caddy add 'flush_interval -1' to reverse_proxy.`),null;if(n.action===`reconnect`){const i=Math.min(this.#v.backoffMaxDelay,this.#v.backoffBaseDelay*Math.pow(2,n.backoffAttempt)),r=Math.floor(Math.random()*i);await new Promise(l=>setTimeout(l,r))}this.#z(),this.#u=new AbortController;const t=await this.#d(this.offset,this.cursor,this.#u.signal);return t.body?IS(t.body,this.#u.signal):null}async#B(n){const{done:t,value:i}=await n.next();if(t){try{const r=await this.#k();if(r)return{type:`continue`,newIterator:r}}catch(r){return{type:`error`,error:r instanceof Error?r:new Error(`SSE reconnection failed`)}}return{type:`closed`}}return i.type===`data`?this.#L(i.data,n):(this.#U(i),i.upToDate?{type:`response`,response:kO(``,i.streamNextOffset,i.streamCursor,!0,i.streamClosed??!1,this.contentType,this.#E)}:{type:`continue`})}async#L(n,t){const i=[n];for(;;){const{done:r,value:l}=await t.next();if(r){const o=Bd(i,this.offset,this.cursor,this.upToDate,this.streamClosed,this.contentType,this.#E,this.#c);try{const u=await this.#k();return{type:`response`,response:o,newIterator:u??void 0}}catch(u){return{type:`error`,error:u instanceof Error?u:new Error(`SSE reconnection failed`)}}}if(l.type===`control`)return this.#U(l),{type:`response`,response:Bd(i,l.streamNextOffset,l.streamCursor,l.upToDate??!1,l.streamClosed??!1,this.contentType,this.#E,this.#c)};i.push(l.data)}}#I(n){let t=!1,i=null;return new ReadableStream({pull:async r=>{try{if(!t)if(t=!0,(n.headers.get(`content-type`)?.includes(`text/event-stream`)??!1)&&n.body)this.#z(),this.#u=new AbortController,i=IS(n.body,this.#u.signal);else{if(r.enqueue(n),this.upToDate&&!this.#M()){this.#r(),r.close();return}return}if(i){if(this.#o===`pause-requested`||this.#o===`paused`){if(this.#o=`paused`,this.#m&&await this.#m,this.#l.signal.aborted){this.#r(),r.close();return}const l=await this.#k();if(l)i=l;else{this.#r(),r.close();return}}for(;;){const l=await this.#B(i);switch(l.type){case`response`:l.newIterator&&(i=l.newIterator),r.enqueue(l.response);return;case`closed`:this.#r(),r.close();return;case`error`:this.#_(l.error),r.error(l.error);return;case`continue`:l.newIterator&&(i=l.newIterator);continue}}}if(this.#M()){let l=!1;if(this.#o===`pause-requested`||this.#o===`paused`){if(this.#o=`paused`,this.#m&&await this.#m,this.#l.signal.aborted){this.#r(),r.close();return}l=!0}if(this.#l.signal.aborted){this.#r(),r.close();return}this.#u=new AbortController;const o=await this.#p(this.offset,this.cursor,this.#u.signal,l);this.#j(o),r.enqueue(o);return}this.#r(),r.close()}catch(l){if(this.#u?.signal.aborted&&this.#u.signal.reason===HS){this.#o===`pause-requested`&&(this.#o=`paused`);return}this.#l.signal.aborted?(this.#r(),r.close()):(this.#_(l instanceof Error?l:new Error(String(l))),r.error(l))}},cancel:()=>{this.#l.abort(),this.#w?.(),this.#r()}})}#C(){return this.#O.getReader()}async body(){this.#b(`body`),this.#y=!0;const n=this.#C(),t=[];try{let r=await n.read();for(;!r.done;){const l=this.upToDate,o=await r.value.blob();if(o.size>0&&t.push(o),l)break;r=await n.read()}}finally{n.releaseLock()}if(this.#r(),t.length===0)return new Uint8Array(0);if(t.length===1)return new Uint8Array(await t[0].arrayBuffer());const i=new Blob(t);return new Uint8Array(await i.arrayBuffer())}async json(){this.#b(`json`),this.#A(),this.#y=!0;const n=this.#C(),t=[];try{let i=await n.read();for(;!i.done;){const r=this.upToDate,o=(await i.value.text()).trim()||`[]`;let u;try{u=JSON.parse(o)}catch(d){const p=o.length>100?o.slice(0,100)+`...`:o;throw new Wt(`Failed to parse JSON response: ${d instanceof Error?d.message:String(d)}. Data: ${p}`,`PARSE_ERROR`)}if(Array.isArray(u)?t.push(...u):t.push(u),r)break;i=await n.read()}}finally{n.releaseLock()}return this.#r(),t}async text(){this.#b(`text`),this.#y=!0;const n=this.#C(),t=[];try{let i=await n.read();for(;!i.done;){const r=this.upToDate,l=await i.value.text();if(l&&t.push(l),r)break;i=await n.read()}}finally{n.releaseLock()}return this.#r(),t.join(``)}#N(){const{readable:n,writable:t}=new TransformStream,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done;){const o=this.upToDate,u=l.value.body;if(u&&await u.pipeTo(t,{preventClose:!0,preventAbort:!0,preventCancel:!0}),o&&!this.#M())break;l=await i.read()}await t.close(),this.#r()}catch(l){if(this.#l.signal.aborted){try{await t.close()}catch{}this.#r()}else{try{await t.abort(l)}catch{}this.#_(l instanceof Error?l:new Error(String(l)))}}finally{i.releaseLock()}})(),n}bodyStream(){return this.#b(`bodyStream`),Yh(this.#N())}jsonStream(){this.#b(`jsonStream`),this.#A();const n=this.#C();let t=[];const i=new ReadableStream({pull:async r=>{if(t.length>0){r.enqueue(t.shift());return}let l=await n.read();for(;!l.done;){const d=(await l.value.text()).trim()||`[]`;let p;try{p=JSON.parse(d)}catch(g){const y=d.length>100?d.slice(0,100)+`...`:d;throw new Wt(`Failed to parse JSON response: ${g instanceof Error?g.message:String(g)}. Data: ${y}`,`PARSE_ERROR`)}if(t=Array.isArray(p)?p:[p],t.length>0){r.enqueue(t.shift());return}l=await n.read()}this.#r(),r.close()},cancel:()=>{n.releaseLock(),this.cancel()}});return Yh(i)}textStream(){this.#b(`textStream`);const n=new TextDecoder,t=this.#N().pipeThrough(new TransformStream({transform(i,r){r.enqueue(n.decode(i,{stream:!0}))},flush(i){const r=n.decode();r&&i.enqueue(r)}}));return Yh(t)}subscribeJson(n){this.#b(`subscribeJson`),this.#A();const t=new AbortController,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done&&!t.signal.aborted;){const o=l.value,{offset:u,cursor:d,upToDate:p,streamClosed:g}=Qh(o,this.offset,this.cursor,this.streamClosed),m=(await o.text()).trim()||`[]`;let v;try{v=JSON.parse(m)}catch(b){const E=m.length>100?m.slice(0,100)+`...`:m;throw new Wt(`Failed to parse JSON response: ${b instanceof Error?b.message:String(b)}. Data: ${E}`,`PARSE_ERROR`)}const w=Array.isArray(v)?v:[v];await n({items:w,offset:u,cursor:d,upToDate:p,streamClosed:g}),l=await i.read()}this.#r()}catch(l){const o=t.signal.aborted,u=l instanceof TypeError&&String(l).includes(`Body`);!o&&!u?this.#_(l instanceof Error?l:new Error(String(l))):this.#r()}finally{i.releaseLock()}})(),()=>{t.abort(),this.cancel()}}subscribeBytes(n){this.#b(`subscribeBytes`);const t=new AbortController,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done&&!t.signal.aborted;){const o=l.value,{offset:u,cursor:d,upToDate:p,streamClosed:g}=Qh(o,this.offset,this.cursor,this.streamClosed),y=await o.arrayBuffer();await n({data:new Uint8Array(y),offset:u,cursor:d,upToDate:p,streamClosed:g}),l=await i.read()}this.#r()}catch(l){const o=t.signal.aborted,u=l instanceof TypeError&&String(l).includes(`Body`);!o&&!u?this.#_(l instanceof Error?l:new Error(String(l))):this.#r()}finally{i.releaseLock()}})(),()=>{t.abort(),this.cancel()}}subscribeText(n){this.#b(`subscribeText`);const t=new AbortController,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done&&!t.signal.aborted;){const o=l.value,{offset:u,cursor:d,upToDate:p,streamClosed:g}=Qh(o,this.offset,this.cursor,this.streamClosed),y=await o.text();await n({text:y,offset:u,cursor:d,upToDate:p,streamClosed:g}),l=await i.read()}this.#r()}catch(l){const o=t.signal.aborted,u=l instanceof TypeError&&String(l).includes(`Body`);!o&&!u?this.#_(l instanceof Error?l:new Error(String(l))):this.#r()}finally{i.releaseLock()}})(),()=>{t.abort(),this.cancel()}}cancel(n){this.#l.abort(n),this.#w?.(),this.#r()}get closed(){return this.#g}};function Qh(n,t,i,r){const l=n.headers.get(Tn),o=n.headers.get(Gc),u=n.headers.has(Yc),d=n.headers.get(Ln)?.toLowerCase()===`true`;return{offset:l??t,cursor:o??i,upToDate:u,streamClosed:d||r}}function MO(n){const t=n.replace(/[\n\r]/g,``);if(t.length===0)return new Uint8Array(0);if(t.length%4!==0)throw new Wt(`Invalid base64 data: length ${t.length} is not a multiple of 4`,`PARSE_ERROR`);try{if(typeof Buffer<`u`)return new Uint8Array(Buffer.from(t,`base64`));{const i=atob(t),r=new Uint8Array(i.length);for(let l=0;lm.length>0).map(m=>MO(m));if(y.length===0)g=new ArrayBuffer(0);else if(y.length===1){const m=y[0];g=m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength)}else{const m=y.reduce((b,E)=>b+E.length,0),v=new Uint8Array(m);let w=0;for(const b of y)v.set(b,w),w+=b.length;g=v.buffer}}else if(d){const y=[];for(const m of n){const v=m.trim();if(v.length!==0)if(v.startsWith(`[`)&&v.endsWith(`]`)){const w=v.slice(1,-1).trim();w.length>0&&y.push(w)}else y.push(v)}g=`[${y.join(`,`)}]`}else g=n.join(``);return new Response(g,{status:200,headers:p})}async function nl(n){const t={};if(!n)return t;for(const[i,r]of Object.entries(n))typeof r==`function`?t[i]=await r():t[i]=r;return t}async function hs(n,t,i){const r=n.status;if(r===404)throw new Wt(`Stream not found: ${t}`,`NOT_FOUND`,404);if(r===409){if(n.headers.get(Ln)?.toLowerCase()===`true`){const d=n.headers.get(Tn)??void 0;throw new mb(t,d)}const o=i?.operation===`create`?`Stream already exists: ${t}`:`Sequence conflict: seq is lower than last appended`,u=i?.operation===`create`?`CONFLICT_EXISTS`:`CONFLICT_SEQ`;throw new Wt(o,u,409)}throw r===400?new Wt(`Bad request (possibly content-type mismatch)`,`BAD_REQUEST`,400):await Wt.fromResponse(n,t)}async function fc(n){const t={};if(!n)return t;for(const[i,r]of Object.entries(n))r!==void 0&&(typeof r==`function`?t[i]=await r():t[i]=r);return t}const qS=new Set;function UO(){if(!(typeof process>`u`))return`production`}function zO(){return typeof globalThis.window<`u`}function NO(){if(typeof globalThis.window<`u`&&typeof globalThis.window.location<`u`)return globalThis.window.location.href}function jO(n){try{return new URL(n)}catch{const t=NO();if(t)try{return new URL(n,t)}catch{return}return}}function bb(n,t){if(t===!1||UO()===`test`||!zO()||typeof console>`u`||typeof console.warn!=`function`)return;const r=n instanceof URL?n.toString():n,l=jO(r);l&&l.protocol===`http:`&&(qS.has(l.origin)||(qS.add(l.origin),console.warn(`[DurableStream] Using HTTP (not HTTPS) typically limits browsers to ~6 concurrent connections per origin under HTTP/1.1. This can cause slow streams and app freezes with multiple active streams. Use HTTPS for HTTP/2 support. See https://electric-sql.com/r/electric-http2 for more information.`)))}async function BO(n){if(!n.url)throw new Wt(`Invalid stream options: missing required url parameter`,`BAD_REQUEST`);let t=n.headers,i=n.params;for(;;)try{return await LO({...n,headers:t,params:i})}catch(r){if(n.onError){const l=await n.onError(r instanceof Error?r:new Error(String(r)));if(l===void 0)throw r;l.params&&(i={...i,...l.params}),l.headers&&(t={...t,...l.headers});continue}throw r}}async function LO(n){const t=n.url instanceof URL?n.url.toString():n.url;bb(t,n.warnOnHttp);const i=new URL(t),r=n.offset??`-1`;i.searchParams.set(Gh,r);const l=n.live??!0;(l===`long-poll`||l===`sse`)&&i.searchParams.set(Po,l);const o=await fc(n.params);for(const[q,K]of Object.entries(o))i.searchParams.set(q,K);const u=await nl(n.headers),d=new AbortController;n.signal&&n.signal.addEventListener(`abort`,()=>d.abort(n.signal?.reason),{once:!0});const p=n.fetch??((...q)=>fetch(...q)),g=n.backoffOptions??mp,y=Sb(p,g);let m;try{m=await y(i.toString(),{method:`GET`,headers:u,signal:d.signal})}catch(q){throw q instanceof yp?new Wt(`Stream request was aborted`,`UNKNOWN`):q}const v=m.headers.get(`content-type`)??void 0,w=m.headers.get(Tn)??r,b=m.headers.get(Gc)??void 0,E=m.headers.has(Yc),_=m.headers.get(Ln)?.toLowerCase()===`true`,j=n.json===!0||(v?.includes(`application/json`)??!1),A=m.headers.get(wO)===`base64`?`base64`:void 0,M=async(q,K,W,et)=>{const X=new URL(t);X.searchParams.set(Gh,q),et||(l===`sse`?X.searchParams.set(Po,`sse`):(l===!0||l===`long-poll`)&&X.searchParams.set(Po,`long-poll`)),K&&X.searchParams.set(`cursor`,K);const at=await fc(n.params);for(const[Lt,dt]of Object.entries(at))X.searchParams.set(Lt,dt);const nt=await nl(n.headers),bt=await y(X.toString(),{method:`GET`,headers:nt,signal:W});return bt.ok||await hs(bt,t),bt},G=l===`sse`?async(q,K,W)=>{const et=new URL(t);et.searchParams.set(Gh,q),et.searchParams.set(Po,`sse`),K&&et.searchParams.set(`cursor`,K);const X=await fc(n.params);for(const[bt,Lt]of Object.entries(X))et.searchParams.set(bt,Lt);const at=await nl(n.headers),nt=await y(et.toString(),{method:`GET`,headers:at,signal:W});return nt.ok||await hs(nt,t),nt}:void 0;return new DO({url:t,contentType:v,live:l,startOffset:r,isJsonMode:j,initialOffset:w,initialCursor:b,initialUpToDate:E,initialStreamClosed:_,firstResponse:m,abortController:d,fetchNext:M,startSSE:G,sseResilience:n.sseResilience,encoding:A})}var KS=class extends Error{currentEpoch;constructor(n){super(`Producer epoch is stale. Current server epoch: ${n}. Call restart() or create a new producer with a higher epoch.`),this.name=`StaleEpochError`,this.currentEpoch=n}},IO=class extends Error{expectedSeq;receivedSeq;constructor(n,t){super(`Producer sequence gap: expected ${n}, received ${t}`),this.name=`SequenceGapError`,this.expectedSeq=n,this.receivedSeq=t}};function VS(n){return n?n.split(`;`)[0].trim().toLowerCase():``}var wb=class{#t;#e;#n;#s=0;#a;#i;#c;#l;#p;#d;#h=[];#f=0;#g=null;#y;#x;#o=!1;#u=null;#w;#m;#S=new Map;constructor(n,t,i){const r=i?.epoch??0,l=i?.maxBatchBytes??1024*1024,o=i?.maxInFlight??5,u=i?.lingerMs??5;if(r<0)throw new Error(`epoch must be >= 0`);if(l<=0)throw new Error(`maxBatchBytes must be > 0`);if(o<=0)throw new Error(`maxInFlight must be > 0`);if(u<0)throw new Error(`lingerMs must be >= 0`);this.#t=n,this.#e=t,this.#n=r,this.#a=i?.autoClaim??!1,this.#i=l,this.#c=u,this.#p=i?.signal,this.#d=i?.onError,this.#l=i?.fetch??((...d)=>fetch(...d)),this.#x=o,this.#m=!this.#a,this.#y=gb.promise(this.#O.bind(this),this.#x),this.#p&&this.#p.addEventListener(`abort`,()=>{this.#A(new Wt(`Producer aborted`,`ALREADY_CLOSED`,void 0,void 0))},{once:!0})}append(n){if(this.#o)throw new Wt(`Producer is closed`,`ALREADY_CLOSED`,void 0,void 0);let t;if(typeof n==`string`)t=new TextEncoder().encode(n);else if(n instanceof Uint8Array)t=n;else throw new Wt(`append() requires string or Uint8Array. For objects, use JSON.stringify().`,`BAD_REQUEST`,400,void 0);this.#h.push({body:t}),this.#f+=t.length,this.#f>=this.#i?this.#E():this.#g||(this.#g=setTimeout(()=>{this.#g=null,this.#h.length>0&&this.#E()},this.#c))}async flush(){this.#g&&(clearTimeout(this.#g),this.#g=null),this.#h.length>0&&this.#E(),await this.#y.drained()}async detach(){if(!this.#o){this.#o=!0;try{await this.flush()}catch{}}}async close(n){if(this.#o){if(this.#u)return this.#u;await this.flush();const i=await this.#v(this.#w);return this.#u=i,i}this.#o=!0,this.#w=n,await this.flush();const t=await this.#v(n);return this.#u=t,t}async#v(n){const t=this.#t.contentType??`application/octet-stream`,i=VS(t)===`application/json`;let r;if(n!==void 0){const g=typeof n==`string`?new TextEncoder().encode(n):n;i?r=`[${new TextDecoder().decode(g)}]`:r=g}const l=this.#s,u={...await this.#t.resolveHeaders(),"content-type":t,[jS]:this.#e,[Wo]:this.#n.toString(),[BS]:l.toString(),[Ln]:`true`},d=await this.#l(this.#t.url,{method:`POST`,headers:u,body:r,signal:this.#p});if(d.status===204)return this.#s=l+1,{finalOffset:d.headers.get(Tn)??``};if(d.status===200)return this.#s=l+1,{finalOffset:d.headers.get(Tn)??``};if(d.status===403){const g=d.headers.get(Wo),y=g?parseInt(g,10):this.#n;if(this.#a){const m=y+1;return this.#n=m,this.#s=0,this.#v(n)}throw new KS(y)}throw await Js.fromResponse(d,this.#t.url)}async restart(){await this.flush(),this.#n++,this.#s=0}get epoch(){return this.#n}get nextSeq(){return this.#s}get pendingCount(){return this.#h.length}get inFlightCount(){return this.#y.length()}#E(){if(this.#h.length===0)return;const n=this.#h,t=this.#s;this.#h=[],this.#f=0,this.#s++,this.#a&&!this.#m&&this.#y.length()>0?this.#y.drained().then(()=>{this.#y.push({batch:n,seq:t}).catch(()=>{})}):this.#y.push({batch:n,seq:t}).catch(()=>{})}async#O(n){const{batch:t,seq:i}=n,r=this.#n;try{await this.#T(t,i,r),this.#m||(this.#m=!0),this.#R(r,i,void 0)}catch(l){throw this.#R(r,i,l),this.#d&&this.#d(l),l}}#R(n,t,i){let r=this.#S.get(n);r||(r=new Map,this.#S.set(n,r));const l=r.get(t);if(l){l.resolved=!0,l.error=i;for(const u of l.waiters)u(i);l.waiters=[]}else r.set(t,{resolved:!0,error:i,waiters:[]});const o=t-this.#x*3;if(o>0)for(const u of r.keys())u{const u=d=>{d?o(d):l()};r?r.waiters.push(u):i.set(t,{resolved:!1,waiters:[u]})})}async#T(n,t,i){const r=this.#t.contentType??`application/octet-stream`,l=VS(r)===`application/json`;let o;if(l)o=`[${n.map(v=>new TextDecoder().decode(v.body)).join(`,`)}]`;else{const m=n.reduce((b,E)=>b+E.body.length,0),v=new Uint8Array(m);let w=0;for(const b of n)v.set(b.body,w),w+=b.body.length;o=v}const u=this.#t.url,p={...await this.#t.resolveHeaders(),"content-type":r,[jS]:this.#e,[Wo]:i.toString(),[BS]:t.toString()},g=await this.#l(u,{method:`POST`,headers:p,body:o,signal:this.#p});if(g.status===204)return{offset:``,duplicate:!0};if(g.status===200)return{offset:g.headers.get(Tn)??``,duplicate:!1};if(g.status===403){const m=g.headers.get(Wo),v=m?parseInt(m,10):i;if(this.#a){const w=v+1;return this.#n=w,this.#s=1,this.#T(n,0,w)}throw new KS(v)}if(g.status===409){const m=g.headers.get(vO),v=m?parseInt(m,10):0;if(v0&&this.#d(n),this.#h=[],this.#f=0,this.#g&&(clearTimeout(this.#g),this.#g=null)}};function Xh(n){return n?n.split(`;`)[0].trim().toLowerCase():``}function HO(n){return n!=null&&typeof n.then==`function`}var Ys=class Wa{url;contentType;#t;#e;#n;#s;#a;#i;#c=[];constructor(t){VO(t);const i=t.url instanceof URL?t.url.toString():t.url;this.url=i,this.#t={...t,url:i},this.#s=t.onError,t.contentType&&(this.contentType=t.contentType),this.#a=t.batching!==!1,this.#a&&(this.#i=gb.promise(this.#d.bind(this),1)),this.#n=t.fetch??((...o)=>fetch(...o));const r={...t.backoffOptions??mp},l=Sb(this.#n,r);this.#e=AO(l)}static async create(t){const i=new Wa(t);return await i.create({contentType:t.contentType,ttlSeconds:t.ttlSeconds,expiresAt:t.expiresAt,body:t.body,closed:t.closed}),i}static async connect(t){const i=new Wa(t);return await i.head(),i}static async head(t){return new Wa(t).head()}static async delete(t){return new Wa(t).delete()}async head(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=await this.#n(r.toString(),{method:`HEAD`,headers:i,signal:t?.signal??this.#t.signal});if(!l.ok){if(l.status===404)return{exists:!1};await hs(l,this.url)}const o=l.headers.get(`content-type`)??void 0,u=l.headers.get(Tn)??void 0,d=l.headers.get(`etag`)??void 0,p=l.headers.get(`cache-control`)??void 0,g=l.headers.get(Ln)?.toLowerCase()===`true`;return o&&(this.contentType=o),{exists:!0,contentType:o,offset:u,etag:d,cacheControl:p,streamClosed:g}}async create(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=t?.contentType??this.#t.contentType;l&&(i[`content-type`]=l),t?.ttlSeconds!==void 0&&(i[mO]=String(t.ttlSeconds)),t?.expiresAt&&(i[SO]=t.expiresAt),t?.closed&&(i[Ln]=`true`);const o=qO(t?.body),u=await this.#e(r.toString(),{method:`PUT`,headers:i,body:o,signal:this.#t.signal});u.ok||await hs(u,this.url,{operation:`create`});const d=u.headers.get(`content-type`);return d?this.contentType=d:l&&(this.contentType=l),this}async delete(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=await this.#e(r.toString(),{method:`DELETE`,headers:i,signal:t?.signal??this.#t.signal});l.ok||await hs(l,this.url)}async close(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=t?.contentType??this.#t.contentType??this.contentType;l&&(i[`content-type`]=l),i[Ln]=`true`;let o;t?.body!==void 0&&(Xh(l)===`application/json`?o=`[${typeof t.body==`string`?t.body:new TextDecoder().decode(t.body)}]`:o=(typeof t.body==`string`,t.body));const u=await this.#e(r.toString(),{method:`POST`,headers:i,body:o,signal:t?.signal??this.#t.signal});if(u.status===409&&u.headers.get(Ln)?.toLowerCase()===`true`){const g=u.headers.get(Tn)??void 0;throw new mb(this.url,g)}return u.ok||await hs(u,this.url),{finalOffset:u.headers.get(Tn)??``}}async append(t,i){const r=HO(t)?await t:t;return this.#a&&this.#i?this.#p(r,i):this.#l(r,i)}async#l(t,i){const{requestHeaders:r,fetchUrl:l}=await this.#f(),o=i?.contentType??this.#t.contentType??this.contentType;o&&(r[`content-type`]=o),i?.seq&&(r[$h]=i.seq);const u=Xh(o)===`application/json`;let d;u?d=`[${typeof t==`string`?t:new TextDecoder().decode(t)}]`:typeof t==`string`?d=t:d=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);const p=await this.#e(l.toString(),{method:`POST`,headers:r,body:d,signal:i?.signal??this.#t.signal});p.ok||await hs(p,this.url)}async#p(t,i){return new Promise((r,l)=>{if(this.#c.push({data:t,seq:i?.seq,contentType:i?.contentType,signal:i?.signal,resolve:r,reject:l}),this.#i.idle()){const o=this.#c.splice(0);this.#i.push(o).catch(u=>{for(const d of o)d.reject(u)})}})}async#d(t){try{await this.#h(t);for(const i of t)i.resolve();if(this.#c.length>0){const i=this.#c.splice(0);this.#i.push(i).catch(r=>{for(const l of i)l.reject(r)})}}catch(i){for(const r of t)r.reject(i);for(const r of this.#c)r.reject(i);throw this.#c=[],i}}async#h(t){if(t.length===0)return;const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=t[0]?.contentType??this.#t.contentType??this.contentType;l&&(i[`content-type`]=l);let o;for(let m=t.length-1;m>=0;m--)if(t[m].seq!==void 0){o=t[m].seq;break}o&&(i[$h]=o);const u=Xh(l)===`application/json`;let d;if(u)d=`[${t.map(v=>typeof v.data==`string`?v.data:new TextDecoder().decode(v.data)).join(`,`)}]`;else{const m=t.some(w=>w.data instanceof Uint8Array),v=t.some(w=>typeof w.data==`string`);if(m&&!v){const w=t.map(j=>j.data),b=w.reduce((j,O)=>j+O.length,0),E=new Uint8Array(b);let _=0;for(const j of w)E.set(j,_),_+=j.length;d=E}else if(v&&!m)d=t.map(w=>w.data).join(``);else{const w=new TextEncoder,b=t.map(O=>typeof O.data==`string`?w.encode(O.data):O.data),E=b.reduce((O,A)=>O+A.length,0),_=new Uint8Array(E);let j=0;for(const O of b)_.set(O,j),j+=O.length;d=_}}const p=[];this.#t.signal&&p.push(this.#t.signal);for(const m of t)m.signal&&p.push(m.signal);const g=p.length>0?AbortSignal.any(p):void 0,y=await this.#e(r.toString(),{method:`POST`,headers:i,body:d,signal:g});y.ok||await hs(y,this.url)}async appendStream(t,i){const{requestHeaders:r,fetchUrl:l}=await this.#f(),o=i?.contentType??this.#t.contentType??this.contentType;o&&(r[`content-type`]=o),i?.seq&&(r[$h]=i.seq);const u=KO(t),d=await this.#e(l.toString(),{method:`POST`,headers:r,body:u,duplex:`half`,signal:i?.signal??this.#t.signal});d.ok||await hs(d,this.url)}writable(t){const i=t?.producerId??`writable-${crypto.randomUUID().slice(0,8)}`;let r=null;const l=new wb(this,i,{autoClaim:!0,lingerMs:t?.lingerMs,maxBatchBytes:t?.maxBatchBytes,onError:o=>{r||(r=o),t?.onError?.(o)},signal:t?.signal??this.#t.signal});return new WritableStream({write(o){l.append(o)},async close(){if(await l.close(),r)throw r},abort(o){l.detach().catch(u=>{t?.onError?.(u)})}})}async stream(t){const i={...this.#t.headers,...t?.headers},r={...this.#t.params,...t?.params};return BO({url:this.url,headers:i,params:r,signal:t?.signal??this.#t.signal,fetch:this.#t.fetch,backoffOptions:this.#t.backoffOptions,offset:t?.offset,live:t?.live,json:t?.json,onError:t?.onError??this.#s,warnOnHttp:t?.warnOnHttp??this.#t.warnOnHttp})}async resolveHeaders(){return nl(this.#t.headers)}async#f(){const t=await nl(this.#t.headers),i=new URL(this.url),r=await fc(this.#t.params);for(const[l,o]of Object.entries(r))i.searchParams.set(l,o);return{requestHeaders:t,fetchUrl:i}}};function qO(n){if(n!==void 0)return typeof n==`string`?new TextEncoder().encode(n):n instanceof Uint8Array||n instanceof Blob||n instanceof FormData||n instanceof ReadableStream||n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n:new TextEncoder().encode(JSON.stringify(n))}function KO(n){if(n instanceof ReadableStream)return n.pipeThrough(new TransformStream({transform(r,l){typeof r==`string`?l.enqueue(new TextEncoder().encode(r)):l.enqueue(r)}}));const t=new TextEncoder,i=n[Symbol.asyncIterator]();return new ReadableStream({async pull(r){try{const{done:l,value:o}=await i.next();l?r.close():typeof o==`string`?r.enqueue(t.encode(o)):r.enqueue(o)}catch(l){r.error(l)}},cancel(){i.return?.()}})}function VO(n){if(!n.url)throw new EO;if(n.signal&&!(n.signal instanceof AbortSignal))throw new CO;bb(n.url,n.warnOnHttp)}function Eb(n){return n!=null&&`operation`in n.headers}function Cb(n){return n!=null&&`control`in n.headers}var $O=class{handlers=new Map;pendingHandlers=new Set;isUpToDate=!1;preloadResolvers=[];preloadRejecters=[];seenTxids=new Set;pendingTxids=new Set;txidResolvers=new Map;existingKeys=new Map;registerHandler(n,t){this.handlers.set(n,t),this.existingKeys.has(n)||this.existingKeys.set(n,new Set)}dispatchChange(n){if(!Eb(n))return;n.headers.txid&&typeof n.headers.txid==`string`&&this.pendingTxids.add(n.headers.txid);const t=this.handlers.get(n.type);if(!t)return;let i=n.headers.operation;if(i!==`delete`&&(typeof n.value!=`object`||n.value===null))throw new Error(`StreamDB collections require object values; got ${typeof n.value} for type=${n.type}, key=${n.key}`);const l={...n.value??{}};l[t.primaryKey]=n.key,this.pendingHandlers.has(t)||(t.begin(),this.pendingHandlers.add(t)),i===`upsert`&&(i=this.existingKeys.get(n.type)?.has(n.key)?`update`:`insert`);const o=this.existingKeys.get(n.type);i===`insert`||i===`update`?o?.add(n.key):o?.delete(n.key);try{t.write(l,i)}catch(u){throw console.error(`[StreamDB] Error in handler.write():`,u),console.error(`[StreamDB] Event that caused error:`,{type:n.type,key:n.key,operation:i}),u}}dispatchControl(n){if(Cb(n))switch(n.headers.control){case`reset`:for(const t of this.handlers.values())t.truncate();for(const t of this.existingKeys.values())t.clear();this.pendingHandlers.clear(),this.isUpToDate=!1;break}}markUpToDate(){for(const n of this.pendingHandlers)try{n.commit()}catch(t){if(console.error(`[StreamDB] Error in handler.commit():`,t),t instanceof Error&&t.message.includes(`already exists in the collection`)&&t.message.includes(`live-query`)){console.warn(`[StreamDB] Known TanStack DB groupBy bug detected - continuing despite error`),console.warn(`[StreamDB] Queries with groupBy may show stale data until fixed`);continue}throw t}this.pendingHandlers.clear();for(const n of this.pendingTxids){this.seenTxids.add(n);const t=this.txidResolvers.get(n);if(t){for(const{resolve:i,timeoutId:r}of t)clearTimeout(r),i();this.txidResolvers.delete(n)}}if(this.pendingTxids.clear(),!this.isUpToDate){this.isUpToDate=!0;for(const n of this.handlers.values())n.markReady();for(const n of this.preloadResolvers)n();this.preloadResolvers=[]}}waitForUpToDate(){return this.isUpToDate?Promise.resolve():new Promise((n,t)=>{this.preloadResolvers.push(n),this.preloadRejecters.push(t)})}rejectAll(n){for(const t of this.preloadRejecters)t(n);this.preloadResolvers=[],this.preloadRejecters=[];for(const t of this.txidResolvers.values())for(const{reject:i,timeoutId:r}of t)clearTimeout(r),i(n);this.txidResolvers.clear()}get ready(){return this.isUpToDate}awaitTxId(n,t=5e3){return this.seenTxids.has(n)?Promise.resolve():new Promise((i,r)=>{const l=setTimeout(()=>{const o=this.txidResolvers.get(n);if(o){const u=o.findIndex(d=>d.timeoutId===l);u!==-1&&o.splice(u,1),o.length===0&&this.txidResolvers.delete(n)}r(new Error(`Timeout waiting for txid: ${n}`))},t);this.txidResolvers.has(n)||this.txidResolvers.set(n,[]),this.txidResolvers.get(n).push({resolve:i,reject:r,timeoutId:l})})}};function GO(n,t,i){return{sync:({begin:r,write:l,commit:o,markReady:u,truncate:d})=>(t.registerHandler(n,{begin:r,write:(p,g)=>{l({value:p,type:g})},commit:o,markReady:u,truncate:d,primaryKey:i}),t.ready&&u(),()=>{})}}const $S=new Set([`collections`,`preload`,`close`,`utils`,`actions`]);function YO(n,t,i){return{insert:({key:r,value:l,headers:o})=>{const u=i[`~standard`].validate(l);if(`issues`in u)throw new Error(`Validation failed for ${n} insert: ${u.issues?.map(g=>g.message).join(`, `)??`Unknown validation error`}`);const d=l[t],p=r??(d!=null&&d!==``?String(d):void 0);if(p==null||p===``)throw new Error(`Cannot create ${n} insert event: must provide either 'key' or a value with a non-empty '${t}' field`);return{type:n,key:p,value:l,headers:{...o,operation:`insert`}}},update:({key:r,value:l,oldValue:o,headers:u})=>{const d=i[`~standard`].validate(l);if(`issues`in d)throw new Error(`Validation failed for ${n} update: ${d.issues?.map(y=>y.message).join(`, `)??`Unknown validation error`}`);if(o!==void 0){const y=i[`~standard`].validate(o);if(`issues`in y)throw new Error(`Validation failed for ${n} update (oldValue): ${y.issues?.map(m=>m.message).join(`, `)??`Unknown validation error`}`)}const p=l[t],g=r??(p!=null&&p!==``?String(p):void 0);if(g==null||g===``)throw new Error(`Cannot create ${n} update event: must provide either 'key' or a value with a non-empty '${t}' field`);return{type:n,key:g,value:l,old_value:o,headers:{...u,operation:`update`}}},delete:({key:r,oldValue:l,headers:o})=>{if(l!==void 0){const d=i[`~standard`].validate(l);if(`issues`in d)throw new Error(`Validation failed for ${n} delete (oldValue): ${d.issues?.map(p=>p.message).join(`, `)??`Unknown validation error`}`)}const u=r??(l?String(l[t]):void 0);if(!u)throw new Error(`Cannot create ${n} delete event: must provide either 'key' or 'oldValue' with a ${t} field`);return{type:n,key:u,old_value:l,headers:{...o,operation:`delete`}}},upsert:({key:r,value:l,headers:o})=>{const u=i[`~standard`].validate(l);if(`issues`in u)throw new Error(`Validation failed for ${n} upsert: ${u.issues?.map(g=>g.message).join(`, `)??`Unknown validation error`}`);const d=l[t],p=r??(d!=null&&d!==``?String(d):void 0);if(p==null||p===``)throw new Error(`Cannot create ${n} upsert event: must provide either 'key' or a value with a non-empty '${t}' field`);return{type:n,key:p,value:l,headers:{...o,operation:`upsert`}}}}}function xb(n){for(const r of Object.keys(n))if($S.has(r))throw new Error(`Reserved collection name "${r}" - this would collide with StreamDB properties (${Array.from($S).join(`, `)})`);const t=new Map;for(const[r,l]of Object.entries(n)){const o=t.get(l.type);if(o)throw new Error(`Duplicate event type "${l.type}" - used by both "${o}" and "${r}" collections`);t.set(l.type,r)}const i={};for(const[r,l]of Object.entries(n))i[r]={...l,...YO(l.type,l.primaryKey,l.schema)};return i}function FO(n){const{streamOptions:t,state:i,actions:r}=n,l=new Ys(t),o=new $O,u={};for(const[w,b]of Object.entries(i)){const E=op({id:`stream-db:${w}`,schema:b.schema,getKey:_=>String(_[b.primaryKey]),sync:GO(b.type,o,b.primaryKey),startSync:!0,gcTime:0});console.log(`[StreamDB] Created collection "${w}":`,{type:typeof E,constructor:E.constructor.name,isCollection:E instanceof Object,hasSize:`size`in E}),u[w]=E}let d=null;const p=new AbortController;let g=!1;const y=async()=>{if(g)return;g=!0,d=await l.stream({live:!0,signal:p.signal});let w=0,b=Date.now();d.subscribeJson(_=>{try{w++,b=Date.now(),_.items.length>0&&console.log(`[StreamDB] Processing batch #${w}: ${_.items.length} items, upToDate=${_.upToDate}`);for(const j of _.items)Eb(j)?o.dispatchChange(j):Cb(j)&&o.dispatchControl(j);_.upToDate&&(console.log(`[StreamDB] Marking up-to-date after batch #${w}`),o.markUpToDate(),console.log(`[StreamDB] Successfully marked up-to-date`)),_.items.length>0&&console.log(`[StreamDB] Successfully processed batch #${w}`)}catch(j){console.error(`[StreamDB] Error processing batch:`,j),console.error(`[StreamDB] Failed batch:`,_),o.rejectAll(j),p.abort()}return Promise.resolve()});const E=setInterval(()=>{const _=Date.now()-b;console.log(`[StreamDB] Health: ${w} batches processed, last batch ${(_/1e3).toFixed(1)}s ago`)},15e3);p.signal.addEventListener(`abort`,()=>{clearInterval(E),console.log(`[StreamDB] Aborted - cleaning up health check`)})},m={stream:l,preload:async()=>{await y(),await o.waitForUpToDate()},close:()=>{o.rejectAll(new Error(`StreamDB closed`)),p.abort()},utils:{awaitTxId:(w,b)=>o.awaitTxId(w,b)}};console.log(`[StreamDB] Creating db object with collections:`,Object.keys(u));const v={collections:u,...m};if(console.log(`[StreamDB] db.collections:`,Object.keys(v.collections)),console.log(`[StreamDB] db.collections.events:`,v.collections.events),r){const w=r({db:v,stream:l}),b={};for(const[E,_]of Object.entries(w))b[E]=uA({onMutate:_.onMutate,mutationFn:_.mutationFn});return{...v,actions:b}}return v}const bp=600,QO=bp/2*1e3,XO=3600*24,JO={"~standard":{version:1,vendor:`durable-streams`,validate:n=>{const t=n;return typeof t.roomId!=`string`||t.roomId.length===0?{issues:[{message:`roomId must be a non-empty string`}]}:typeof t.name!=`string`||t.name.length===0?{issues:[{message:`name must be a non-empty string`}]}:typeof t.boardSize!=`string`?{issues:[{message:`boardSize must be a string`}]}:typeof t.createdAt!=`number`?{issues:[{message:`createdAt must be a number`}]}:typeof t.expiresAt!=`number`?{issues:[{message:`expiresAt must be a number`}]}:t.playerCount!==void 0&&typeof t.playerCount!=`number`?{issues:[{message:`playerCount must be a number`}]}:{value:t}}}},Jh=xb({rooms:{schema:JO,type:`stream`,primaryKey:`roomId`}}),ZO={"~standard":{version:1,vendor:`durable-streams`,validate:n=>{const t=n;return typeof t.playerName!=`string`||t.playerName.length===0?{issues:[{message:`playerName must be a non-empty string`}]}:typeof t.score!=`number`?{issues:[{message:`score must be a number`}]}:typeof t.timestamp!=`number`?{issues:[{message:`timestamp must be a number`}]}:{value:t}}}},GS=xb({scores:{schema:ZO,type:`stream`,primaryKey:`playerName`}});function _b(n){const[t,i]=J.useState({db:null,isLoading:!0,error:null}),r=n.streamOptions.url;return J.useEffect(()=>{let l=null;const o=new AbortController,u=()=>o.signal.aborted;return(async()=>{i({db:null,isLoading:!0,error:null});try{const g=await new Ys({url:r,headers:n.streamOptions.headers,contentType:`application/json`}).head();if(u()||(g.exists||await Ys.create({url:r,headers:n.streamOptions.headers,contentType:`application/json`,ttlSeconds:n.ttlSeconds}),l=await FO(n),await l.preload(),u()))return;i({db:l,isLoading:!1,error:null})}catch(p){if(u())return;const g=p instanceof Error?p:new Error(String(p));console.error(`[useStreamDB] Failed to initialize ${r}:`,g),i({db:null,isLoading:!1,error:g})}})(),()=>{o.abort(),l&&l.close()}},[r]),t}function WO(n,t){return{streamOptions:{url:n,headers:t,contentType:`application/json`},state:Jh,ttlSeconds:XO,actions:({db:i,stream:r})=>({addRoom:{onMutate:l=>{i.collections.rooms.insert(l)},mutationFn:async l=>{const o=crypto.randomUUID();await r.append(JSON.stringify(Jh.rooms.insert({value:l,headers:{txid:o}}))),await i.utils.awaitTxId(o)}},deleteRoom:{onMutate:l=>{i.collections.rooms.delete(l)},mutationFn:async l=>{const o=crypto.randomUUID();await r.append(JSON.stringify(Jh.rooms.delete({key:l,headers:{txid:o}}))),await i.utils.awaitTxId(o)}}})}}function PO(n,t){return _b(WO(n,t))}const Tb=J.createContext(null);function Ab(){const n=J.useContext(Tb);if(!n)throw new Error(`useRegistryContext must be used within RegistryProvider`);return n}function tR({children:n}){const{dsEndpoint:t,dsHeaders:i}=Zd(),{db:r,isLoading:l,error:o}=PO(`${t}/__snake_rooms`,i);return l?F.jsxs(`div`,{style:YS.center,children:[F.jsx(`style`,{children:`@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');`}),F.jsx(`div`,{style:{color:`#d0bcff`,fontSize:8},children:`LOADING...`})]}):o||!r?F.jsxs(`div`,{style:YS.center,children:[F.jsx(`style`,{children:`@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');`}),F.jsxs(`div`,{style:{color:`#FF3D71`,fontSize:8},children:[`Registry Error: `,o?.message||`Failed to load`]})]}):F.jsx(Tb.Provider,{value:{registryDB:r},children:n})}const YS={center:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100vh`,gap:16,fontFamily:`'Press Start 2P', monospace`,background:`#1b1b1f`}},Zh=1;function eR(n,t=[]){const i=n&&typeof n==`object`&&typeof n.subscribeChanges==`function`&&typeof n.startSyncImmediate==`function`&&typeof n.id==`string`,r=J.useRef(null),l=J.useRef(null),o=J.useRef(null),u=J.useRef(0),d=J.useRef(null),p=!r.current||i&&o.current!==n||!i&&(l.current===null||l.current.length!==t.length||l.current.some((b,E)=>b!==t[E]));if(p)if(i)n.config?.syncMode===`on-demand`&&console.warn(`[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.
+
+Instead, use a query builder function:
+ const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))
+
+Or switch to syncMode "eager" if you want all data to sync automatically.`),n.startSyncImmediate(),r.current=n,o.current=n;else if(typeof n==`function`){const b=new Zt,E=n(b);if(E==null)r.current=null;else if(E instanceof cp)E.startSyncImmediate(),r.current=E;else if(E instanceof Zt)r.current=Kh({query:n,startSync:!0,gcTime:Zh});else if(E&&typeof E==`object`)r.current=Kh({startSync:!0,gcTime:Zh,...E});else throw new Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof E}`);l.current=[...t]}else r.current=Kh({startSync:!0,gcTime:Zh,...n}),l.current=[...t];p&&(u.current=0,d.current=null);const g=J.useRef(null);(!g.current||p)&&(g.current=b=>{if(!r.current)return()=>{};const E=r.current.subscribeChanges(()=>{u.current+=1,b()});return r.current.status===`ready`&&(u.current+=1,b()),()=>{E.unsubscribe()}});const y=J.useRef(null);(!y.current||p)&&(y.current=()=>{const b=u.current,E=r.current;return(!d.current||d.current.version!==b||d.current.collection!==E)&&(d.current={collection:E,version:b}),d.current});const m=J.useSyncExternalStore(g.current,y.current),v=J.useRef(null),w=J.useRef(null);if(!v.current||v.current.version!==m.version||v.current.collection!==m.collection){if(!m.collection)w.current={state:void 0,data:void 0,collection:void 0,status:`disabled`,isLoading:!1,isReady:!0,isIdle:!1,isError:!1,isCleanedUp:!1,isEnabled:!1};else{const b=Array.from(m.collection.entries()),_=m.collection.config.singleResult;let j=null,O=null;w.current={get state(){return j||(j=new Map(b)),j},get data(){return O||(O=b.map(([,A])=>A)),_?O[0]:O},collection:m.collection,status:m.collection.status,isLoading:m.collection.status===`loading`,isReady:m.collection.status===`ready`,isIdle:m.collection.status===`idle`,isError:m.collection.status===`error`,isCleanedUp:m.collection.status===`cleaned-up`,isEnabled:!0}}v.current=m}return w.current}const Nt={bg:`#1b1b1f`,card:`#161618`,border:`#2e2e32`,text:`rgba(235,235,245,0.68)`,accent:`#d0bcff`,dim:`rgba(235,235,245,0.38)`},tc=[{label:`32x32`,cols:32,rows:32},{label:`64x64`,cols:64,rows:64},{label:`128x128`,cols:128,rows:128}];function Wh(n,t){return`${n}__${t.cols}x${t.rows}`}function nR(){const n=[`neon`,`cyber`,`pixel`,`hyper`,`turbo`,`mega`,`ultra`,`nova`],t=n[Math.floor(Math.random()*n.length)],i=Math.floor(Math.random()*900)+100;return`${t}-${i}`}function sR({playerName:n,onPlayerNameChange:t,onJoinRoom:i}){const{registryDB:r}=Ab(),[l,o]=J.useState(nR),[u,d]=J.useState(1),[p,g]=J.useState(!1),[y,m]=J.useState(0),[v,w]=J.useState(``),[,b]=J.useState(0);J.useEffect(()=>{const O=setInterval(()=>b(A=>A+1),1e3);return()=>clearInterval(O)},[]);const E=Date.now(),{data:_=[]}=eR(O=>O.from({rooms:r.collections.rooms}).where(({rooms:A})=>wd(A.expiresAt,E)).orderBy(({rooms:A})=>A.createdAt,`desc`)),j=async()=>{if(!p){g(!0);try{const O=l.trim()||`room-${Math.random().toString(36).slice(2,7)}`,A=tc[u],M=Wh(O,A),G=Date.now(),q={roomId:M,name:O,boardSize:`${A.cols}x${A.rows}`,createdAt:G,expiresAt:G+bp*1e3};await r.actions.addRoom(q),o(``),i(M)}catch(O){console.error(`Failed to create room:`,O)}finally{g(!1)}}};return F.jsxs(`div`,{style:mn.container,children:[F.jsx(`style`,{children:`
+ @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
+ .lobby-btn:active { opacity: 0.7; }
+ `}),F.jsx(`div`,{style:mn.title,children:`TERRITORY WARS`}),F.jsx(`div`,{style:{fontSize:7,color:Nt.dim,marginBottom:20,textAlign:`center`,maxWidth:340,lineHeight:1.6},children:`Claim 30% territory or lead when time runs out.`}),F.jsxs(`div`,{style:mn.card,children:[F.jsx(`div`,{style:mn.cardTitle,children:`NAME`}),F.jsx(`input`,{style:mn.input,value:n,onChange:O=>t(O.target.value),placeholder:`Enter your name...`,maxLength:20})]}),F.jsxs(`div`,{style:mn.card,children:[F.jsx(`div`,{style:mn.cardTitle,children:`ROOM`}),F.jsx(`input`,{style:mn.input,value:l,onChange:O=>o(O.target.value),placeholder:`room name`,onKeyDown:O=>O.key===`Enter`&&j()}),F.jsx(`div`,{style:mn.cardTitle,children:`BOARD SIZE`}),F.jsx(`div`,{style:{display:`flex`,gap:6,marginBottom:10},children:tc.map((O,A)=>F.jsx(`button`,{className:`lobby-btn`,style:{flex:1,padding:`6px 0`,fontSize:7,fontFamily:`inherit`,background:A===u?Nt.accent:`transparent`,color:A===u?`#000`:Nt.accent,border:`1px solid ${Nt.accent}`,cursor:`pointer`,letterSpacing:1},onClick:()=>d(A),children:O.label},O.label))}),F.jsx(`button`,{className:`lobby-btn`,style:{...mn.createBtn,opacity:p?.6:1},onClick:j,disabled:p,children:p?`STARTING...`:`START`})]}),F.jsxs(`div`,{style:mn.card,children:[F.jsx(`div`,{style:mn.cardTitle,children:`ROOMS`}),F.jsxs(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[_.slice(y*3,y*3+3).map(O=>F.jsx(iR,{room:O,onJoin:()=>i(O.roomId)},O.roomId)),F.jsxs(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,background:Nt.bg,border:`1px solid ${Nt.border}`,padding:`8px 12px`},children:[F.jsx(`input`,{style:{fontSize:8,color:Nt.text,fontFamily:`inherit`,background:`transparent`,border:`none`,outline:`none`,flex:1,padding:0},value:v,onChange:O=>w(O.target.value),placeholder:`room-id`,onKeyDown:O=>{if(O.key===`Enter`&&v.trim()){const A=_.find(M=>M.name===v.trim());i(A?A.roomId:Wh(v.trim(),tc[u]))}}}),v.trim()&&F.jsx(`button`,{className:`lobby-btn`,style:{background:Nt.accent,color:`#000`,border:`none`,fontFamily:`inherit`,fontSize:7,padding:`4px 12px`,cursor:`pointer`,letterSpacing:1,flexShrink:0},onClick:()=>{const O=_.find(A=>A.name===v.trim());i(O?O.roomId:Wh(v.trim(),tc[u]))},children:`JOIN`})]})]}),_.length>3&&F.jsxs(`div`,{style:{display:`flex`,justifyContent:`center`,gap:8,marginTop:10},children:[F.jsx(`button`,{className:`lobby-btn`,style:{fontFamily:`inherit`,fontSize:6,background:Nt.bg,color:Nt.dim,border:`1px solid ${Nt.border}`,cursor:`pointer`,width:28,padding:`4px 0`,opacity:y===0?.3:1},disabled:y===0,onClick:()=>m(O=>O-1),children:`<`}),F.jsxs(`span`,{style:{fontSize:7,color:Nt.dim,lineHeight:`24px`},children:[y+1,`/`,Math.ceil(_.length/3)]}),F.jsx(`button`,{className:`lobby-btn`,style:{fontFamily:`inherit`,fontSize:6,background:Nt.bg,color:Nt.dim,border:`1px solid ${Nt.border}`,cursor:`pointer`,width:28,padding:`4px 0`,opacity:y>=Math.ceil(_.length/3)-1?.3:1},disabled:y>=Math.ceil(_.length/3)-1,onClick:()=>m(O=>O+1),children:`>`})]})]})]})}function iR({room:n,onJoin:t}){const[i,r]=J.useState(!1),l=o=>{o.stopPropagation(),navigator.clipboard.writeText(n.name).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1200)};return F.jsxs(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,background:Nt.bg,border:`1px solid ${Nt.border}`,padding:`8px 12px`,cursor:`pointer`},onClick:t,children:[F.jsx(`div`,{style:{display:`flex`,alignItems:`center`,gap:6},onClick:l,title:`Click to copy room name`,children:F.jsx(`span`,{style:{fontSize:8,color:i?Nt.accent:Nt.text,cursor:`pointer`},children:i?`COPIED`:n.name})}),F.jsx(`button`,{className:`lobby-btn`,style:{background:Nt.accent,color:`#000`,border:`none`,fontFamily:`inherit`,fontSize:7,padding:`4px 12px`,cursor:`pointer`,letterSpacing:1},onClick:o=>{o.stopPropagation(),t()},children:`JOIN`})]})}const mn={container:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,minHeight:`100vh`,fontFamily:`'Press Start 2P', monospace`,background:Nt.bg,color:Nt.text,padding:20},title:{fontSize:16,letterSpacing:4,color:Nt.accent,marginBottom:6},card:{background:Nt.card,border:`1px solid ${Nt.border}`,padding:16,width:`100%`,maxWidth:340,marginBottom:12},cardTitle:{fontSize:7,color:Nt.accent,letterSpacing:2,marginBottom:10},input:{width:`100%`,background:Nt.bg,border:`1px solid ${Nt.border}`,padding:`8px 10px`,color:Nt.text,fontFamily:`inherit`,fontSize:8,marginBottom:10,outline:`none`,boxSizing:`border-box`},createBtn:{width:`100%`,padding:`10px 0`,fontSize:8,fontFamily:`inherit`,background:Nt.accent,color:`#000`,border:`none`,cursor:`pointer`,letterSpacing:2}},An=()=>new Map,Ld=n=>{const t=An();return n.forEach((i,r)=>{t.set(r,i)}),t},Ws=(n,t,i)=>{let r=n.get(t);return r===void 0&&n.set(t,r=i()),r},rR=(n,t)=>{const i=[];for(const[r,l]of n)i.push(t(l,r));return i},aR=(n,t)=>{for(const[i,r]of n)if(t(r,i))return!0;return!1},Hr=()=>new Set,Ph=n=>n[n.length-1],lR=(n,t)=>{for(let i=0;i{for(let i=0;i{for(let i=0;i{const i=new Array(n);for(let r=0;r{this.off(t,r),i(...l)};this.on(t,r)}off(t,i){const r=this._observers.get(t);r!==void 0&&(r.delete(i),r.size===0&&this._observers.delete(t))}emit(t,i){return Ei((this._observers.get(t)||An()).values()).forEach(r=>r(...i))}destroy(){this._observers=An()}};const Hn=Math.floor,hc=Math.abs,Rb=(n,t)=>nn>t?n:t,Db=n=>n!==0?n<0:1/n<0,FS=1,QS=2,td=4,ed=8,hl=32,gs=64,rn=128,Qc=31,Id=63,wi=127,uR=2147483647,Oc=Number.MAX_SAFE_INTEGER,XS=Number.MIN_SAFE_INTEGER,fR=Number.isInteger||(n=>typeof n==`number`&&isFinite(n)&&Hn(n)===n),hR=String.fromCharCode,dR=n=>n.toLowerCase(),pR=/^\s*/g,gR=n=>n.replace(pR,``),yR=/([A-Z])/g,JS=(n,t)=>gR(n.replace(yR,i=>`${t}${dR(i)}`)),mR=n=>{const t=unescape(encodeURIComponent(n)),i=t.length,r=new Uint8Array(i);for(let l=0;ldl.encode(n),vR=dl?SR:mR;let sl=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});sl&&sl.decode(new Uint8Array).length===1&&(sl=null);const bR=(n,t)=>oR(t,()=>n).join(``);let Tl=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Xc=()=>new Tl,wR=n=>{let t=n.cpos;for(let i=0;i{const t=new Uint8Array(wR(n));let i=0;for(let r=0;r{const i=n.cbuf.length;i-n.cpos{const i=n.cbuf.length;n.cpos===i&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(i*2),n.cpos=0),n.cbuf[n.cpos++]=t},Hd=ye,Dt=(n,t)=>{for(;t>wi;)ye(n,rn|wi&t),t=Hn(t/128);ye(n,wi&t)},Ep=(n,t)=>{const i=Db(t);for(i&&(t=-t),ye(n,(t>Id?rn:0)|(i?gs:0)|Id&t),t=Hn(t/64);t>0;)ye(n,(t>wi?rn:0)|wi&t),t=Hn(t/128)},qd=new Uint8Array(3e4),CR=qd.length/3,xR=(n,t)=>{if(t.length{const i=unescape(encodeURIComponent(t)),r=i.length;Dt(n,r);for(let l=0;l{const i=n.cbuf.length,r=n.cpos,l=Rb(i-r,t.length),o=t.length-l;n.cbuf.set(t.subarray(0,l),r),n.cpos+=l,o>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(Yr(i*2,o)),n.cbuf.set(t.subarray(l)),n.cpos=o)},nn=(n,t)=>{Dt(n,t.byteLength),Jc(n,t)},Cp=(n,t)=>{ER(n,t);const i=new DataView(n.cbuf.buffer,n.cpos,t);return n.cpos+=t,i},TR=(n,t)=>Cp(n,4).setFloat32(0,t,!1),AR=(n,t)=>Cp(n,8).setFloat64(0,t,!1),OR=(n,t)=>Cp(n,8).setBigInt64(0,t,!1),ZS=new DataView(new ArrayBuffer(4)),RR=n=>(ZS.setFloat32(0,n),ZS.getFloat32(0)===n),pl=(n,t)=>{switch(typeof t){case`string`:ye(n,119),Rr(n,t);break;case`number`:fR(t)&&hc(t)<=uR?(ye(n,125),Ep(n,t)):RR(t)?(ye(n,124),TR(n,t)):(ye(n,123),AR(n,t));break;case`bigint`:ye(n,122),OR(n,t);break;case`object`:if(t===null)ye(n,126);else if(Fc(t)){ye(n,117),Dt(n,t.length);for(let i=0;i0&&Dt(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const PS=n=>{n.count>0&&(Ep(n.encoder,n.count===1?n.s:-n.s),n.count>1&&Dt(n.encoder,n.count-2))};class dc{constructor(){this.encoder=new Tl,this.s=0,this.count=0}write(t){this.s===t?this.count++:(PS(this),this.count=1,this.s=t)}toUint8Array(){return PS(this),In(this.encoder)}}const tv=n=>{if(n.count>0){const t=n.diff*2+(n.count===1?0:1);Ep(n.encoder,t),n.count>1&&Dt(n.encoder,n.count-2)}};class nd{constructor(){this.encoder=new Tl,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(tv(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return tv(this),In(this.encoder)}}class DR{constructor(){this.sarr=[],this.s=``,this.lensE=new dc}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(t.length)}toUint8Array(){const t=new Tl;return this.sarr.push(this.s),this.s=``,Rr(t,this.sarr.join(``)),Jc(t,this.lensE.toUint8Array()),In(t)}}const qn=n=>new Error(n),On=()=>{throw qn(`Method unimplemented`)},bn=()=>{throw qn(`Unexpected case`)},Mb=qn(`Unexpected end of array`),kb=qn(`Integer out of Range`);let Zc=class{constructor(t){this.arr=t,this.pos=0}};const xp=n=>new Zc(n),MR=n=>n.pos!==n.arr.length,kR=(n,t)=>{const i=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,t);return n.pos+=t,i},sn=n=>kR(n,Ot(n)),qr=n=>n.arr[n.pos++],Ot=n=>{let t=0,i=1;const r=n.arr.length;for(;n.posOc)throw kb}throw Mb},_p=n=>{let t=n.arr[n.pos++],i=t&Id,r=64;const l=(t&gs)>0?-1:1;if((t&rn)===0)return l*i;const o=n.arr.length;for(;n.posOc)throw kb}throw Mb},UR=n=>{let t=Ot(n);if(t===0)return``;{let i=String.fromCodePoint(qr(n));if(--t<100)for(;t--;)i+=String.fromCodePoint(qr(n));else for(;t>0;){const r=t<1e4?t:1e4,l=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,i+=String.fromCodePoint.apply(null,l),t-=r}return decodeURIComponent(escape(i))}},zR=n=>sl.decode(sn(n)),Dr=sl?zR:UR,Tp=(n,t)=>{const i=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,t);return n.pos+=t,i},NR=n=>Tp(n,4).getFloat32(0,!1),jR=n=>Tp(n,8).getFloat64(0,!1),BR=n=>Tp(n,8).getBigInt64(0,!1),LR=[n=>{},n=>null,_p,NR,jR,BR,n=>!1,n=>!0,Dr,n=>{const t=Ot(n),i={};for(let r=0;r{const t=Ot(n),i=[];for(let r=0;rLR[127-qr(n)](n);class ev extends Zc{constructor(t,i){super(t),this.reader=i,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),MR(this)?this.count=Ot(this)+1:this.count=-1),this.count--,this.s}}class pc extends Zc{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=_p(this);const t=Db(this.s);this.count=1,t&&(this.s=-this.s,this.count=Ot(this)+2)}return this.count--,this.s}}class sd extends Zc{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=_p(this),i=t&1;this.diff=Hn(t/2),this.count=1,i&&(this.count=Ot(this)+2)}return this.s+=this.diff,this.count--,this.s}}class IR{constructor(t){this.decoder=new pc(t),this.str=Dr(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),i=this.str.slice(this.spos,t);return this.spos=t,i}}const HR=crypto.getRandomValues.bind(crypto),Ub=()=>HR(new Uint32Array(1))[0],qR=`10000000-1000-4000-8000`+-1e11,KR=()=>qR.replace(/[018]/g,n=>(n^Ub()&15>>n/4).toString(16)),nv=n=>new Promise(n);Promise.all.bind(Promise);const sv=n=>n===void 0?null:n;class VR{constructor(){this.map=new Map}setItem(t,i){this.map.set(t,i)}getItem(t){return this.map.get(t)}}let zb=new VR,$R=!0;try{typeof localStorage<`u`&&localStorage&&(zb=localStorage,$R=!1)}catch{}const GR=zb,yl=Symbol(`Equality`),Nb=(n,t)=>n===t||!!n?.[yl]?.(t)||!1,YR=n=>typeof n==`object`,FR=Object.assign,QR=Object.keys,XR=(n,t)=>{for(const i in n)t(n[i],i)},Rc=n=>QR(n).length,JR=n=>{for(const t in n)return!1;return!0},Al=(n,t)=>{for(const i in n)if(!t(n[i],i))return!1;return!0},Ap=(n,t)=>Object.prototype.hasOwnProperty.call(n,t),ZR=(n,t)=>n===t||Rc(n)===Rc(t)&&Al(n,(i,r)=>(i!==void 0||Ap(t,r))&&Nb(t[r],i)),WR=Object.freeze,jb=n=>{for(const t in n){const i=n[t];(typeof i==`object`||typeof i==`function`)&&jb(n[t])}return WR(n)},Op=(n,t,i=0)=>{try{for(;i{if(n===t)return!0;if(n==null||t==null||n.constructor!==t.constructor&&(n.constructor||Object)!==(t.constructor||Object))return!1;if(n[yl]!=null)return n[yl](t);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),t=new Uint8Array(t);case Uint8Array:{if(n.byteLength!==t.byteLength)return!1;for(let i=0;it.includes(n);var Bb={};const ml=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`;let Nn;const tD=()=>{if(Nn===void 0)if(ml){Nn=An();const n=process.argv;let t=null;for(let i=0;i{if(n.length!==0){const[t,i]=n.split(`=`);Nn.set(`--${JS(t,`-`)}`,i),Nn.set(`-${JS(t,`-`)}`,i)}})):Nn=An();return Nn},Kd=n=>tD().has(n),Dc=n=>sv(ml?Bb[n.toUpperCase().replaceAll(`-`,`_`)]:GR.getItem(n)),Lb=n=>Kd(`--`+n)||Dc(n)!==null,eD=Lb(`production`),nD=ml&&PR(Bb.FORCE_COLOR,[`true`,`1`,`2`]),sD=nD||!Kd(`--no-colors`)&&!Lb(`no-color`)&&(!ml||process.stdout.isTTY)&&(!ml||Kd(`--color`)||Dc(`COLORTERM`)!==null||(Dc(`TERM`)||``).includes(`color`)),iD=n=>new Uint8Array(n),rD=n=>{const t=iD(n.byteLength);return t.set(n),t};class aD{constructor(t,i){this.left=t,this.right=i}}const us=(n,t)=>new aD(n,t),iv=n=>n.next()>=.5,id=(n,t,i)=>Hn(n.next()*(i+1-t)+t),Ib=(n,t,i)=>Hn(n.next()*(i+1-t)+t),Rp=(n,t,i)=>Ib(n,t,i),lD=n=>hR(Rp(n,97,122)),oD=(n,t=0,i=20)=>{const r=Rp(n,t,i);let l=``;for(let o=0;ot[Rp(n,0,t.length-1)],cD=Symbol(`0schema`);class uD{constructor(){this._rerrs=[]}extend(t,i,r,l=null){this._rerrs.push({path:t,expected:i,has:r,message:l})}toString(){const t=[];for(let i=this._rerrs.length-1;i>0;i--){const r=this._rerrs[i];t.push(bR(` `,(this._rerrs.length-i)*2)+`${r.path!=null?`[${r.path}] `:``}${r.has} doesn't match ${r.expected}. ${r.message}`)}return t.join(`
+`)}}const Vd=(n,t)=>n===t?!0:n==null||t==null||n.constructor!==t.constructor?!1:n[yl]?Nb(n,t):Fc(n)?wp(n,i=>Ob(t,r=>Vd(i,r))):YR(n)?Al(n,(i,r)=>Vd(i,t[r])):!1;class Ne{static _dilutes=!1;extends(t){let[i,r]=[this.shape,t.shape];return this.constructor._dilutes&&([r,i]=[i,r]),Vd(i,r)}equals(t){return this.constructor===t.constructor&&gc(this.shape,t.shape)}[cD](){return!0}[yl](t){return this.equals(t)}validate(t){return this.check(t)}check(t,i){On()}get nullable(){return Fr(this,nu)}get optional(){return new Kb(this)}cast(t){return rv(t,this),t}expect(t){return rv(t,this),t}}class Dp extends Ne{constructor(t,i){super(),this.shape=t,this._c=i}check(t,i=void 0){const r=t?.constructor===this.shape&&(this._c==null||this._c(t));return!r&&i?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?`Constructor match failed`:`Check failed`),r}}const oe=(n,t=null)=>new Dp(n,t);oe(Dp);class Mp extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=this.shape(t);return!r&&i?.extend(null,`custom prop`,t?.constructor.name,`failed to check custom prop`),r}}const ve=n=>new Mp(n);oe(Mp);class Wc extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=this.shape.some(l=>l===t);return!r&&i?.extend(null,this.shape.join(` | `),t.toString()),r}}const Pc=(...n)=>new Wc(n),Hb=oe(Wc),fD=RegExp.escape||(n=>n.replace(/[().|&,$^[\]]/g,t=>`\\`+t)),qb=n=>{if(Kr.check(n))return[fD(n)];if(Hb.check(n))return n.shape.map(t=>t+``);if(Zb.check(n))return[`[+-]?\\d+.?\\d*`];if(Wb.check(n))return[`.*`];if(Mc.check(n))return n.shape.map(qb).flat(1);bn()};class hD extends Ne{constructor(t){super(),this.shape=t,this._r=new RegExp(`^`+t.map(qb).map(i=>`(${i.join(`|`)})`).join(``)+`$`)}check(t,i){const r=this._r.exec(t)!=null;return!r&&i?.extend(null,this._r.toString(),t.toString(),`String doesn't match string template.`),r}}oe(hD);const dD=Symbol(`optional`);class Kb extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=t===void 0||this.shape.check(t);return!r&&i?.extend(null,`undefined (optional)`,`()`),r}get[dD](){return!0}}const pD=oe(Kb);class gD extends Ne{check(t,i){return i?.extend(null,`never`,typeof t),!1}}oe(gD);class tu extends Ne{constructor(t,i=!1){super(),this.shape=t,this._isPartial=i}static _dilutes=!0;get partial(){return new tu(this.shape,!0)}check(t,i){return t==null?(i?.extend(null,`object`,`null`),!1):Al(this.shape,(r,l)=>{const o=this._isPartial&&!Ap(t,l)||r.check(t[l],i);return!o&&i?.extend(l.toString(),r.toString(),typeof t[l],`Object property does not match`),o})}}const yD=n=>new tu(n),mD=oe(tu),SD=ve(n=>n!=null&&(n.constructor===Object||n.constructor==null));class Vb extends Ne{constructor(t,i){super(),this.shape={keys:t,values:i}}check(t,i){return t!=null&&Al(t,(r,l)=>{const o=this.shape.keys.check(l,i);return!o&&i?.extend(l+``,`Record`,typeof t,o?`Key doesn't match schema`:`Value doesn't match value`),o&&this.shape.values.check(r,i)})}}const $b=(n,t)=>new Vb(n,t),vD=oe(Vb);class Gb extends Ne{constructor(t){super(),this.shape=t}check(t,i){return t!=null&&Al(this.shape,(r,l)=>{const o=r.check(t[l],i);return!o&&i?.extend(l.toString(),`Tuple`,typeof r),o})}}const bD=(...n)=>new Gb(n);oe(Gb);class Yb extends Ne{constructor(t){super(),this.shape=t.length===1?t[0]:new kp(t)}check(t,i){const r=Fc(t)&&wp(t,l=>this.shape.check(l));return!r&&i?.extend(null,`Array`,``),r}}const Fb=(...n)=>new Yb(n),wD=oe(Yb),ED=ve(n=>Fc(n));class Qb extends Ne{constructor(t,i){super(),this.shape=t,this._c=i}check(t,i){const r=t instanceof this.shape&&(this._c==null||this._c(t));return!r&&i?.extend(null,this.shape.name,t?.constructor.name),r}}const CD=(n,t=null)=>new Qb(n,t);oe(Qb);const xD=CD(Ne);class _D extends Ne{constructor(t){super(),this.len=t.length-1,this.args=bD(...t.slice(-1)),this.res=t[this.len]}check(t,i){const r=t.constructor===Function&&t.length<=this.len;return!r&&i?.extend(null,`function`,typeof t),r}}const TD=oe(_D),AD=ve(n=>typeof n==`function`);class OD extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=wp(this.shape,l=>l.check(t,i));return!r&&i?.extend(null,`Intersectinon`,typeof t),r}}oe(OD,n=>n.shape.length>0);class kp extends Ne{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,i){const r=Ob(this.shape,l=>l.check(t,i));return i?.extend(null,`Union`,typeof t),r}}const Fr=(...n)=>n.findIndex(t=>Mc.check(t))>=0?Fr(...n.map(t=>Sl(t)).map(t=>Mc.check(t)?t.shape:[t]).flat(1)):n.length===1?n[0]:new kp(n),Mc=oe(kp),Xb=()=>!0,kc=ve(Xb),RD=oe(Mp,n=>n.shape===Xb),Up=ve(n=>typeof n==`bigint`),DD=ve(n=>n===Up),Jb=ve(n=>typeof n==`symbol`);ve(n=>n===Jb);const Mr=ve(n=>typeof n==`number`),Zb=ve(n=>n===Mr),Kr=ve(n=>typeof n==`string`),Wb=ve(n=>n===Kr),eu=ve(n=>typeof n==`boolean`),MD=ve(n=>n===eu),Pb=Pc(void 0);oe(Wc,n=>n.shape.length===1&&n.shape[0]===void 0);Pc(void 0);const nu=Pc(null),kD=oe(Wc,n=>n.shape.length===1&&n.shape[0]===null);oe(Uint8Array);oe(Dp,n=>n.shape===Uint8Array);const UD=Fr(Mr,Kr,nu,Pb,Up,eu,Jb);(()=>{const n=Fb(kc),t=$b(Kr,kc),i=Fr(Mr,Kr,nu,eu,n,t);return n.shape=i,t.shape.values=i,i})();const Sl=n=>{if(xD.check(n))return n;if(SD.check(n)){const t={};for(const i in n)t[i]=Sl(n[i]);return yD(t)}else{if(ED.check(n))return Fr(...n.map(Sl));if(UD.check(n))return Pc(n);if(AD.check(n))return oe(n)}bn()},rv=eD?()=>{}:(n,t)=>{const i=new uD;if(!t.check(n,i))throw qn(`Expected value to be of type ${t.constructor.name}.
+${i.toString()}`)};class zD{constructor(t){this.patterns=[],this.$state=t}if(t,i){return this.patterns.push({if:Sl(t),h:i}),this}else(t){return this.if(kc,t)}done(){return(t,i)=>{for(let r=0;rnew zD(n),tw=ND(kc).if(Zb,(n,t)=>id(t,XS,Oc)).if(Wb,(n,t)=>oD(t)).if(MD,(n,t)=>iv(t)).if(DD,(n,t)=>BigInt(id(t,XS,Oc))).if(Mc,(n,t)=>vr(t,rd(t,n.shape))).if(mD,(n,t)=>{const i={};for(const r in n.shape){let l=n.shape[r];if(pD.check(l)){if(iv(t))continue;l=l.shape}i[r]=tw(l,t)}return i}).if(wD,(n,t)=>{const i=[],r=Ib(t,0,42);for(let l=0;lrd(t,n.shape)).if(kD,(n,t)=>null).if(TD,(n,t)=>{const i=vr(t,n.res);return()=>i}).if(RD,(n,t)=>vr(t,rd(t,[Mr,Kr,nu,Pb,Up,eu,Fb(Mr),$b(Fr(`a`,`b`,`c`),Mr)]))).if(vD,(n,t)=>{const i={},r=id(t,0,3);for(let l=0;ltw(Sl(t),n),su=typeof document<`u`?document:{};ve(n=>n.nodeType===HD);typeof DOMParser<`u`&&new DOMParser;ve(n=>n.nodeType===BD);ve(n=>n.nodeType===LD);const jD=n=>rR(n,(t,i)=>`${i}:${t};`).join(``),BD=su.ELEMENT_NODE,LD=su.TEXT_NODE,ID=su.DOCUMENT_NODE,HD=su.DOCUMENT_FRAGMENT_NODE;ve(n=>n.nodeType===ID);const ms=Symbol,ew=ms(),nw=ms(),qD=ms(),KD=ms(),VD=ms(),sw=ms(),$D=ms(),zp=ms(),GD=ms(),YD=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());const t=[],i=[];let r=0;for(;r0&&i.push(t.join(``));r{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());const t=[],i=[],r=An();let l=[],o=0;for(;o0||p.length>0?(t.push(`%c`+u),i.push(p)):t.push(u)}else break}}for(o>0&&(l=i,l.unshift(t.join(``)));o{console.log(...iw(n)),rw.forEach(t=>t.print(n))},JD=(...n)=>{console.warn(...iw(n)),n.unshift(zp),rw.forEach(t=>t.print(n))},rw=Hr(),aw=n=>({[Symbol.iterator](){return this},next:n}),ZD=(n,t)=>aw(()=>{let i;do i=n.next();while(!i.done&&!t(i.value));return i}),ad=(n,t)=>aw(()=>{const{done:i,value:r}=n.next();return{done:i,value:i?void 0:t(r)}});class Np{constructor(t,i){this.clock=t,this.len=i}}class iu{constructor(){this.clients=new Map}}const lw=(n,t,i)=>t.clients.forEach((r,l)=>{const o=n.doc.store.clients.get(l);if(o!=null){const u=o[o.length-1],d=u.id.clock+u.length;for(let p=0,g=r[p];p{let i=0,r=n.length-1;for(;i<=r;){const l=Hn((i+r)/2),o=n[l],u=o.clock;if(u<=t){if(t{const i=n.clients.get(t.client);return i!==void 0&&WD(i,t.clock)!==null},jp=n=>{n.clients.forEach(t=>{t.sort((l,o)=>l.clock-o.clock);let i,r;for(i=1,r=1;i=o.clock?t[r-1]=new Np(l.clock,Yr(l.len,o.clock+o.len-l.clock)):(r{const t=new iu;for(let i=0;i{if(!t.clients.has(l)){const o=r.slice();for(let u=i+1;u{Ws(n.clients,t,()=>[]).push(new Np(i,r))},Bp=(n,t)=>{Dt(n.restEncoder,t.clients.size),Ei(t.clients.entries()).sort((i,r)=>r[0]-i[0]).forEach(([i,r])=>{n.resetDsCurVal(),Dt(n.restEncoder,i);const l=r.length;Dt(n.restEncoder,l);for(let o=0;o{const t=new iu,i=Ot(n.restDecoder);for(let r=0;r0){const u=Ws(t.clients,l,()=>[]);for(let d=0;d{const r=new iu,l=Ot(n.restDecoder);for(let o=0;o0){const o=new ru;return Dt(o.restEncoder,0),Bp(o,r),o.toUint8Array()}return null},cw=Ub;class Qr extends cR{constructor({guid:t=KR(),collectionid:i=null,gc:r=!0,gcFilter:l=()=>!0,meta:o=null,autoLoad:u=!1,shouldLoad:d=!0}={}){super(),this.gc=r,this.gcFilter=l,this.clientID=cw(),this.guid=t,this.collectionid=i,this.share=new Map,this.store=new dw,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=d,this.autoLoad=u,this.meta=o,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=nv(g=>{this.on(`load`,()=>{this.isLoaded=!0,g(this)})});const p=()=>nv(g=>{const y=m=>{(m===void 0||m===!0)&&(this.off(`sync`,y),g())};this.on(`sync`,y)});this.on(`sync`,g=>{g===!1&&this.isSynced&&(this.whenSynced=p()),this.isSynced=g===void 0||g===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=p()}load(){const t=this._item;t!==null&&!this.shouldLoad&&$t(t.parent.doc,i=>{i.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ei(this.subdocs).map(t=>t.guid))}transact(t,i=null){return $t(this,t,i)}get(t,i=_e){const r=Ws(this.share,t,()=>{const o=new i;return o._integrate(this,null),o}),l=r.constructor;if(i!==_e&&l!==i)if(l===_e){const o=new i;o._map=r._map,r._map.forEach(u=>{for(;u!==null;u=u.left)u.parent=o}),o._start=r._start;for(let u=o._start;u!==null;u=u.right)u.parent=o;return o._length=r._length,this.share.set(t,o),o._integrate(this,null),o}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return r}getArray(t=``){return this.get(t,Ur)}getText(t=``){return this.get(t,$r)}getMap(t=``){return this.get(t,Vr)}getXmlElement(t=``){return this.get(t,Gr)}getXmlFragment(t=``){return this.get(t,Ci)}toJSON(){const t={};return this.share.forEach((i,r)=>{t[r]=i.toJSON()}),t}destroy(){this.isDestroyed=!0,Ei(this.subdocs).forEach(i=>i.destroy());const t=this._item;if(t!==null){this._item=null;const i=t.content;i.doc=new Qr({guid:this.guid,...i.opts,shouldLoad:!1}),i.doc._item=t,$t(t.parent.doc,r=>{const l=i.doc;t.deleted||r.subdocsAdded.add(l),r.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}}class eM{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return Ot(this.restDecoder)}readDsLen(){return Ot(this.restDecoder)}}class nM extends eM{readLeftID(){return Rt(Ot(this.restDecoder),Ot(this.restDecoder))}readRightID(){return Rt(Ot(this.restDecoder),Ot(this.restDecoder))}readClient(){return Ot(this.restDecoder)}readInfo(){return qr(this.restDecoder)}readString(){return Dr(this.restDecoder)}readParentInfo(){return Ot(this.restDecoder)===1}readTypeRef(){return Ot(this.restDecoder)}readLen(){return Ot(this.restDecoder)}readAny(){return gl(this.restDecoder)}readBuf(){return rD(sn(this.restDecoder))}readJSON(){return JSON.parse(Dr(this.restDecoder))}readKey(){return Dr(this.restDecoder)}}class sM{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ot(this.restDecoder),this.dsCurrVal}readDsLen(){const t=Ot(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class zc extends sM{constructor(t){super(t),this.keys=[],Ot(t),this.keyClockDecoder=new sd(sn(t)),this.clientDecoder=new pc(sn(t)),this.leftClockDecoder=new sd(sn(t)),this.rightClockDecoder=new sd(sn(t)),this.infoDecoder=new ev(sn(t),qr),this.stringDecoder=new IR(sn(t)),this.parentInfoDecoder=new ev(sn(t),qr),this.typeRefDecoder=new pc(sn(t)),this.lenDecoder=new pc(sn(t))}readLeftID(){return new kr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new kr(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return gl(this.restDecoder)}readBuf(){return sn(this.restDecoder)}readJSON(){return gl(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{r=Yr(r,t[0].id.clock);const l=Kn(t,r);Dt(n.restEncoder,t.length-l),n.writeClient(i),Dt(n.restEncoder,r);const o=t[l];o.write(n,r-o.id.clock);for(let u=l+1;u{const r=new Map;i.forEach((l,o)=>{me(t,o)>l&&r.set(o,l)}),Lp(t).forEach((l,o)=>{i.has(o)||r.set(o,0)}),Dt(n.restEncoder,r.size),Ei(r.entries()).sort((l,o)=>o[0]-l[0]).forEach(([l,o])=>{lM(n,t.clients.get(l),l,o)})},oM=(n,t)=>{const i=An(),r=Ot(n.restDecoder);for(let l=0;l{const r=[];let l=Ei(i.keys()).sort((w,b)=>w-b);if(l.length===0)return null;const o=()=>{if(l.length===0)return null;let w=i.get(l[l.length-1]);for(;w.refs.length===w.i;)if(l.pop(),l.length>0)w=i.get(l[l.length-1]);else return null;return w};let u=o();if(u===null)return null;const d=new dw,p=new Map,g=(w,b)=>{const E=p.get(w);(E==null||E>b)&&p.set(w,b)};let y=u.refs[u.i++];const m=new Map,v=()=>{for(const w of r){const b=w.id.client,E=i.get(b);E?(E.i--,d.clients.set(b,E.refs.slice(E.i)),i.delete(b),E.i=0,E.refs=[]):d.clients.set(b,[w]),l=l.filter(_=>_!==b)}r.length=0};for(;;){if(y.constructor!==_n){const b=Ws(m,y.id.client,()=>me(t,y.id.client))-y.id.clock;if(b<0)r.push(y),g(y.id.client,y.id.clock-1),v();else{const E=y.getMissing(n,t);if(E!==null){r.push(y);const _=i.get(E)||{refs:[],i:0};if(_.refs.length===_.i)g(E,me(t,E)),v();else{y=_.refs[_.i++];continue}}else(b===0||b0)y=r.pop();else if(u!==null&&u.i0){const w=new ru;return uw(w,d,new Map),Dt(w.restEncoder,0),{missing:p,update:w.toUint8Array()}}return null},uM=(n,t)=>uw(n,t.doc.store,t.beforeState),fM=(n,t,i,r=new zc(n))=>$t(t,l=>{l.local=!1;let o=!1;const u=l.doc,d=u.store,p=oM(r,u),g=cM(l,d,p),y=d.pendingStructs;if(y){for(const[v,w]of y.missing)if(ww)&&y.missing.set(v,w)}y.update=pv([y.update,g.update])}}else d.pendingStructs=g;const m=av(r,l,d);if(d.pendingDs){const v=new zc(xp(d.pendingDs));Ot(v.restDecoder);const w=av(v,l,d);m&&w?d.pendingDs=pv([m,w]):d.pendingDs=m||w}else d.pendingDs=m;if(o){const v=d.pendingStructs.update;d.pendingStructs=null,fw(l.doc,v)}},i,!1),fw=(n,t,i,r=zc)=>{const l=xp(t);fM(l,n,i,new r(l))},lv=(n,t,i)=>fw(n,t,i,nM);class hM{constructor(){this.l=[]}}const ov=()=>new hM,cv=(n,t)=>n.l.push(t),uv=(n,t)=>{const i=n.l,r=i.length;n.l=i.filter(l=>t!==l),r===n.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},hw=(n,t,i)=>Op(n.l,[t,i]);class kr{constructor(t,i){this.client=t,this.clock=i}}const ec=(n,t)=>n===t||n!==null&&t!==null&&n.client===t.client&&n.clock===t.clock,Rt=(n,t)=>new kr(n,t),dM=n=>{for(const[t,i]of n.doc.share.entries())if(i===n)return t;throw bn()},Cr=(n,t)=>t===void 0?!n.deleted:t.sv.has(n.id.client)&&(t.sv.get(n.id.client)||0)>n.id.clock&&!ow(t.ds,n.id),$d=(n,t)=>{const i=Ws(n.meta,$d,Hr),r=n.doc.store;i.has(t)||(t.sv.forEach((l,o)=>{l{}),i.add(t))};class dw{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Lp=n=>{const t=new Map;return n.clients.forEach((i,r)=>{const l=i[i.length-1];t.set(r,l.id.clock+l.length)}),t},me=(n,t)=>{const i=n.clients.get(t);if(i===void 0)return 0;const r=i[i.length-1];return r.id.clock+r.length},pw=(n,t)=>{let i=n.clients.get(t.id.client);if(i===void 0)i=[],n.clients.set(t.id.client,i);else{const r=i[i.length-1];if(r.id.clock+r.length!==t.id.clock)throw bn()}i.push(t)},Kn=(n,t)=>{let i=0,r=n.length-1,l=n[r],o=l.id.clock;if(o===t)return r;let u=Hn(t/(o+l.length-1)*r);for(;i<=r;){if(l=n[u],o=l.id.clock,o<=t){if(t{const i=n.clients.get(t.client);return i[Kn(i,t.clock)]},ld=pM,Gd=(n,t,i)=>{const r=Kn(t,i),l=t[r];return l.id.clock{const i=n.doc.store.clients.get(t.client);return i[Gd(n,i,t.clock)]},fv=(n,t,i)=>{const r=t.clients.get(i.client),l=Kn(r,i.clock),o=r[l];return i.clock!==o.id.clock+o.length-1&&o.constructor!==vn&&r.splice(l+1,0,Hc(n,o,i.clock-o.id.clock+1)),o},gM=(n,t,i)=>{const r=n.clients.get(t.id.client);r[Kn(r,t.id.clock)]=i},gw=(n,t,i,r,l)=>{if(r===0)return;const o=i+r;let u=Gd(n,t,i),d;do d=t[u++],ot.deleteSet.clients.size===0&&!aR(t.afterState,(i,r)=>t.beforeState.get(r)!==i)?!1:(jp(t.deleteSet),uM(n,t),Bp(n,t.deleteSet),!0),dv=(n,t,i)=>{const r=t._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&Ws(n.changed,t,Hr).add(i)},yc=(n,t)=>{let i=n[t],r=n[t-1],l=t;for(;l>0;i=r,r=n[--l-1]){if(r.deleted===i.deleted&&r.constructor===i.constructor&&r.mergeWith(i)){i instanceof fe&&i.parentSub!==null&&i.parent._map.get(i.parentSub)===i&&i.parent._map.set(i.parentSub,r);continue}break}const o=t-l;return o&&n.splice(t+1-o,o),o},mM=(n,t,i)=>{for(const[r,l]of n.clients.entries()){const o=t.clients.get(r);for(let u=l.length-1;u>=0;u--){const d=l[u],p=d.clock+d.len;for(let g=Kn(o,d.clock),y=o[g];g{n.clients.forEach((i,r)=>{const l=t.clients.get(r);for(let o=i.length-1;o>=0;o--){const u=i[o],d=Rb(l.length-1,1+Kn(l,u.clock+u.len-1));for(let p=d,g=l[p];p>0&&g.id.clock>=u.clock;g=l[p])p-=1+yc(l,p)}})},yw=(n,t)=>{if(td.push(()=>{(g._item===null||!g._item.deleted)&&g._callObserver(i,p)})),d.push(()=>{i.changedParentTypes.forEach((p,g)=>{g._dEH.l.length>0&&(g._item===null||!g._item.deleted)&&(p=p.filter(y=>y.target._item===null||!y.target._item.deleted),p.forEach(y=>{y.currentTarget=g,y._path=null}),p.sort((y,m)=>y.path.length-m.path.length),d.push(()=>{hw(g._dEH,p,i)}))}),d.push(()=>r.emit(`afterTransaction`,[i,r])),d.push(()=>{i._needFormattingCleanup&&BM(i)})}),Op(d,[])}finally{r.gc&&mM(o,l,r.gcFilter),SM(o,l),i.afterState.forEach((y,m)=>{const v=i.beforeState.get(m)||0;if(v!==y){const w=l.clients.get(m),b=Yr(Kn(w,v),1);for(let E=w.length-1;E>=b;)E-=1+yc(w,E)}});for(let y=u.length-1;y>=0;y--){const{client:m,clock:v}=u[y].id,w=l.clients.get(m),b=Kn(w,v);b+11||b>0&&yc(w,b)}if(!i.local&&i.afterState.get(r.clientID)!==i.beforeState.get(r.clientID)&&(XD(zp,ew,`[yjs] `,nw,sw,`Changed the client-id because another client seems to be using it.`),r.clientID=cw()),r.emit(`afterTransactionCleanup`,[i,r]),r._observers.has(`update`)){const y=new rM;hv(y,i)&&r.emit(`update`,[y.toUint8Array(),i.origin,r,i])}if(r._observers.has(`updateV2`)){const y=new ru;hv(y,i)&&r.emit(`updateV2`,[y.toUint8Array(),i.origin,r,i])}const{subdocsAdded:d,subdocsLoaded:p,subdocsRemoved:g}=i;(d.size>0||g.size>0||p.size>0)&&(d.forEach(y=>{y.clientID=r.clientID,y.collectionid==null&&(y.collectionid=r.collectionid),r.subdocs.add(y)}),g.forEach(y=>r.subdocs.delete(y)),r.emit(`subdocs`,[{loaded:p,added:d,removed:g},r,i]),g.forEach(y=>y.destroy())),n.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,n])):yw(n,t+1)}}},$t=(n,t,i=null,r=!0)=>{const l=n._transactionCleanups;let o=!1,u=null;n._transaction===null&&(o=!0,n._transaction=new yM(n,i,r),l.push(n._transaction),l.length===1&&n.emit(`beforeAllTransactions`,[n]),n.emit(`beforeTransaction`,[n._transaction,n]));try{u=t(n._transaction)}finally{if(o){const d=n._transaction===l[0];n._transaction=null,d&&yw(l,0)}}return u};function*vM(n){const t=Ot(n.restDecoder);for(let i=0;i{if(n.constructor===vn){const{client:i,clock:r}=n.id;return new vn(Rt(i,r+t),n.length-t)}else if(n.constructor===_n){const{client:i,clock:r}=n.id;return new _n(Rt(i,r+t),n.length-t)}else{const i=n,{client:r,clock:l}=i.id;return new fe(Rt(r,l+t),null,Rt(r,l+t-1),null,i.rightOrigin,i.parent,i.parentSub,i.content.splice(t))}},pv=(n,t=zc,i=ru)=>{if(n.length===1)return n[0];const r=n.map(y=>new t(xp(y)));let l=r.map(y=>new bM(y,!0)),o=null;const u=new i,d=new wM(u);for(;l=l.filter(v=>v.curr!==null),l.sort((v,w)=>{if(v.curr.id.client===w.curr.id.client){const b=v.curr.id.clock-w.curr.id.clock;return b===0?v.curr.constructor===w.curr.constructor?0:v.curr.constructor===_n?1:-1:b}else return w.curr.id.client-v.curr.id.client}),l.length!==0;){const y=l[0],m=y.curr.id.client;if(o!==null){let v=y.curr,w=!1;for(;v!==null&&v.id.clock+v.length<=o.struct.id.clock+o.struct.length&&v.id.client>=o.struct.id.client;)v=y.next(),w=!0;if(v===null||v.id.client!==m||w&&v.id.clock>o.struct.id.clock+o.struct.length)continue;if(m!==o.struct.id.client)Fa(d,o.struct,o.offset),o={struct:v,offset:0},y.next();else if(o.struct.id.clock+o.struct.length0&&(o.struct.constructor===_n?o.struct.length-=b:v=EM(v,b)),o.struct.mergeWith(v)||(Fa(d,o.struct,o.offset),o={struct:v,offset:0},y.next())}}else o={struct:y.curr,offset:0},y.next();for(let v=y.curr;v!==null&&v.id.client===m&&v.id.clock===o.struct.id.clock+o.struct.length&&v.constructor!==_n;v=y.next())Fa(d,o.struct,o.offset),o={struct:v,offset:0}}o!==null&&(Fa(d,o.struct,o.offset),o=null),CM(d);const p=r.map(y=>tM(y)),g=PD(p);return Bp(u,g),u.toUint8Array()},mw=n=>{n.written>0&&(n.clientStructs.push({written:n.written,restEncoder:In(n.encoder.restEncoder)}),n.encoder.restEncoder=Xc(),n.written=0)},Fa=(n,t,i)=>{n.written>0&&n.currClient!==t.id.client&&mw(n),n.written===0&&(n.currClient=t.id.client,n.encoder.writeClient(t.id.client),Dt(n.encoder.restEncoder,t.id.clock+i)),t.write(n.encoder,i),n.written++},CM=n=>{mw(n);const t=n.encoder.restEncoder;Dt(t,n.clientStructs.length);for(let i=0;i{if(l!==null){const o=i._map.get(l);let u,d;if(this.adds(o)){let p=o.left;for(;p!==null&&this.adds(p);)p=p.left;if(this.deletes(o))if(p!==null&&this.deletes(p))u=`delete`,d=Ph(p.content.getContent());else return;else p!==null&&this.deletes(p)?(u=`update`,d=Ph(p.content.getContent())):(u=`add`,d=void 0)}else if(this.deletes(o))u=`delete`,d=Ph(o.content.getContent());else return;t.set(l,{action:u,oldValue:d})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw qn(gv);const i=this.target,r=Hr(),l=Hr(),o=[];if(t={added:r,deleted:l,delta:o,keys:this.keys},this.transaction.changed.get(i).has(null)){let d=null;const p=()=>{d&&o.push(d)};for(let g=i._start;g!==null;g=g.right)g.deleted?this.deletes(g)&&!this.adds(g)&&((d===null||d.delete===void 0)&&(p(),d={delete:0}),d.delete+=g.length,l.add(g)):this.adds(g)?((d===null||d.insert===void 0)&&(p(),d={insert:[]}),d.insert=d.insert.concat(g.content.getContent()),r.add(g)):((d===null||d.retain===void 0)&&(p(),d={retain:0}),d.retain+=g.length);d!==null&&d.retain===void 0&&p()}this._changes=t}return t}}const xM=(n,t)=>{const i=[];for(;t._item!==null&&t!==n;){if(t._item.parentSub!==null)i.unshift(t._item.parentSub);else{let r=0,l=t._item.parent._start;for(;l!==t._item&&l!==null;)!l.deleted&&l.countable&&(r+=l.length),l=l.right;i.unshift(r)}t=t._item.parent}return i},Re=()=>{JD(`Invalid access: Add Yjs type to a document before reading data.`)},Sw=80;let Ip=0;class _M{constructor(t,i){t.marker=!0,this.p=t,this.index=i,this.timestamp=Ip++}}const TM=n=>{n.timestamp=Ip++},vw=(n,t,i)=>{n.p.marker=!1,n.p=t,t.marker=!0,n.index=i,n.timestamp=Ip++},AM=(n,t,i)=>{if(n.length>=Sw){const r=n.reduce((l,o)=>l.timestamp{if(n._start===null||t===0||n._searchMarker===null)return null;const i=n._searchMarker.length===0?null:n._searchMarker.reduce((o,u)=>hc(t-o.index)t;)r=r.left,!r.deleted&&r.countable&&(l-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(l-=r.length);return i!==null&&hc(i.index-l){for(let r=n.length-1;r>=0;r--){const l=n[r];if(i>0){let o=l.p;for(o.marker=!1;o&&(o.deleted||!o.countable);)o=o.left,o&&!o.deleted&&o.countable&&(l.index-=o.length);if(o===null||o.marker===!0){n.splice(r,1);continue}l.p=o,o.marker=!0}(t0&&t===l.index)&&(l.index=Yr(t,l.index+i))}},ou=(n,t,i)=>{const r=n,l=t.changedParentTypes;for(;Ws(l,n,()=>[]).push(i),n._item!==null;)n=n._item.parent;hw(r._eH,i,t)};class _e{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ov(),this._dEH=ov(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,i){this.doc=t,this._item=i}_copy(){throw On()}clone(){throw On()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,i){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){cv(this._eH,t)}observeDeep(t){cv(this._dEH,t)}unobserve(t){uv(this._eH,t)}unobserveDeep(t){uv(this._dEH,t)}toJSON(){}}const bw=(n,t,i)=>{n.doc??Re(),t<0&&(t=n._length+t),i<0&&(i=n._length+i);let r=i-t;const l=[];let o=n._start;for(;o!==null&&r>0;){if(o.countable&&!o.deleted){const u=o.content.getContent();if(u.length<=t)t-=u.length;else{for(let d=t;d0;d++)l.push(u[d]),r--;t=0}}o=o.right}return l},ww=n=>{n.doc??Re();const t=[];let i=n._start;for(;i!==null;){if(i.countable&&!i.deleted){const r=i.content.getContent();for(let l=0;l{let i=0,r=n._start;for(n.doc??Re();r!==null;){if(r.countable&&!r.deleted){const l=r.content.getContent();for(let o=0;o{const i=[];return bl(n,(r,l)=>{i.push(t(r,l,n))}),i},OM=n=>{let t=n._start,i=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(i===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};i=t.content.getContent(),r=0,t=t.right}const l=i[r++];return i.length<=r&&(i=null),{done:!1,value:l}}}},Cw=(n,t)=>{n.doc??Re();const i=lu(n,t);let r=n._start;for(i!==null&&(r=i.p,t-=i.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t{let l=i;const o=n.doc,u=o.clientID,d=o.store,p=i===null?t._start:i.right;let g=[];const y=()=>{g.length>0&&(l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new xi(g)),l.integrate(n,0),g=[])};r.forEach(m=>{if(m===null)g.push(m);else switch(m.constructor){case Number:case Object:case Boolean:case Array:case String:g.push(m);break;default:switch(y(),m.constructor){case Uint8Array:case ArrayBuffer:l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new Ol(new Uint8Array(m))),l.integrate(n,0);break;case Qr:l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new Rl(m)),l.integrate(n,0);break;default:if(m instanceof _e)l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new Ss(m)),l.integrate(n,0);else throw new Error(`Unexpected content type in insert operation`)}}}),y()},xw=()=>qn(`Length exceeded!`),_w=(n,t,i,r)=>{if(i>t._length)throw xw();if(i===0)return t._searchMarker&&vl(t._searchMarker,i,r.length),Nc(n,t,null,r);const l=i,o=lu(t,i);let u=t._start;for(o!==null&&(u=o.p,i-=o.index,i===0&&(u=u.prev,i+=u&&u.countable&&!u.deleted?u.length:0));u!==null;u=u.right)if(!u.deleted&&u.countable){if(i<=u.length){i{let l=(t._searchMarker||[]).reduce((o,u)=>u.index>o.index?u:o,{index:0,p:t._start}).p;if(l)for(;l.right;)l=l.right;return Nc(n,t,l,i)},Tw=(n,t,i,r)=>{if(r===0)return;const l=i,o=r,u=lu(t,i);let d=t._start;for(u!==null&&(d=u.p,i-=u.index);d!==null&&i>0;d=d.right)!d.deleted&&d.countable&&(i0&&d!==null;)d.deleted||(r0)throw xw();t._searchMarker&&vl(t._searchMarker,l,-o+r)},jc=(n,t,i)=>{const r=t._map.get(i);r!==void 0&&r.delete(n)},Hp=(n,t,i,r)=>{const l=t._map.get(i)||null,o=n.doc,u=o.clientID;let d;if(r==null)d=new xi([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:d=new xi([r]);break;case Uint8Array:d=new Ol(r);break;case Qr:d=new Rl(r);break;default:if(r instanceof _e)d=new Ss(r);else throw new Error(`Unexpected content type`)}new fe(Rt(u,me(o.store,u)),l,l&&l.lastId,null,null,t,i,d).integrate(n,0)},qp=(n,t)=>{n.doc??Re();const i=n._map.get(t);return i!==void 0&&!i.deleted?i.content.getContent()[i.length-1]:void 0},Aw=n=>{const t={};return n.doc??Re(),n._map.forEach((i,r)=>{i.deleted||(t[r]=i.content.getContent()[i.length-1])}),t},Ow=(n,t)=>{n.doc??Re();const i=n._map.get(t);return i!==void 0&&!i.deleted},DM=(n,t)=>{const i={};return n._map.forEach((r,l)=>{let o=r;for(;o!==null&&(!t.sv.has(o.id.client)||o.id.clock>=(t.sv.get(o.id.client)||0));)o=o.left;o!==null&&Cr(o,t)&&(i[l]=o.content.getContent()[o.length-1])}),i},nc=n=>(n.doc??Re(),ZD(n._map.entries(),t=>!t[1].deleted));class MM extends au{}class Ur extends _e{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const i=new Ur;return i.push(t),i}_integrate(t,i){super._integrate(t,i),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ur}clone(){const t=new Ur;return t.insert(0,this.toArray().map(i=>i instanceof _e?i.clone():i)),t}get length(){return this.doc??Re(),this._length}_callObserver(t,i){super._callObserver(t,i),ou(this,t,new MM(this,t))}insert(t,i){this.doc!==null?$t(this.doc,r=>{_w(r,this,t,i)}):this._prelimContent.splice(t,0,...i)}push(t){this.doc!==null?$t(this.doc,i=>{RM(i,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,i=1){this.doc!==null?$t(this.doc,r=>{Tw(r,this,t,i)}):this._prelimContent.splice(t,i)}get(t){return Cw(this,t)}toArray(){return ww(this)}slice(t=0,i=this.length){return bw(this,t,i)}toJSON(){return this.map(t=>t instanceof _e?t.toJSON():t)}map(t){return Ew(this,t)}forEach(t){bl(this,t)}[Symbol.iterator](){return OM(this)}_write(t){t.writeTypeRef(n2)}}const kM=n=>new Ur;class UM extends au{constructor(t,i,r){super(t,i),this.keysChanged=r}}class Vr extends _e{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,i){super._integrate(t,i),this._prelimContent.forEach((r,l)=>{this.set(l,r)}),this._prelimContent=null}_copy(){return new Vr}clone(){const t=new Vr;return this.forEach((i,r)=>{t.set(r,i instanceof _e?i.clone():i)}),t}_callObserver(t,i){ou(this,t,new UM(this,t,i))}toJSON(){this.doc??Re();const t={};return this._map.forEach((i,r)=>{if(!i.deleted){const l=i.content.getContent()[i.length-1];t[r]=l instanceof _e?l.toJSON():l}}),t}get size(){return[...nc(this)].length}keys(){return ad(nc(this),t=>t[0])}values(){return ad(nc(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return ad(nc(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Re(),this._map.forEach((i,r)=>{i.deleted||t(i.content.getContent()[i.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?$t(this.doc,i=>{jc(i,this,t)}):this._prelimContent.delete(t)}set(t,i){return this.doc!==null?$t(this.doc,r=>{Hp(r,this,t,i)}):this._prelimContent.set(t,i),i}get(t){return qp(this,t)}has(t){return Ow(this,t)}clear(){this.doc!==null?$t(this.doc,t=>{this.forEach(function(i,r,l){jc(t,l,r)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(s2)}}const zM=n=>new Vr,Qs=(n,t)=>n===t||typeof n==`object`&&typeof t==`object`&&n&&t&&ZR(n,t);class Yd{constructor(t,i,r,l){this.left=t,this.right=i,this.index=r,this.currentAttributes=l}forward(){switch(this.right===null&&bn(),this.right.content.constructor){case he:this.right.deleted||Xr(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const yv=(n,t,i)=>{for(;t.right!==null&&i>0;){switch(t.right.content.constructor){case he:t.right.deleted||Xr(t.currentAttributes,t.right.content);break;default:t.right.deleted||(i{const l=new Map,o=r?lu(t,i):null;if(o){const u=new Yd(o.p.left,o.p,o.index,l);return yv(n,u,i-o.index)}else{const u=new Yd(null,t._start,0,l);return yv(n,u,i)}},Rw=(n,t,i,r)=>{for(;i.right!==null&&(i.right.deleted===!0||i.right.content.constructor===he&&Qs(r.get(i.right.content.key),i.right.content.value));)i.right.deleted||r.delete(i.right.content.key),i.forward();const l=n.doc,o=l.clientID;r.forEach((u,d)=>{const p=i.left,g=i.right,y=new fe(Rt(o,me(l.store,o)),p,p&&p.lastId,g,g&&g.id,t,null,new he(d,u));y.integrate(n,0),i.right=y,i.forward()})},Xr=(n,t)=>{const{key:i,value:r}=t;r===null?n.delete(i):n.set(i,r)},Dw=(n,t)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===he&&Qs(t[n.right.content.key]??null,n.right.content.value)))break;n.forward()}},Mw=(n,t,i,r)=>{const l=n.doc,o=l.clientID,u=new Map;for(const d in r){const p=r[d],g=i.currentAttributes.get(d)??null;if(!Qs(g,p)){u.set(d,g);const{left:y,right:m}=i;i.right=new fe(Rt(o,me(l.store,o)),y,y&&y.lastId,m,m&&m.id,t,null,new he(d,p)),i.right.integrate(n,0),i.forward()}}return u},od=(n,t,i,r,l)=>{i.currentAttributes.forEach((v,w)=>{l[w]===void 0&&(l[w]=null)});const o=n.doc,u=o.clientID;Dw(i,l);const d=Mw(n,t,i,l),p=r.constructor===String?new Vn(r):r instanceof _e?new Ss(r):new Mi(r);let{left:g,right:y,index:m}=i;t._searchMarker&&vl(t._searchMarker,i.index,p.getLength()),y=new fe(Rt(u,me(o.store,u)),g,g&&g.lastId,y,y&&y.id,t,null,p),y.integrate(n,0),i.right=y,i.index=m,i.forward(),Rw(n,t,i,d)},mv=(n,t,i,r,l)=>{const o=n.doc,u=o.clientID;Dw(i,l);const d=Mw(n,t,i,l);t:for(;i.right!==null&&(r>0||d.size>0&&(i.right.deleted||i.right.content.constructor===he));){if(!i.right.deleted)switch(i.right.content.constructor){case he:{const{key:p,value:g}=i.right.content,y=l[p];if(y!==void 0){if(Qs(y,g))d.delete(p);else{if(r===0)break t;d.set(p,g)}i.right.delete(n)}else i.currentAttributes.set(p,g);break}default:r0){let p=``;for(;r>0;r--)p+=`
+`;i.right=new fe(Rt(u,me(o.store,u)),i.left,i.left&&i.left.lastId,i.right,i.right&&i.right.id,t,null,new Vn(p)),i.right.integrate(n,0),i.forward()}Rw(n,t,i,d)},kw=(n,t,i,r,l)=>{let o=t;const u=An();for(;o&&(!o.countable||o.deleted);){if(!o.deleted&&o.content.constructor===he){const g=o.content;u.set(g.key,g)}o=o.right}let d=0,p=!1;for(;t!==o;){if(i===t&&(p=!0),!t.deleted){const g=t.content;switch(g.constructor){case he:{const{key:y,value:m}=g,v=r.get(y)??null;(u.get(y)!==g||v===m)&&(t.delete(n),d++,!p&&(l.get(y)??null)===m&&v!==m&&(v===null?l.delete(y):l.set(y,v))),!p&&!t.deleted&&Xr(l,g);break}}}t=t.right}return d},NM=(n,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const i=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===he){const r=t.content.key;i.has(r)?t.delete(n):i.add(r)}t=t.left}},jM=n=>{let t=0;return $t(n.doc,i=>{let r=n._start,l=n._start,o=An();const u=Ld(o);for(;l;){if(l.deleted===!1)switch(l.content.constructor){case he:Xr(u,l.content);break;default:t+=kw(i,r,l,o,u),o=Ld(u),r=l;break}l=l.right}}),t},BM=n=>{const t=new Set,i=n.doc;for(const[r,l]of n.afterState.entries()){const o=n.beforeState.get(r)||0;l!==o&&gw(n,i.store.clients.get(r),o,l,u=>{!u.deleted&&u.content.constructor===he&&u.constructor!==vn&&t.add(u.parent)})}$t(i,r=>{lw(n,n.deleteSet,l=>{if(l instanceof vn||!l.parent._hasFormatting||t.has(l.parent))return;const o=l.parent;l.content.constructor===he?t.add(o):NM(r,l)});for(const l of t)jM(l)})},Sv=(n,t,i)=>{const r=i,l=Ld(t.currentAttributes),o=t.right;for(;i>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Ss:case Mi:case Vn:i{l===null?this.childListChanged=!0:this.keysChanged.add(l)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,i=[];$t(t,r=>{const l=new Map,o=new Map;let u=this.target._start,d=null;const p={};let g=``,y=0,m=0;const v=()=>{if(d!==null){let w=null;switch(d){case`delete`:m>0&&(w={delete:m}),m=0;break;case`insert`:(typeof g==`object`||g.length>0)&&(w={insert:g},l.size>0&&(w.attributes={},l.forEach((b,E)=>{b!==null&&(w.attributes[E]=b)}))),g=``;break;case`retain`:y>0&&(w={retain:y},JR(p)||(w.attributes=FR({},p))),y=0;break}w&&i.push(w),d=null}};for(;u!==null;){switch(u.content.constructor){case Ss:case Mi:this.adds(u)?this.deletes(u)||(v(),d=`insert`,g=u.content.getContent()[0],v()):this.deletes(u)?(d!==`delete`&&(v(),d=`delete`),m+=1):u.deleted||(d!==`retain`&&(v(),d=`retain`),y+=1);break;case Vn:this.adds(u)?this.deletes(u)||(d!==`insert`&&(v(),d=`insert`),g+=u.content.str):this.deletes(u)?(d!==`delete`&&(v(),d=`delete`),m+=u.length):u.deleted||(d!==`retain`&&(v(),d=`retain`),y+=u.length);break;case he:{const{key:w,value:b}=u.content;if(this.adds(u)){if(!this.deletes(u)){const E=l.get(w)??null;Qs(E,b)?b!==null&&u.delete(r):(d===`retain`&&v(),Qs(b,o.get(w)??null)?delete p[w]:p[w]=b)}}else if(this.deletes(u)){o.set(w,b);const E=l.get(w)??null;Qs(E,b)||(d===`retain`&&v(),p[w]=E)}else if(!u.deleted){o.set(w,b);const E=p[w];E!==void 0&&(Qs(E,b)?E!==null&&u.delete(r):(d===`retain`&&v(),b===null?delete p[w]:p[w]=b))}u.deleted||(d===`insert`&&v(),Xr(l,u.content));break}}u=u.right}for(v();i.length>0;){const w=i[i.length-1];if(w.retain!==void 0&&w.attributes===void 0)i.pop();else break}}),this._delta=i}return this._delta}}class $r extends _e{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Re(),this._length}_integrate(t,i){super._integrate(t,i);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new $r}clone(){const t=new $r;return t.applyDelta(this.toDelta()),t}_callObserver(t,i){super._callObserver(t,i);const r=new LM(this,t,i);ou(this,t,r),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Re();let t=``,i=this._start;for(;i!==null;)!i.deleted&&i.countable&&i.content.constructor===Vn&&(t+=i.content.str),i=i.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:i=!0}={}){this.doc!==null?$t(this.doc,r=>{const l=new Yd(null,this._start,0,new Map);for(let o=0;o0)&&od(r,this,l,d,u.attributes||{})}else u.retain!==void 0?mv(r,this,l,u.retain,u.attributes||{}):u.delete!==void 0&&Sv(r,l,u.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,i,r){this.doc??Re();const l=[],o=new Map,u=this.doc;let d=``,p=this._start;function g(){if(d.length>0){const m={};let v=!1;o.forEach((b,E)=>{v=!0,m[E]=b});const w={insert:d};v&&(w.attributes=m),l.push(w),d=``}}const y=()=>{for(;p!==null;){if(Cr(p,t)||i!==void 0&&Cr(p,i))switch(p.content.constructor){case Vn:{const m=o.get(`ychange`);t!==void 0&&!Cr(p,t)?(m===void 0||m.user!==p.id.client||m.type!==`removed`)&&(g(),o.set(`ychange`,r?r(`removed`,p.id):{type:`removed`})):i!==void 0&&!Cr(p,i)?(m===void 0||m.user!==p.id.client||m.type!==`added`)&&(g(),o.set(`ychange`,r?r(`added`,p.id):{type:`added`})):m!==void 0&&(g(),o.delete(`ychange`)),d+=p.content.str;break}case Ss:case Mi:{g();const m={insert:p.content.getContent()[0]};if(o.size>0){const v={};m.attributes=v,o.forEach((w,b)=>{v[b]=w})}l.push(m);break}case he:Cr(p,t)&&(g(),Xr(o,p.content));break}p=p.right}g()};return t||i?$t(u,m=>{t&&$d(m,t),i&&$d(m,i),y()},`cleanup`):y(),l}insert(t,i,r){if(i.length<=0)return;const l=this.doc;l!==null?$t(l,o=>{const u=sc(o,this,t,!r);r||(r={},u.currentAttributes.forEach((d,p)=>{r[p]=d})),od(o,this,u,i,r)}):this._pending.push(()=>this.insert(t,i,r))}insertEmbed(t,i,r){const l=this.doc;l!==null?$t(l,o=>{const u=sc(o,this,t,!r);od(o,this,u,i,r||{})}):this._pending.push(()=>this.insertEmbed(t,i,r||{}))}delete(t,i){if(i===0)return;const r=this.doc;r!==null?$t(r,l=>{Sv(l,sc(l,this,t,!0),i)}):this._pending.push(()=>this.delete(t,i))}format(t,i,r){if(i===0)return;const l=this.doc;l!==null?$t(l,o=>{const u=sc(o,this,t,!1);u.right!==null&&mv(o,this,u,i,r)}):this._pending.push(()=>this.format(t,i,r))}removeAttribute(t){this.doc!==null?$t(this.doc,i=>{jc(i,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,i){this.doc!==null?$t(this.doc,r=>{Hp(r,this,t,i)}):this._pending.push(()=>this.setAttribute(t,i))}getAttribute(t){return qp(this,t)}getAttributes(){return Aw(this)}_write(t){t.writeTypeRef(i2)}}const IM=n=>new $r;class cd{constructor(t,i=()=>!0){this._filter=i,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Re()}[Symbol.iterator](){return this}next(){let t=this._currentNode,i=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(i)))do if(i=t.content.type,!t.deleted&&(i.constructor===Gr||i.constructor===Ci)&&i._start!==null)t=i._start;else for(;t!==null;){const r=t.next;if(r!==null){t=r;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class Ci extends _e{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,i){super._integrate(t,i),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ci}clone(){const t=new Ci;return t.insert(0,this.toArray().map(i=>i instanceof _e?i.clone():i)),t}get length(){return this.doc??Re(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new cd(this,t)}querySelector(t){t=t.toUpperCase();const r=new cd(this,l=>l.nodeName&&l.nodeName.toUpperCase()===t).next();return r.done?null:r.value}querySelectorAll(t){return t=t.toUpperCase(),Ei(new cd(this,i=>i.nodeName&&i.nodeName.toUpperCase()===t))}_callObserver(t,i){ou(this,t,new KM(this,i,t))}toString(){return Ew(this,t=>t.toString()).join(``)}toJSON(){return this.toString()}toDOM(t=document,i={},r){const l=t.createDocumentFragment();return r!==void 0&&r._createAssociation(l,this),bl(this,o=>{l.insertBefore(o.toDOM(t,i,r),null)}),l}insert(t,i){this.doc!==null?$t(this.doc,r=>{_w(r,this,t,i)}):this._prelimContent.splice(t,0,...i)}insertAfter(t,i){if(this.doc!==null)$t(this.doc,r=>{const l=t&&t instanceof _e?t._item:t;Nc(r,this,l,i)});else{const r=this._prelimContent,l=t===null?0:r.findIndex(o=>o===t)+1;if(l===0&&t!==null)throw qn(`Reference item not found`);r.splice(l,0,...i)}}delete(t,i=1){this.doc!==null?$t(this.doc,r=>{Tw(r,this,t,i)}):this._prelimContent.splice(t,i)}toArray(){return ww(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return Cw(this,t)}slice(t=0,i=this.length){return bw(this,t,i)}forEach(t){bl(this,t)}_write(t){t.writeTypeRef(a2)}}const HM=n=>new Ci;class Gr extends Ci{constructor(t=`UNDEFINED`){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,i){super._integrate(t,i),this._prelimAttrs.forEach((r,l)=>{this.setAttribute(l,r)}),this._prelimAttrs=null}_copy(){return new Gr(this.nodeName)}clone(){const t=new Gr(this.nodeName),i=this.getAttributes();return XR(i,(r,l)=>{t.setAttribute(l,r)}),t.insert(0,this.toArray().map(r=>r instanceof _e?r.clone():r)),t}toString(){const t=this.getAttributes(),i=[],r=[];for(const d in t)r.push(d);r.sort();const l=r.length;for(let d=0;d0?` `+i.join(` `):``;return`<${o}${u}>${super.toString()}${o}>`}removeAttribute(t){this.doc!==null?$t(this.doc,i=>{jc(i,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,i){this.doc!==null?$t(this.doc,r=>{Hp(r,this,t,i)}):this._prelimAttrs.set(t,i)}getAttribute(t){return qp(this,t)}hasAttribute(t){return Ow(this,t)}getAttributes(t){return t?DM(this,t):Aw(this)}toDOM(t=document,i={},r){const l=t.createElement(this.nodeName),o=this.getAttributes();for(const u in o){const d=o[u];typeof d==`string`&&l.setAttribute(u,d)}return bl(this,u=>{l.appendChild(u.toDOM(t,i,r))}),r!==void 0&&r._createAssociation(l,this),l}_write(t){t.writeTypeRef(r2),t.writeKey(this.nodeName)}}const qM=n=>new Gr(n.readKey());class KM extends au{constructor(t,i,r){super(t,r),this.childListChanged=!1,this.attributesChanged=new Set,i.forEach(l=>{l===null?this.childListChanged=!0:this.attributesChanged.add(l)})}}class Bc extends Vr{constructor(t){super(),this.hookName=t}_copy(){return new Bc(this.hookName)}clone(){const t=new Bc(this.hookName);return this.forEach((i,r)=>{t.set(r,i)}),t}toDOM(t=document,i={},r){const l=i[this.hookName];let o;return l!==void 0?o=l.createDom(this):o=document.createElement(this.hookName),o.setAttribute(`data-yjs-hook`,this.hookName),r!==void 0&&r._createAssociation(o,this),o}_write(t){t.writeTypeRef(l2),t.writeKey(this.hookName)}}const VM=n=>new Bc(n.readKey());class Lc extends $r{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Lc}clone(){const t=new Lc;return t.applyDelta(this.toDelta()),t}toDOM(t=document,i,r){const l=t.createTextNode(this.toString());return r!==void 0&&r._createAssociation(l,this),l}toString(){return this.toDelta().map(t=>{const i=[];for(const l in t.attributes){const o=[];for(const u in t.attributes[l])o.push({key:u,value:t.attributes[l][u]});o.sort((u,d)=>u.keyl.nodeName`}r+=t.insert;for(let l=i.length-1;l>=0;l--)r+=`${i[l].nodeName}>`;return r}).join(``)}toJSON(){return this.toString()}_write(t){t.writeTypeRef(o2)}}const $M=n=>new Lc;class Kp{constructor(t,i){this.id=t,this.length=i}get deleted(){throw On()}mergeWith(t){return!1}write(t,i,r){throw On()}integrate(t,i){throw On()}}const GM=0;class vn extends Kp{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,i){i>0&&(this.id.clock+=i,this.length-=i),pw(t.doc.store,this)}write(t,i){t.writeInfo(GM),t.writeLen(this.length-i)}getMissing(t,i){return null}}class Ol{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ol(this.content)}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){}delete(t){}gc(t){}write(t,i){t.writeBuf(this.content)}getRef(){return 3}}const YM=n=>new Ol(n.readBuf());class wl{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new wl(this.len)}splice(t){const i=new wl(this.len-t);return this.len=t,i}mergeWith(t){return this.len+=t.len,!0}integrate(t,i){Uc(t.deleteSet,i.id.client,i.id.clock,this.len),i.markDeleted()}delete(t){}gc(t){}write(t,i){t.writeLen(this.len-i)}getRef(){return 1}}const FM=n=>new wl(n.readLen()),Uw=(n,t)=>new Qr({guid:n,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Rl{constructor(t){t._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=t;const i={};this.opts=i,t.gc||(i.gc=!1),t.autoLoad&&(i.autoLoad=!0),t.meta!==null&&(i.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Rl(Uw(this.doc.guid,this.opts))}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){this.doc._item=i,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,i){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const QM=n=>new Rl(Uw(n.readString(),n.readAny()));class Mi{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Mi(this.embed)}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){}delete(t){}gc(t){}write(t,i){t.writeJSON(this.embed)}getRef(){return 5}}const XM=n=>new Mi(n.readJSON());class he{constructor(t,i){this.key=t,this.value=i}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new he(this.key,this.value)}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){const r=i.parent;r._searchMarker=null,r._hasFormatting=!0}delete(t){}gc(t){}write(t,i){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const JM=n=>new he(n.readKey(),n.readJSON());class Ic{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ic(this.arr)}splice(t){const i=new Ic(this.arr.slice(t));return this.arr=this.arr.slice(0,t),i}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,i){}delete(t){}gc(t){}write(t,i){const r=this.arr.length;t.writeLen(r-i);for(let l=i;l{const t=n.readLen(),i=[];for(let r=0;r{const t=n.readLen(),i=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,i.str=`�`+i.str.slice(1)),i}mergeWith(t){return this.str+=t.str,!0}integrate(t,i){}delete(t){}gc(t){}write(t,i){t.writeString(i===0?this.str:this.str.slice(i))}getRef(){return 4}}const t2=n=>new Vn(n.readString()),e2=[kM,zM,IM,qM,HM,VM,$M],n2=0,s2=1,i2=2,r2=3,a2=4,l2=5,o2=6;class Ss{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Ss(this.type._copy())}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){this.type._integrate(t.doc,i)}delete(t){let i=this.type._start;for(;i!==null;)i.deleted?i.id.clock<(t.beforeState.get(i.id.client)||0)&&t._mergeStructs.push(i):i.delete(t),i=i.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(t.beforeState.get(r.id.client)||0)&&t._mergeStructs.push(r):r.delete(t)}),t.changed.delete(this.type)}gc(t){let i=this.type._start;for(;i!==null;)i.gc(t,!0),i=i.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(t,!0),r=r.left}),this.type._map=new Map}write(t,i){this.type._write(t)}getRef(){return 7}}const c2=n=>new Ss(e2[n.readTypeRef()](n)),Hc=(n,t,i)=>{const{client:r,clock:l}=t.id,o=new fe(Rt(r,l+i),t,Rt(r,l+i-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(i));return t.deleted&&o.markDeleted(),t.keep&&(o.keep=!0),t.redone!==null&&(o.redone=Rt(t.redone.client,t.redone.clock+i)),t.right=o,o.right!==null&&(o.right.left=o),n._mergeStructs.push(o),o.parentSub!==null&&o.right===null&&o.parent._map.set(o.parentSub,o),t.length=i,o};class fe extends Kp{constructor(t,i,r,l,o,u,d,p){super(t,p.getLength()),this.origin=r,this.left=i,this.right=l,this.rightOrigin=o,this.parent=u,this.parentSub=d,this.redone=null,this.content=p,this.info=this.content.isCountable()?QS:0}set marker(t){(this.info&ed)>0!==t&&(this.info^=ed)}get marker(){return(this.info&ed)>0}get keep(){return(this.info&FS)>0}set keep(t){this.keep!==t&&(this.info^=FS)}get countable(){return(this.info&QS)>0}get deleted(){return(this.info&td)>0}set deleted(t){this.deleted!==t&&(this.info^=td)}markDeleted(){this.info|=td}getMissing(t,i){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=me(i,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=me(i,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===kr&&this.id.client!==this.parent.client&&this.parent.clock>=me(i,this.parent.client))return this.parent.client;if(this.origin&&(this.left=fv(t,i,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Zs(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===vn||this.right&&this.right.constructor===vn)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===fe?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===fe&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===kr){const r=ld(i,this.parent);r.constructor===vn?this.parent=null:this.parent=r.content.type}return null}integrate(t,i){if(i>0&&(this.id.clock+=i,this.left=fv(t,t.doc.store,Rt(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(i),this.length-=i),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,l;if(r!==null)l=r.right;else if(this.parentSub!==null)for(l=this.parent._map.get(this.parentSub)||null;l!==null&&l.left!==null;)l=l.left;else l=this.parent._start;const o=new Set,u=new Set;for(;l!==null&&l!==this.right;){if(u.add(l),o.add(l),ec(this.origin,l.origin)){if(l.id.client{r.p===t&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const i=this.parent;this.countable&&this.parentSub===null&&(i._length-=this.length),this.markDeleted(),Uc(t.deleteSet,this.id.client,this.id.clock,this.length),dv(t,i,this.parentSub),this.content.delete(t)}}gc(t,i){if(!this.deleted)throw bn();this.content.gc(t),i?gM(t,this,new vn(this.id,this.length)):this.content=new wl(this.length)}write(t,i){const r=i>0?Rt(this.id.client,this.id.clock+i-1):this.origin,l=this.rightOrigin,o=this.parentSub,u=this.content.getRef()&Qc|(r===null?0:rn)|(l===null?0:gs)|(o===null?0:hl);if(t.writeInfo(u),r!==null&&t.writeLeftID(r),l!==null&&t.writeRightID(l),r===null&&l===null){const d=this.parent;if(d._item!==void 0){const p=d._item;if(p===null){const g=dM(d);t.writeParentInfo(!0),t.writeString(g)}else t.writeParentInfo(!1),t.writeLeftID(p.id)}else d.constructor===String?(t.writeParentInfo(!0),t.writeString(d)):d.constructor===kr?(t.writeParentInfo(!1),t.writeLeftID(d)):bn();o!==null&&t.writeString(o)}this.content.write(t,i)}}const zw=(n,t)=>u2[t&Qc](n),u2=[()=>{bn()},FM,ZM,YM,t2,XM,JM,c2,PM,QM,()=>{bn()}],f2=10;class _n extends Kp{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,i){bn()}write(t,i){t.writeInfo(f2),Dt(t.restEncoder,this.length-i)}getMissing(t,i){return null}}const Nw=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},jw=`__ $YJS$ __`;Nw[jw]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`);Nw[jw]=!0;const Bw=Math.floor,h2=(n,t)=>nn>t?n:t,Lw=128,mc=127,p2=Number.MAX_SAFE_INTEGER,Iw=()=>new Set,Hw=Array.from,g2=n=>{const t=unescape(encodeURIComponent(n)),i=t.length,r=new Uint8Array(i);for(let l=0;lEl.encode(n),m2=El?y2:g2;let il=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});il&&il.decode(new Uint8Array).length===1&&(il=null);class S2{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const qw=()=>new S2,v2=n=>{let t=n.cpos;for(let i=0;i{const t=new Uint8Array(v2(n));let i=0;for(let r=0;r{const i=n.cbuf.length;n.cpos===i&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(i*2),n.cpos=0),n.cbuf[n.cpos++]=t},zr=(n,t)=>{for(;t>mc;)qc(n,Lw|mc&t),t=Bw(t/128);qc(n,mc&t)},Fd=new Uint8Array(3e4),b2=Fd.length/3,w2=(n,t)=>{if(t.length{const i=unescape(encodeURIComponent(t)),r=i.length;zr(n,r);for(let l=0;l{const i=n.cbuf.length,r=n.cpos,l=h2(i-r,t.length),o=t.length-l;n.cbuf.set(t.subarray(0,l),r),n.cpos+=l,o>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(d2(i*2,o)),n.cbuf.set(t.subarray(l)),n.cpos=o)},Vw=(n,t)=>{zr(n,t.byteLength),x2(n,t)},$w=n=>new Error(n),_2=$w(`Unexpected end of array`),T2=$w(`Integer out of Range`);class A2{constructor(t){this.arr=t,this.pos=0}}const Qd=n=>new A2(n),vv=n=>n.pos!==n.arr.length,O2=(n,t)=>{const i=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,t);return n.pos+=t,i},Xd=n=>O2(n,rl(n)),bv=n=>n.arr[n.pos++],rl=n=>{let t=0,i=1;const r=n.arr.length;for(;n.posp2)throw T2}throw _2},R2=n=>{let t=rl(n);if(t===0)return``;{let i=String.fromCodePoint(bv(n));if(--t<100)for(;t--;)i+=String.fromCodePoint(bv(n));else for(;t>0;){const r=t<1e4?t:1e4,l=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,i+=String.fromCodePoint.apply(null,l),t-=r}return decodeURIComponent(escape(i))}},D2=n=>il.decode(Xd(n)),M2=il?D2:R2,Kc=Date.now,Nr=()=>new Map,Gw=(n,t,i)=>{let r=n.get(t);return r===void 0&&n.set(t,r=i()),r};class k2{constructor(){this._observers=Nr()}on(t,i){return Gw(this._observers,t,Iw).add(i),i}once(t,i){const r=(...l)=>{this.off(t,r),i(...l)};this.on(t,r)}off(t,i){const r=this._observers.get(t);r!==void 0&&(r.delete(i),r.size===0&&this._observers.delete(t))}emit(t,i){return Hw((this._observers.get(t)||Nr()).values()).forEach(r=>r(...i))}destroy(){this._observers=Nr()}}class U2{constructor(){this._observers=Nr()}on(t,i){Gw(this._observers,t,Iw).add(i)}once(t,i){const r=(...l)=>{this.off(t,r),i(...l)};this.on(t,r)}off(t,i){const r=this._observers.get(t);r!==void 0&&(r.delete(i),r.size===0&&this._observers.delete(t))}emit(t,i){return Hw((this._observers.get(t)||Nr()).values()).forEach(r=>r(...i))}destroy(){this._observers=Nr()}}const wv=Symbol(`Equality`),z2=Object.keys,Ev=n=>z2(n).length,N2=(n,t)=>Object.prototype.hasOwnProperty.call(n,t),al=(n,t)=>{if(n===t)return!0;if(n==null||t==null||n.constructor!==t.constructor&&(n.constructor||Object)!==(t.constructor||Object))return!1;if(n[wv]!=null)return n[wv](t);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),t=new Uint8Array(t);case Uint8Array:{if(n.byteLength!==t.byteLength)return!1;for(let i=0;i{const i=Kc();this.getLocalState()!==null&&ud/2<=i-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((l,o)=>{o!==this.clientID&&ud<=i-l.lastUpdated&&this.states.has(o)&&r.push(o)}),r.length>0&&B2(this,r,`timeout`)},Bw(ud/10)),t.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const i=this.clientID,r=this.meta.get(i),l=r===void 0?0:r.clock+1,o=this.states.get(i);t===null?this.states.delete(i):this.states.set(i,t),this.meta.set(i,{clock:l,lastUpdated:Kc()});const u=[],d=[],p=[],g=[];t===null?g.push(i):o==null?t!=null&&u.push(i):(d.push(i),al(o,t)||p.push(i)),(u.length>0||p.length>0||g.length>0)&&this.emit(`change`,[{added:u,updated:p,removed:g},`local`]),this.emit(`update`,[{added:u,updated:d,removed:g},`local`])}setLocalStateField(t,i){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[t]:i})}getStates(){return this.states}}const B2=(n,t,i)=>{const r=[];for(let l=0;l0&&(n.emit(`change`,[{added:[],updated:[],removed:r},i]),n.emit(`update`,[{added:[],updated:[],removed:r},i]))},Cv=(n,t,i=n.states)=>{const r=t.length,l=qw();zr(l,r);for(let o=0;o{const r=Qd(t),l=Kc(),o=[],u=[],d=[],p=[],g=rl(r);for(let y=0;y0||d.length>0||p.length>0)&&n.emit(`change`,[{added:o,updated:d,removed:p},i]),(o.length>0||u.length>0||p.length>0)&&n.emit(`update`,[{added:o,updated:u,removed:p},i])},I2={disconnected:[`connecting`],connecting:[`connected`,`disconnected`],connected:[`disconnected`]},H2=15e3;var q2=class Sc extends k2{doc;awareness;baseUrl;docId;headers;liveMode;_state=`disconnected`;_connectionId=0;_ctx=null;_synced=!1;updatesStreamGeneration=0;updatesSubscription=null;sendingAwareness=!1;pendingAwareness=null;awarenessHeartbeat=null;constructor(t){super(),this.doc=t.doc,this.awareness=t.awareness,this.baseUrl=t.baseUrl.replace(/\/$/,``),this.docId=t.docId,this.headers=t.headers??{},this.liveMode=t.liveMode??`sse`,this.doc.on(`update`,this.handleDocumentUpdate),this.awareness&&this.awareness.on(`update`,this.handleAwarenessUpdate),t.connect!==!1&&this.connect()}get synced(){return this._synced}set synced(t){this._synced!==t&&(this._synced=t,this.emit(`synced`,[t]))}get connected(){return this._state===`connected`}get connecting(){return this._state===`connecting`}transition(t){return I2[this._state].includes(t)?(this._state=t,this.emit(`status`,[t]),!0):(console.warn(`[YjsProvider] Invalid transition: ${this._state} -> ${t}`),!1)}createConnectionContext(){this._connectionId+=1;const t={id:this._connectionId,controller:new AbortController,startOffset:`-1`,producer:null};return this._ctx=t,t}isStale(t){return this._ctx!==t||t.controller.signal.aborted}async connect(){if(this._state!==`disconnected`||!this.transition(`connecting`))return;const t=this.createConnectionContext();try{if(await this.ensureDocument(t),this.isStale(t)||(await this.discoverSnapshot(t),this.isStale(t))||(this.createUpdatesProducer(t),await this.startUpdatesStream(t,t.startOffset),this.isStale(t)))return;this.awareness&&this.startAwareness(t)}catch(i){!(i instanceof Error&&i.name===`AbortError`)&&!this.isStale(t)&&(this.emit(`error`,[i instanceof Error?i:new Error(String(i))]),this.disconnect())}}async disconnect(){const t=this._ctx;!t||this._state===`disconnected`||(this.transition(`disconnected`),this._ctx=null,this.synced=!1,this.awarenessHeartbeat&&(clearInterval(this.awarenessHeartbeat),this.awarenessHeartbeat=null),this.awareness&&this.broadcastAwarenessRemoval(),this.updatesStreamGeneration+=1,this.updatesSubscription&&(this.updatesSubscription(),this.updatesSubscription=null),await this.closeUpdatesProducer(t),t.controller.abort(),this.pendingAwareness=null)}destroy(){this.disconnect().catch(()=>{}),this.doc.off(`update`,this.handleDocumentUpdate),this.awareness&&this.awareness.off(`update`,this.handleAwarenessUpdate),super.destroy()}async flush(){this._ctx?.producer&&await this._ctx.producer.flush()}docUrl(){return`${this.baseUrl}/docs/${this.docId}`}awarenessUrl(t=`default`){return`${this.docUrl()}?awareness=${encodeURIComponent(t)}`}async ensureDocument(t){const i=this.docUrl(),r=await fetch(i,{method:`PUT`,headers:{...this.headers,"content-type":`application/octet-stream`},signal:t.controller.signal});if(r.status===201||r.status===200){await r.arrayBuffer();return}if(r.status===409){await r.arrayBuffer();return}const l=await r.text().catch(()=>``);throw new Error(`Failed to create document: ${r.status} ${l}`)}async discoverSnapshot(t){const i=`${this.docUrl()}?offset=snapshot`,r=await fetch(i,{method:`GET`,headers:this.headers,redirect:`manual`,signal:t.controller.signal});if(r.status===307){const l=r.headers.get(`location`);if(l){const u=new URL(l,i).searchParams.get(`offset`);if(u){u.endsWith(`_snapshot`)?await this.loadSnapshot(t,u):t.startOffset=u;return}}}t.startOffset=`-1`}async loadSnapshot(t,i){const r=`${this.docUrl()}?offset=${encodeURIComponent(i)}`;try{const l=await fetch(r,{method:`GET`,headers:this.headers,signal:t.controller.signal});if(!l.ok){if(l.status===404){await this.discoverSnapshot(t);return}throw new Error(`Failed to load snapshot: ${l.status}`)}const o=new Uint8Array(await l.arrayBuffer());o.length>0&&lv(this.doc,o,`server`);const u=l.headers.get(`stream-next-offset`);t.startOffset=u??`-1`}catch(l){if(this.isNotFoundError(l)){await this.discoverSnapshot(t);return}throw l}}createUpdatesProducer(t){const i=new Ys({url:this.docUrl(),headers:this.headers,contentType:`application/octet-stream`}),r=`${this.docId}-${this.doc.clientID}`;t.producer=new wb(i,r,{autoClaim:!0,signal:t.controller.signal,onError:l=>{l instanceof Error&&l.name===`AbortError`||(console.error(`[YjsProvider] Producer error:`,l),this.emit(`error`,[l]),this.isAuthError(l)||(this.disconnect(),this.connect()))}})}async closeUpdatesProducer(t){if(t.producer){try{await t.producer.close()}catch{}t.producer=null}}startUpdatesStream(t,i){if(t.controller.signal.aborted)return Promise.resolve();this.updatesStreamGeneration+=1;const r=this.updatesStreamGeneration;this.updatesSubscription?.(),this.updatesSubscription=null;let l=!1,o,u;const d=new Promise((p,g)=>{o=()=>{l||(l=!0,p())},u=y=>{l||(l=!0,g(y))}});return this.runUpdatesStream(t,i,r,o,u).catch(p=>{u(p instanceof Error?p:new Error(String(p)))}),d}async runUpdatesStream(t,i,r,l,o){let u=i,d=!0;const p=()=>{d&&(d=!1,this._state===`connecting`&&this.transition(`connected`),this.synced=!0,l())},g=()=>this.isStale(t)||this.updatesStreamGeneration!==r;for(;this.updatesStreamGeneration===r;){if(t.controller.signal.aborted){p();return}const y=new Ys({url:this.docUrl(),headers:this.headers,contentType:`application/octet-stream`});try{const m=await y.stream({offset:u,live:this.liveMode,signal:t.controller.signal});this.updatesSubscription?.(),this.updatesSubscription=m.subscribeBytes(async v=>{g()||(u=v.offset,v.data.length>0&&this.applyUpdates(v.data),d&&v.upToDate?p():v.data.length>0&&(this.synced=!0))}),await m.closed,p();continue}catch(m){if(g()){p();return}if(this.isNotFoundError(m)){if(d){o(m instanceof Error?m:new Error(String(m)));return}this.emit(`error`,[m instanceof Error?m:new Error(String(m))]),this.disconnect();return}if(d){o(m instanceof Error?m:new Error(String(m)));return}await new Promise(v=>setTimeout(v,1e3))}finally{this.updatesSubscription&&(this.updatesSubscription(),this.updatesSubscription=null)}}}static frameUpdate(t){const i=qw();return Vw(i,t),Kw(i)}applyUpdates(t){if(t.length===0)return;const i=Qd(t);for(;vv(i);){const r=Xd(i);lv(this.doc,r,`server`)}}applyAwarenessUpdates(t){if(!(t.length===0||!this.awareness))try{const i=Qd(t);for(;vv(i);){const r=Xd(i);try{L2(this.awareness,r,`server`)}catch{}}}catch{}}handleDocumentUpdate=(t,i)=>{if(i===`server`)return;const r=this._ctx?.producer;!r||!this.connected||(this.synced=!1,r.append(Sc.frameUpdate(t)))};startAwareness(t){this.awareness&&(t.controller.signal.aborted||(this.broadcastAwareness(),this.awarenessHeartbeat=setInterval(()=>{this.broadcastAwareness()},H2),this.subscribeAwareness(t)))}handleAwarenessUpdate=(t,i)=>{if(!this.awareness||i===`server`||i===this)return;const{added:r,updated:l,removed:o}=t;r.concat(l).concat(o).includes(this.awareness.clientID)&&(this.pendingAwareness=t,this.sendAwareness())};broadcastAwareness(){this.awareness&&(this.pendingAwareness={added:[this.awareness.clientID],updated:[],removed:[]},this.sendAwareness())}broadcastAwarenessRemoval(){if(this.awareness)try{this.awareness.setLocalState(null);const t=Cv(this.awareness,[this.awareness.clientID]);new Ys({url:this.awarenessUrl(),headers:this.headers,contentType:`application/octet-stream`}).append(Sc.frameUpdate(t),{contentType:`application/octet-stream`}).catch(()=>{})}catch{}}async sendAwareness(){if(!(!this.awareness||!this.connected&&!this.connecting||this.sendingAwareness)){this.sendingAwareness=!0;try{for(;this.pendingAwareness;){const t=this.pendingAwareness;this.pendingAwareness=null;const{added:i,updated:r,removed:l}=t,o=i.concat(r).concat(l),u=Cv(this.awareness,o);await new Ys({url:this.awarenessUrl(),headers:this.headers,contentType:`application/octet-stream`}).append(Sc.frameUpdate(u),{contentType:`application/octet-stream`})}}catch(t){console.error(`[YjsProvider] Failed to send awareness:`,t)}finally{this.sendingAwareness=!1}}}async subscribeAwareness(t){if(!this.awareness)return;const i=t.controller.signal;if(i.aborted)return;const r=new Ys({url:this.awarenessUrl(),headers:this.headers,contentType:`application/octet-stream`});try{const l=await r.stream({offset:`now`,live:`sse`,signal:i});l.closed.catch(()=>{}),l.subscribeBytes(async o=>{i.aborted||o.data.length>0&&this.applyAwarenessUpdates(o.data)}),await l.closed,this.connected&&!i.aborted&&(await new Promise(o=>setTimeout(o,250)),this.subscribeAwareness(t))}catch(l){if(i.aborted||!this.connected&&!this.connecting)return;if(this.isNotFoundError(l)){console.error(`[YjsProvider] Awareness stream not found`);return}console.error(`[YjsProvider] Awareness stream error:`,l),await new Promise(o=>setTimeout(o,1e3)),this.connected&&this.subscribeAwareness(t)}}isNotFoundError(t){return t instanceof Wt&&t.code===`NOT_FOUND`||t instanceof Js&&t.status===404}isAuthError(t){return t instanceof Wt&&(t.code===`UNAUTHORIZED`||t.code===`FORBIDDEN`)||t instanceof Js&&(t.status===401||t.status===403)}};const K2=64,V2=64,xv=200,$2=1500,vc=.3,_v=12e4,G2=`#d0bcff`,ic=[`#FF0055`,`#00FF88`,`#FFEE00`,`#00CCFF`,`#FF6600`,`#00FFCC`,`#FF2299`,`#33FF00`,`#FF00AA`,`#00AAFF`,`#FFAA00`,`#CC00FF`,`#00FF55`,`#FF4400`,`#0066FF`];function Y2(n){const t=n.match(/__(\d+)x(\d+)(?:_(\d+)ms)?$/);return t?{cols:parseInt(t[1]),rows:parseInt(t[2])}:{cols:K2,rows:V2}}function ll(n){return n.getMap(`territoryCell`)}function jn(n){return n.getMap(`players`)}function cu(n){return n.getMap(`gameState`)}function Yw(n,t){const i=jn(n),r=new Map;return i.forEach((l,o)=>{o!==t&&r.set(o,l)}),r}function fd(n){const t=ll(n),i=new Map;return t.forEach((r,l)=>{i.set(l,r)}),i}function F2(n,t){let i=0;return n.forEach(r=>{r.owner===t&&i++}),i}function Q2(n,t,i,r){const l=new Set;t.forEach((p,g)=>{p.owner===n&&l.add(g)});const o=new Set,u=[];for(let p=0;p0;){const{x:p,y:g}=u.pop();for(const[y,m]of[[0,-1],[0,1],[-1,0],[1,0]]){const v=p+y,w=g+m;if(v<0||v>=i||w<0||w>=r)continue;const b=`${v},${w}`;l.has(b)||o.has(b)||(o.add(b),u.push({x:v,y:w}))}}const d=[];for(let p=0;pA.x===m&&A.y===v);if(b){const[A,M]=b,G=p+$2,q=jn(n);return q.set(A,{...M,stunnedUntil:G}),q.set(t,{x:r.x,y:r.y,name:i,stunnedUntil:G}),{moved:!1,stunned:!0,x:r.x,y:r.y,stunnedUntil:G}}jn(n).set(t,{x:m,y:v,name:i});const _=ll(n),j=Date.now();n.transact(()=>{_.set(`${m},${v}`,{owner:t,claimedAt:j})});const O=Q2(t,_,o,u);return O.length>0&&n.transact(()=>{for(const A of O)_.set(`${A.x},${A.y}`,{owner:t,claimedAt:j})}),{moved:!0,stunned:!1,x:m,y:v,stunnedUntil:0}}function Tv(n){const t=cu(n);t.has(`gameStartedAt`)||n.transact(()=>{t.has(`gameStartedAt`)||t.set(`gameStartedAt`,Date.now())})}function Z2(n){const i=cu(n).get(`gameStartedAt`);return i!==void 0?i:null}function hd(n){const i=cu(n).get(`gameEndedAt`);return i!==void 0?i:null}function Av(n){const t=cu(n);(!t.has(`gameEndedAt`)||t.get(`gameEndedAt`)===null)&&n.transact(()=>{t.set(`gameEndedAt`,Date.now())})}function Vp(n){const t=new Map;return n.forEach(i=>{t.set(i.owner,(t.get(i.owner)||0)+1)}),t}function Ov(n,t,i){const r=Vp(n),l=vc*t;for(const[o,u]of r)if(u>=l){const d=i.get(o);if(d)return{name:d.name,pct:Math.round(u/t*100)}}return null}function Rv(n,t,i){const r=Vp(n);let l=0,o=``;if(r.forEach((d,p)=>{d>l&&(l=d,o=p)}),!o||l===0)return null;const u=i.get(o);return u?{name:u.name,pct:Math.round(l/t*100)}:null}const Fw=J.createContext(null);function W2(){const n=J.useContext(Fw);if(!n)throw new Error(`useGameRoom must be used within GameRoom`);return n}function P2(n,t){return{streamOptions:{url:n,headers:t,contentType:`application/json`},state:GS,actions:({db:i,stream:r})=>({submitScore:{onMutate:l=>{i.collections.scores.insert(l)},mutationFn:async l=>{const o=crypto.randomUUID();await r.append(JSON.stringify(GS.scores.insert({value:l,headers:{txid:o}}))),await i.utils.awaitTxId(o)}}})}}function tk(n,t){return _b(P2(n,t))}const ek=J.createContext(null);function nk({roomId:n,children:t}){const{dsEndpoint:i,dsHeaders:r}=Zd(),{db:l,error:o}=tk(`${i}/__snake_scores_${encodeURIComponent(n)}`,r);return o&&console.warn(`[Scores] Error loading scores:`,o.message),F.jsx(ek.Provider,{value:l?{scoresDB:l}:null,children:t})}const sk=1,br=8,Dv=14,Vt={bg:`#1b1b1f`,grid:`#202127`,gridLine:`#2e2e32`,border:`#2e2e32`,text:`rgba(235,235,245,0.68)`,accent:`#d0bcff`,dim:`rgba(235,235,245,0.38)`},wr={ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1},ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},w:{dx:0,dy:-1},s:{dx:0,dy:1},a:{dx:-1,dy:0},d:{dx:1,dy:0}};function ik(n,t){return n>256||t>256?2:n>64||t>64?4:14}function rk({onLeave:n}){const{doc:t,awareness:i,roomId:r,playerId:l,playerName:o,playerColor:u}=W2(),{cols:d,rows:p}=J.useMemo(()=>Y2(r),[r]),g=d*p,y=J.useMemo(()=>ik(d,p),[d,p]),m=d<=100&&p<=100,[v,w]=J.useState(new Map),[b,E]=J.useState(new Map),[_,j]=J.useState({x:0,y:0}),[O,A]=J.useState(1),[M,G]=J.useState(!1),[q,K]=J.useState(!1),[W,et]=J.useState(null),[X,at]=J.useState(_v/1e3),nt=r.replace(/__\d+x\d+(?:_\d+ms)?$/,``),bt=J.useRef(void 0),Lt=J.useRef(null),dt=J.useRef({x:0,y:0,stunnedUntil:0}),k=J.useMemo(()=>F2(v,l)*sk,[v,l]),I=J.useMemo(()=>Math.round(k/g*100),[k,g]),Z=J.useMemo(()=>Vp(v),[v]),it=J.useRef(null),[ft,T]=J.useState(!1),B=J.useMemo(()=>{let tt=0,P=``;if(Z.forEach((ht,Qt)=>{ht>tt&&(tt=ht,P=Qt)}),!P||tt===0)return null;const gt=Math.round(tt/g*100);if(P===l)return{name:o,pct:gt};const pt=b.get(P);return pt?{name:pt.name,pct:gt}:null},[Z,g,l,o,b]);J.useEffect(()=>{if(B){if(it.current!==null&&it.current!==B.name){T(!0);const tt=setTimeout(()=>T(!1),900);return()=>clearTimeout(tt)}it.current=B.name}},[B]),J.useEffect(()=>{const tt=Math.floor(Math.random()*d),P=Math.floor(Math.random()*p);dt.current={x:tt,y:P,stunnedUntil:0},j({x:tt,y:P});const gt=jn(t);gt.set(l,{x:tt,y:P,name:o});const pt=ll(t);return t.transact(()=>{pt.set(`${tt},${P}`,{owner:l,claimedAt:Date.now()})}),Tv(t),()=>{gt.delete(l)}},[t,l,o,u,d,p]),J.useEffect(()=>{const tt=ll(t),P=()=>{const gt=fd(t);if(w(gt),hd(t)!==null)return;const pt=Ov(gt,g,jn(t));pt&&(et(pt),Av(t))};return tt.observe(P),P(),()=>tt.unobserve(P)},[t,g]),J.useEffect(()=>{const tt=()=>{const gt=Z2(t);if(!gt)return;const pt=Date.now()-gt,ht=Math.max(0,_v-pt);at(Math.ceil(ht/1e3));const Qt=hd(t)!==null;if(ht<=0&&!Qt){const De=fd(t),Ge=Rv(De,g,jn(t));et(Ge||{name:`Nobody`,pct:0}),Av(t)}else Qt&&et(De=>{if(De)return De;const Ge=fd(t),Ye=Ov(Ge,g,jn(t));return Ye||(Rv(Ge,g,jn(t))??{name:`Nobody`,pct:0})})},P=setInterval(tt,1e3);return tt(),()=>clearInterval(P)},[t,g]),J.useEffect(()=>{const tt=jn(t),P=()=>{E(Yw(t,l))};return tt.observe(P),P(),()=>tt.unobserve(P)},[t,l]),J.useEffect(()=>{const tt=()=>{const P=new Set,gt=new Set([o]);i.getStates().forEach((ht,Qt)=>{if(Qt!==i.clientID){ht.playerId&&P.add(ht.playerId);const De=ht.user?.name;De&>.add(De)}}),A(ht=>{const Qt=gt.size;return ht===Qt?ht:Qt});const pt=jn(t);pt.forEach((ht,Qt)=>{Qt!==l&&!P.has(Qt)&&pt.delete(Qt)})};return i.on(`change`,tt),tt(),()=>i.off(`change`,tt)},[i,t,l,o]),J.useEffect(()=>{const tt=new Set,P=pt=>{if(pt.key in wr){pt.preventDefault();const ht=!Lt.current;tt.add(pt.key),Lt.current=wr[pt.key],ht&&$e.current?.(wr[pt.key])}},gt=pt=>{if(tt.delete(pt.key),pt.key in wr){let ht=!1;for(const Qt of tt)if(Qt in wr){Lt.current=wr[Qt],ht=!0;break}ht||(Lt.current=null)}};return window.addEventListener(`keydown`,P),window.addEventListener(`keyup`,gt),()=>{window.removeEventListener(`keydown`,P),window.removeEventListener(`keyup`,gt)}},[]);const Y=J.useRef(null),Q=J.useRef(null),ot=J.useRef(0),st=10,mt=J.useCallback((tt,P)=>{const gt=Date.now();if(gt-ot.currentMath.abs(Wr)?$e.current?.({dx:zi>0?1:-1,dy:0}):$e.current?.({dx:0,dy:Wr>0?1:-1}),ot.current=gt)},[y]),Ut=J.useCallback(tt=>{tt.preventDefault();const P=tt.touches[0];Q.current={x:P.clientX,y:P.clientY},mt(P.clientX,P.clientY)},[mt]),wt=J.useCallback(tt=>{if(tt.preventDefault(),!Q.current)return;const P=tt.touches[0],gt=P.clientX-Q.current.x,pt=P.clientY-Q.current.y;Math.abs(gt){Q.current=null},[]),$e=J.useRef(void 0),Ps=J.useCallback(tt=>{const P=Y.current;if(!P)return;const gt=P.createSVGPoint();gt.x=tt.clientX,gt.y=tt.clientY;const pt=P.getScreenCTM();if(!pt)return;const ht=gt.matrixTransform(pt.inverse()),Qt=ht.x/y-.5,De=ht.y/y-.5,Ge=dt.current,Ye=Qt-Ge.x,Gn=De-Ge.y;Ye===0&&Gn===0||(Math.abs(Ye)>Math.abs(Gn)?$e.current?.({dx:Ye>0?1:-1,dy:0}):$e.current?.({dx:0,dy:Gn>0?1:-1}))},[y]),ki=J.useCallback(()=>{n()},[n]);J.useEffect(()=>{const tt=gt=>{if(hd(t)!==null)return;const pt=dt.current,ht=J2(t,l,o,{x:pt.x,y:pt.y},gt,d,p,pt.stunnedUntil);pt.stunnedUntil=ht.stunnedUntil,ht.moved&&(pt.x=ht.x,pt.y=ht.y,j({x:ht.x,y:ht.y}),i.setLocalState({...i.getLocalState(),x:ht.x,y:ht.y}))};$e.current=tt;const P=setInterval(()=>{const gt=Lt.current;gt&&tt(gt)},xv);return()=>clearInterval(P)},[t,l,o,u,d,p,i]);const Te=d*y,ti=p*y,Jr=J.useCallback(()=>{navigator.clipboard.writeText(nt).catch(()=>{}),G(!0),clearTimeout(bt.current),bt.current=setTimeout(()=>G(!1),1200)},[nt]);J.useEffect(()=>()=>clearTimeout(bt.current),[]);const uu=J.useMemo(()=>m?F.jsxs(F.Fragment,{children:[Array.from({length:d},(tt,P)=>F.jsx(`line`,{x1:P*y,y1:0,x2:P*y,y2:ti,stroke:Vt.gridLine,strokeWidth:.5},`v${P}`)),Array.from({length:p},(tt,P)=>F.jsx(`line`,{x1:0,y1:P*y,x2:Te,y2:P*y,stroke:Vt.gridLine,strokeWidth:.5},`h${P}`))]}):null,[d,p,Te,ti,y,m]),Ui=J.useMemo(()=>{const tt=new Map;tt.set(l,u);const P=[...b.keys()].sort();for(let gt=0;gt{const P=Math.floor(tt/60),gt=tt%60;return`${P}:${gt.toString().padStart(2,`0`)}`};return F.jsxs(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,fontFamily:`'Press Start 2P', monospace`,background:Vt.bg,color:Vt.text,minHeight:`100dvh`,maxHeight:`100dvh`,padding:8,boxSizing:`border-box`,overflow:`hidden`,touchAction:`none`},children:[F.jsx(`style`,{children:`
+ @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
+ @keyframes blink { 0%,100% { opacity:1 } 50% { opacity:0.3 } }
+ .live-dot { animation: blink 1.5s ease-in-out infinite; }
+ @keyframes stun-pulse { 0%,100% { opacity:1 } 50% { opacity:0.2 } }
+ .stunned { animation: stun-pulse 0.3s ease-in-out infinite; }
+ @keyframes leader-blink { 0%,100% { opacity:1 } 50% { opacity:0 } }
+ .leader-blink { animation: leader-blink 0.3s ease-in-out 3; }
+ `}),F.jsxs(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,width:`100%`,maxWidth:Te,marginBottom:8,fontSize:br},children:[F.jsx(`button`,{onClick:ki,style:{background:`none`,border:`none`,color:Vt.accent,fontFamily:`inherit`,fontSize:br,padding:`4px 0`,cursor:`pointer`},children:`EXIT`}),F.jsxs(`div`,{style:{display:`flex`,gap:6,cursor:`pointer`},onClick:Jr,title:`Click to copy room name`,children:[F.jsx(`span`,{style:{color:Vt.accent},children:o}),F.jsx(`span`,{style:{color:Vt.dim},children:`@`}),F.jsx(`span`,{style:{color:M?Vt.accent:Vt.text,textDecoration:`underline`,textUnderlineOffset:3},children:M?`COPIED`:nt})]}),F.jsx(`span`,{style:{color:X<=30?`#FF3D71`:Vt.accent,fontVariantNumeric:`tabular-nums`},children:Zr(X)}),F.jsxs(`div`,{style:{color:Vt.accent,position:`relative`,cursor:`pointer`},onMouseEnter:()=>K(!0),onMouseLeave:()=>K(!1),onClick:()=>K(tt=>!tt),children:[O,` PLAYERS`,q&&F.jsx(`div`,{style:{position:`absolute`,top:`100%`,right:0,marginTop:6,background:Vt.bg,border:`1px solid ${Vt.border}`,padding:10,zIndex:5,minWidth:120},children:[{id:l,name:o},...Array.from(b.entries()).map(([tt,P])=>({id:tt,name:P.name}))].map(tt=>{const P=Ui.get(tt.id)??ic[0],gt=Z.get(tt.id)||0,pt=Math.round(gt/g*100);return F.jsxs(`div`,{style:{display:`flex`,justifyContent:`space-between`,gap:8,padding:`3px 0`},children:[F.jsxs(`span`,{style:{display:`flex`,alignItems:`center`,gap:4},children:[F.jsx(`span`,{style:{width:6,height:6,borderRadius:`50%`,background:P,display:`inline-block`}}),tt.name]}),F.jsxs(`span`,{style:{color:Vt.accent},children:[pt,`%`]})]},tt.id)})})]})]}),F.jsxs(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`flex-end`,width:`100%`,maxWidth:Te,marginBottom:8,fontSize:br},children:[F.jsxs(`div`,{children:[F.jsxs(`span`,{style:{fontSize:Dv,color:Vt.accent},children:[I,`%`]}),` `,F.jsx(`span`,{style:{color:Vt.dim},children:`TERRITORY`})]}),F.jsxs(`div`,{style:{textAlign:`right`},children:[F.jsxs(`div`,{style:{marginBottom:B?4:0,color:B&&B.pct>=Math.round(vc*100)-5?`#FF3D71`:Vt.dim},children:[`WIN AT `,Math.round(vc*100),`%`]}),B&&F.jsxs(`div`,{children:[F.jsx(`span`,{className:ft?`leader-blink`:void 0,style:{color:Vt.dim},children:B.name}),` `,F.jsxs(`span`,{style:{fontSize:Dv,color:Vt.accent},children:[B.pct,`%`]})]})]})]}),F.jsxs(`svg`,{ref:Y,viewBox:`0 0 ${Te} ${ti}`,onTouchStart:Ut,onTouchMove:wt,onTouchEnd:an,onClick:Ps,style:{width:`min(100%, calc(100dvh - 140px))`,maxWidth:Te,height:`auto`,aspectRatio:`${d} / ${p}`,background:Vt.grid,border:`1px solid ${Vt.border}`,flexShrink:0,userSelect:`none`,WebkitUserSelect:`none`},children:[uu,Array.from(v.entries()).map(([tt,P])=>{const[gt,pt]=tt.split(`,`).map(Number),ht=Ui.get(P.owner)||Vt.accent;return F.jsx(`rect`,{x:gt*y,y:pt*y,width:y,height:y,fill:ht,opacity:.5},tt)}),Array.from(b.entries()).map(([tt,P])=>{const gt=P.stunnedUntil!=null&&Date.now(){const tt=dt.current.stunnedUntil>0&&Date.now(){const tt=ll(t),P=t.getMap(`gameState`);t.transact(()=>{Array.from(tt.keys()).forEach(pt=>tt.delete(pt)),P.delete(`gameStartedAt`),P.delete(`gameEndedAt`)}),et(null),Tv(t)},style:{fontFamily:`inherit`,fontSize:br,padding:`10px 24px`,background:Vt.accent,color:`#000`,border:`none`,cursor:`pointer`,letterSpacing:2},children:`REMATCH`}),F.jsx(`button`,{onClick:ki,style:{fontFamily:`inherit`,fontSize:br,padding:`10px 24px`,background:`transparent`,color:Vt.accent,border:`1px solid ${Vt.accent}`,cursor:`pointer`,letterSpacing:2},children:`EXIT`})]})]})]})}function ak({roomId:n,yjsBaseUrl:t,yjsHeaders:i,playerName:r,onLeave:l}){const{registryDB:o}=Ab(),[{playerId:u,doc:d,awareness:p}]=J.useState(()=>{const O=`player-${Math.random().toString(36).slice(2,10)}`,A=new Qr,M=new j2(A);return M.setLocalState({user:{name:r},playerId:O,type:`human`}),{playerId:O,doc:A,awareness:M}}),g=G2,[y,m]=J.useState(!0),[v,w]=J.useState(!1),[b,E]=J.useState(null),_=J.useRef(null);J.useEffect(()=>{const O=new q2({doc:d,baseUrl:t,docId:n,awareness:p,headers:i,connect:!1});return O.on(`synced`,A=>{w(A),A&&m(!1)}),O.on(`status`,A=>{A===`connected`&&m(!1)}),O.on(`error`,A=>{E(A),m(!1)}),p.getLocalState()===null&&p.setLocalState({user:{name:r},playerId:u,type:`human`}),_.current=O,O.connect(),()=>{O.destroy(),_.current=null}},[n,d,p,t,i,r,u]),J.useEffect(()=>{const A=setInterval(()=>{const M=new Set([u]);if(p.getStates().forEach(K=>{K.playerId&&M.add(K.playerId)}),[...M].sort()[0]!==u)return;const q=o.collections.rooms.toArray.find(K=>K.roomId===n);if(q)try{o.actions.addRoom({...q,expiresAt:Date.now()+bp*1e3})}catch{}},QO);return()=>clearInterval(A)},[p,o,n,u]),J.useEffect(()=>()=>{d.destroy()},[d]);const j=J.useMemo(()=>({doc:d,awareness:p,roomId:n,playerId:u,playerName:r,playerColor:g,isSynced:v,isLoading:y}),[d,p,n,u,r,g,v,y]);return b?F.jsxs(`div`,{style:dd.center,children:[F.jsxs(`div`,{style:{color:`#FF3D71`,fontSize:8},children:[`Connection error: `,b.message]}),F.jsx(`button`,{onClick:l,style:dd.btn,children:`BACK`})]}):y?F.jsxs(`div`,{style:dd.center,children:[F.jsx(`style`,{children:`@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');`}),F.jsx(`div`,{style:{color:`#d0bcff`,fontSize:8},children:`CONNECTING...`})]}):F.jsx(Fw.Provider,{value:j,children:F.jsx(nk,{roomId:n,children:F.jsx(rk,{onLeave:l})})})}const dd={center:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100vh`,gap:16,fontFamily:`'Press Start 2P', monospace`,background:`#1b1b1f`},btn:{fontFamily:`inherit`,fontSize:8,padding:`8px 24px`,background:`#d0bcff`,color:`#000`,border:`none`,cursor:`pointer`}},Mv=[`Swift`,`Bold`,`Sly`,`Keen`,`Cool`,`Neon`,`Rad`,`Zen`],kv=[`Fox`,`Wolf`,`Hawk`,`Bear`,`Lynx`,`Crow`,`Stag`,`Hare`];function lk(){const n=Mv[Math.floor(Math.random()*Mv.length)],t=kv[Math.floor(Math.random()*kv.length)];return`${n} ${t}`}function ok(){return localStorage.getItem(`territory-player-name`)||lk()}function ck(){const[n,t]=J.useState(()=>{const i=window.location.hash.match(/^#room\/(.+)$/);return i?decodeURIComponent(i[1]):null});return J.useEffect(()=>{const i=()=>{const r=window.location.hash.match(/^#room\/(.+)$/);t(r?decodeURIComponent(r[1]):null)};return window.addEventListener(`hashchange`,i),()=>window.removeEventListener(`hashchange`,i)},[]),n}function uk(){const n=ck(),{yjsEndpoint:t,yjsHeaders:i}=Zd(),[r,l]=J.useState(ok),o=u=>{l(u),localStorage.setItem(`territory-player-name`,u)};return n?F.jsx(ak,{roomId:n,yjsBaseUrl:t,yjsHeaders:i,playerName:r,onLeave:()=>{window.location.hash=``}}):F.jsx(sR,{playerName:r,onPlayerNameChange:o,onJoinRoom:u=>{window.location.hash=`room/${encodeURIComponent(u)}`}})}function fk(){return F.jsx(CC,{children:F.jsx(tR,{children:F.jsx(uk,{})})})}wC.createRoot(document.getElementById(`root`)).render(F.jsx(fk,{}));
diff --git a/website/public/demos/territory-wars/index.html b/website/public/demos/territory-wars/index.html
new file mode 100644
index 0000000000..9402e5c83c
--- /dev/null
+++ b/website/public/demos/territory-wars/index.html
@@ -0,0 +1,24 @@
+
+
+
+
+
+ Territory Wars - Multiplayer with Durable Streams
+
+
+
+
+
+
+
diff --git a/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.png b/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.png
new file mode 100644
index 0000000000..3bdcaee285
Binary files /dev/null and b/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.png differ
diff --git a/website/public/img/demos/territory-wars-screenshot.png b/website/public/img/demos/territory-wars-screenshot.png
new file mode 100644
index 0000000000..6d68ed0182
Binary files /dev/null and b/website/public/img/demos/territory-wars-screenshot.png differ
diff --git a/website/src/components/SnapshotSyncDiagram.vue b/website/src/components/SnapshotSyncDiagram.vue
new file mode 100644
index 0000000000..03c7f5c581
--- /dev/null
+++ b/website/src/components/SnapshotSyncDiagram.vue
@@ -0,0 +1,367 @@
+
+
+
+
+
+ Document Stream (append-only log)
+
+
+
0
+
1
+
2
+
...
+
4780
+
4781
+
4782
+
4783
+
4784
+
...
+
+
+
+
+
+
+
+
+
+
Snapshot
+
@ offset 4782
+
immutable / cacheable
+
+
+
+
+
+
Client sync flow
+
+
+
+
1
+
+
Client requests snapshot
+
GET ?offset=snapshot
+
+
▶
+
+
+
+
+
+
2
+
+
Redirect resolves to snapshot
+
→ Snapshot @ offset 4782
+
+
▶
+
+
+
+
+
+
3
+
+
Client subscribes for live updates
+
GET ?offset=4783&live=sse
+
+
▶
+
+
SSE stream → 4783, 4784, ...
+
+
+
+
+
+
+