UNPKG

@electric-sql/client

Version:

Postgres everywhere - your data, in sync, wherever you need it.

10 lines 58.8 kB
var qr=Object.defineProperty,$r=Object.defineProperties;var Vr=Object.getOwnPropertyDescriptors;var Pt=Object.getOwnPropertySymbols;var zs=Object.prototype.hasOwnProperty,Gs=Object.prototype.propertyIsEnumerable;var Js=r=>{throw TypeError(r)};var Qs=(r,t,e)=>t in r?qr(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,R=(r,t)=>{for(var e in t||(t={}))zs.call(t,e)&&Qs(r,e,t[e]);if(Pt)for(var e of Pt(t))Gs.call(t,e)&&Qs(r,e,t[e]);return r},_=(r,t)=>$r(r,Vr(t));var Je=(r,t)=>{var e={};for(var s in r)zs.call(r,s)&&t.indexOf(s)<0&&(e[s]=r[s]);if(r!=null&&Pt)for(var s of Pt(r))t.indexOf(s)<0&&Gs.call(r,s)&&(e[s]=r[s]);return e};var hs=(r,t,e)=>t.has(r)||Js("Cannot "+e);var a=(r,t,e)=>(hs(r,t,"read from private field"),e?e.call(r):t.get(r)),m=(r,t,e)=>t.has(r)?Js("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),l=(r,t,e,s)=>(hs(r,t,"write to private field"),s?s.call(r,e):t.set(r,e),e),p=(r,t,e)=>(hs(r,t,"access private method"),e);var z=(r,t,e,s)=>({set _(n){l(r,t,n,e)},get _(){return a(r,t,s)}});var w=class r extends Error{constructor(e,s,n,i,o,c){super(c||`HTTP Error ${e} at ${o}: ${s!=null?s:JSON.stringify(n)}`);this.url=o;this.name="FetchError",this.status=e,this.text=s,this.json=n,this.headers=i}static async fromResponse(e,s){let n=e.status,i=Object.fromEntries([...e.headers.entries()]),o,c,h=e.headers.get("content-type");return e.bodyUsed||(h&&h.includes("application/json")?c=await e.json():o=await e.text()),new r(n,o,c,i,s)}},O=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}},Ct=class extends Error{constructor(t){super(t),this.name="InvalidShapeOptionsError"}},_t=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Mt=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},kt=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Ut=class extends Error{constructor(t){super(`Cannot use reserved Electric parameter names in custom params: ${t.join(", ")}`),this.name="ReservedParamError"}},Lt=class extends Error{constructor(t){super(`Column "${t!=null?t:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var G=class extends Error{constructor(t,e){let s=`The response for the shape request to ${t} didn't include the following required headers: `;e.forEach(n=>{s+=`- ${n} `}),s+=` This is often due to a proxy not setting CORS correctly so that all Electric headers can be read by the client.`,s+=` For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}},he=class extends Error{constructor(t){super(t),this.name="StaleCacheError"}};var Ot=r=>Number(r),jr=r=>r==="true"||r==="t",Wr=r=>BigInt(r),Xs=r=>JSON.parse(r),Yr=r=>r,Kr={int2:Ot,int4:Ot,int8:Wr,bool:jr,float4:Ot,float8:Ot,json:Xs,jsonb:Xs};function Qr(r,t){let e=0,s=null,n="",i=!1,o=0,c;function h(d,g,b){let S=d.slice(g,b);return S=S==="NULL"?null:S,t?t(S):S}function u(d){let g=[];for(;e<d.length;e++){if(s=d[e],i)s==="\\"?n+=d[++e]:s==='"'?(g.push(t?t(n):n),n="",i=d[e+1]==='"',o=e+2):n+=s;else if(s==='"')i=!0;else if(s==="{")o=++e,g.push(u(d));else if(s==="}"){i=!1,o<e&&g.push(h(d,o,e)),o=e+1;break}else s===","&&c!=="}"&&c!=='"'&&(g.push(h(d,o,e)),o=e+1);c=s}return o<e&&g.push(g.push(h(d,o,e+1))),g}return u(r)[0]}var Dt=class{constructor(t,e){this.parser=R(R({},Kr),t),this.transformer=e}parse(t,e){return JSON.parse(t,(s,n)=>(s==="value"||s==="old_value")&&typeof n=="object"&&n!==null?this.transformMessageValue(n,e):n)}parseSnapshotData(t,e){return t.map(s=>{let n=s;return n.value&&typeof n.value=="object"&&n.value!==null&&(n.value=this.transformMessageValue(n.value,e)),n.old_value&&typeof n.old_value=="object"&&n.old_value!==null&&(n.old_value=this.transformMessageValue(n.old_value,e)),n})}transformMessageValue(t,e){let s=t;return Object.keys(s).forEach(n=>{s[n]=this.parseRow(n,s[n],e)}),this.transformer?this.transformer(s):s}parseRow(t,e,s){var g;let n=s[t];if(!n)return e;let d=n,{type:i,dims:o}=d,c=Je(d,["type","dims"]),h=(g=this.parser[i])!=null?g:Yr,u=Zs(h,n,t);return o&&o>0?Zs((S,v)=>Qr(S,u),n,t)(e):u(e,c)}};function Zs(r,t,e){var n;let s=!((n=t.not_null)!=null&&n);return i=>{if(i===null){if(!s)throw new Lt(e!=null?e:"unknown");return null}return r(i,t)}}function Xe(r){return`"${r.replace(/"/g,'""')}"`}function us(r){var c,h,u,d;let t=(h=(c=r.match(/^_+/))==null?void 0:c[0])!=null?h:"",e=r.slice(t.length),s=(d=(u=e.match(/_+$/))==null?void 0:u[0])!=null?d:"",o=(s?e.slice(0,e.length-s.length):e).toLowerCase().replace(/_+([a-z])/g,(g,b)=>"_".repeat(g.length-2)+b.toUpperCase());return t+o+s}function er(r){return r.replace(/([a-z_])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function tr(r){let t={};for(let[e,s]of Object.entries(r))t[s]=e;return{decode:e=>{var s;return(s=r[e])!=null?s:e},encode:e=>{var s;return(s=t[e])!=null?s:e}}}function ke(r,t){if(!r||!t)return r!=null?r:"";let e=new Set(["SELECT","FROM","WHERE","AND","OR","NOT","IN","IS","NULL","NULLS","FIRST","LAST","TRUE","FALSE","LIKE","ILIKE","BETWEEN","ASC","DESC","LIMIT","OFFSET","ORDER","BY","GROUP","HAVING","DISTINCT","AS","ON","JOIN","LEFT","RIGHT","INNER","OUTER","CROSS","CASE","WHEN","THEN","ELSE","END","CAST","LOWER","UPPER","COALESCE","NULLIF"]),s=[],n=0;for(;n<r.length;){let c=r[n];if(c==="'"||c==='"'){let h=n,u=c;for(n++;n<r.length;)if(r[n]===u)if(r[n+1]===u)n+=2;else{n++;break}else n++;s.push({start:h,end:n})}else n++}let i=c=>s.some(h=>c>=h.start&&c<h.end),o=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(o,(c,h,u)=>i(u)||e.has(c.toUpperCase())||c.startsWith("$")?c:t(c))}function zr(r){if(r){let t={};for(let e of Object.keys(r))t[e]=us(e);return tr(t)}return{decode:t=>us(t),encode:t=>er(t)}}function Ze(r){return r!=null&&"key"in r}function Bt(r){return r!=null&&"headers"in r&&"control"in r.headers}function Ht(r){return Bt(r)&&r.headers.control==="up-to-date"}function sr(r){if(r.headers.control!="up-to-date")return;let t=r.headers.global_last_seen_lsn;return t?`${t}_0`:void 0}function Gr(r,t){return typeof t=="bigint"?t.toString():t}function It(r){return JSON.stringify(r,Gr)}function rr(r){return JSON.stringify(ds(r))}function ds(r){if(typeof r=="bigint")return r.toString();if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(ds);let t={};for(let e of Object.keys(r).sort())t[e]=ds(r[e]);return t}function fs(r,t){let e=BigInt(r),s=BigInt(t.xmin),n=BigInt(t.xmax),i=t.xip_list.map(BigInt);return e<s||e<n&&!i.includes(e)}var Ft="electric-cursor",J="electric-handle",Ue="electric-offset",et="electric-schema",nr="electric-up-to-date",ps="columns",tt="cursor",st="expired_handle",ue="handle",F="live",de="offset",ar="table",ir="where",or="replica",cr="params",ms="experimental_live_sse",gs="live_sse",ys="force-disconnect-and-refresh",lr="pause-stream",Ss="system-wake",bs="live-request-timeout",Es="log",Le="subset__where",rt="subset__limit",nt="subset__offset",Oe="subset__order_by",at="subset__params",Rs="subset__where_expr",ws="subset__order_by_expr",fe="cache-buster",vs=[F,gs,ms,ue,de,tt,st,Es,Le,rt,nt,Oe,at,Rs,ws,fe];var Jr=[429],qt={initialDelay:1e3,maxDelay:32e3,multiplier:2,maxRetries:1/0};function Xr(r){if(!r)return 0;let t=Number(r);if(Number.isFinite(t)&&t>0)return t*1e3;let e=Date.parse(r);if(!isNaN(e)){let s=e-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}async function Zr(r,t){if(!(r<=0)){if(t!=null&&t.aborted)throw new O;await new Promise((e,s)=>{let n=!1,i=h=>{n||(n=!0,clearTimeout(c),t==null||t.removeEventListener("abort",o),h?s(h):e())},o=()=>i(new O),c=setTimeout(()=>i(),r);t==null||t.addEventListener("abort",o,{once:!0}),t!=null&&t.aborted&&o()})}}function hr(r,t=qt){let{initialDelay:e,maxDelay:s,multiplier:n,debug:i=!1,onFailedAttempt:o,maxRetries:c=1/0}=t;return async(...h)=>{var S,v;let u=h[0],d=h[1],g=e,b=0;for(;;)try{let E=await r(...h);if(E.ok)return E;throw await w.fromResponse(E,u.toString())}catch(E){if(o==null||o(),(S=d==null?void 0:d.signal)!=null&&S.aborted)throw new O;if(E instanceof w&&!Jr.includes(E.status)&&E.status>=400&&E.status<500)throw E;{if(b++,b>c)throw i&&console.log(`Max retries reached (${b}/${c}), giving up`),E;let A=E instanceof w&&E.headers?Xr(E.headers["retry-after"]):0,P=Math.random()*g,L=Math.min(P,s),C=Math.max(A,L);if(i){let _e=A>0?"server+client":"client";console.log(`Retry attempt #${b} after ${C}ms (${_e}, serverMin=${A}ms, clientBackoff=${L}ms)`)}await Zr(C,(v=d==null?void 0:d.signal)!=null?v:void 0),g=Math.min(g*n,s)}}}}var en=[201,204,205];async function As(r,t,e){try{if(r.status<200||en.includes(r.status))return r;let s=await r.text();return new Response(s,r)}catch(s){throw e!=null&&e.aborted?new O:new w(r.status,void 0,void 0,Object.fromEntries([...r.headers.entries()]),t,s instanceof Error?s.message:typeof s=="string"?s:"failed to read body")}}function ur(r){return async(...t)=>{var n,i;let e=t[0],s=await r(...t);return As(s,e.toString(),(i=(n=t[1])==null?void 0:n.signal)!=null?i:void 0)}}var tn={maxChunksToPrefetch:2};function dr(r,t=tn){let{maxChunksToPrefetch:e}=t,s;return async(...i)=>{let o=i[0].toString();if(cn(i[0],i[1])!=="GET")return s==null||s.abort(),s=void 0,r(...i);let h=s==null?void 0:s.consume(...i);if(h)return h;s==null||s.abort(),s=void 0;let u=await r(...i),d=Ts(o,u);return d&&(s=new xs({fetchClient:r,maxPrefetchedRequests:e,url:d,requestInit:i[1]})),u}}var sn=[Ue,J],rn=[Ft],nn=[et];function fr(r){return async(...t)=>{let e=await r(...t);if(e.ok){let s=e.headers,n=[],i=d=>n.push(...d.filter(g=>!s.has(g))),c=t[0].toString(),h=new URL(c);if([Le,at,rt,nt,Oe].some(d=>h.searchParams.has(d)))return e;if(i(sn),h.searchParams.get(F)==="true"&&i(rn),(!h.searchParams.has(F)||h.searchParams.get(F)==="false")&&i(nn),n.length>0)throw new G(c,n)}return e}}var it,ot,N,pe,j,De,Nt,xs=class{constructor(t){m(this,De);m(this,it);m(this,ot);m(this,N,new Map);m(this,pe);m(this,j);var e;l(this,it,(e=t.fetchClient)!=null?e:(...s)=>fetch(...s)),l(this,ot,t.maxPrefetchedRequests),l(this,pe,t.url.toString()),l(this,j,a(this,pe)),p(this,De,Nt).call(this,t.url,t.requestInit)}abort(){a(this,N).forEach(([t,e])=>e.abort()),a(this,N).clear()}consume(...t){let e=t[0].toString(),s=a(this,N).get(e);if(!s||e!==a(this,pe))return;let[n,i]=s;if(i.signal.aborted){a(this,N).delete(e);return}return a(this,N).delete(e),n.then(o=>{let c=Ts(e,o);l(this,pe,c),a(this,j)&&!a(this,N).has(a(this,j))&&p(this,De,Nt).call(this,a(this,j),t[1])}).catch(()=>{}),n}};it=new WeakMap,ot=new WeakMap,N=new WeakMap,pe=new WeakMap,j=new WeakMap,De=new WeakSet,Nt=function(...t){var n,i;let e=t[0].toString();if(a(this,N).size>=a(this,ot))return;let s=new AbortController;try{let{signal:o,cleanup:c}=an(s,(n=t[1])==null?void 0:n.signal),h=a(this,it).call(this,e,_(R({},(i=t[1])!=null?i:{}),{signal:o}));a(this,N).set(e,[h,s]),h.then(u=>{if(!u.ok||s.signal.aborted)return;let d=Ts(e,u);if(!d||d===e){l(this,j,void 0);return}return l(this,j,d),p(this,De,Nt).call(this,d,t[1])}).catch(()=>{}).finally(c)}catch(o){}};function Ts(r,t){let e=t.headers.get(J),s=t.headers.get(Ue),n=t.headers.has(nr);if(!e||!s||n)return;let i=new URL(r);if(i.searchParams.has(F))return;let o=i.searchParams.get(st);if(o&&e===o){console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${e}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. Skipping prefetch to prevent infinite 409 loop.`);return}return i.searchParams.set(ue,e),i.searchParams.set(de,s),i.searchParams.sort(),i.toString()}function an(r,t){let e=on;if(t)if(t.aborted)r.abort();else{let s=()=>r.abort();t.addEventListener("abort",s,{once:!0,signal:r.signal}),e=()=>t.removeEventListener("abort",s)}return{signal:r.signal,cleanup:e}}function on(){}function cn(r,t){return t!=null&&t.method?t.method.toUpperCase():typeof Request!="undefined"&&r instanceof Request?r.method.toUpperCase():"GET"}function ct(r,t){switch(r.type){case"ref":{let e=t?t(r.column):r.column;return Xe(e)}case"val":return`$${r.paramIndex}`;case"func":return ln(r,t);default:{let e=r;throw new Error(`Unknown expression type: ${JSON.stringify(e)}`)}}}function ln(r,t){let e=r.args.map(s=>ct(s,t));switch(r.name){case"eq":return`${e[0]} = ${e[1]}`;case"gt":return`${e[0]} > ${e[1]}`;case"gte":return`${e[0]} >= ${e[1]}`;case"lt":return`${e[0]} < ${e[1]}`;case"lte":return`${e[0]} <= ${e[1]}`;case"and":return e.map(s=>`(${s})`).join(" AND ");case"or":return e.map(s=>`(${s})`).join(" OR ");case"not":return`NOT (${e[0]})`;case"in":return`${e[0]} = ANY(${e[1]})`;case"like":return`${e[0]} LIKE ${e[1]}`;case"ilike":return`${e[0]} ILIKE ${e[1]}`;case"isNull":case"isUndefined":return`${e[0]} IS NULL`;case"upper":return`UPPER(${e[0]})`;case"lower":return`LOWER(${e[0]})`;case"length":return`LENGTH(${e[0]})`;case"concat":return`CONCAT(${e.join(", ")})`;case"coalesce":return`COALESCE(${e.join(", ")})`;default:throw new Error(`Unknown function: ${r.name}`)}}function $t(r,t){return r.map(e=>{let s=t?t(e.column):e.column,n=Xe(s);return e.direction==="desc"&&(n+=" DESC"),e.nulls==="first"&&(n+=" NULLS FIRST"),e.nulls==="last"&&(n+=" NULLS LAST"),n}).join(", ")}async function mr(r,t){let e=r.getReader(),s;for(;!(s=await e.read()).done;)t(s.value)}function gr(r){let t,e,s,n=!1;return function(o){t===void 0?(t=o,e=0,s=-1):t=hn(t,o);let c=t.length,h=0;for(;e<c;){n&&(t[e]===10&&(h=++e),n=!1);let u=-1;for(;e<c&&u===-1;++e)switch(t[e]){case 58:s===-1&&(s=e-h);break;case 13:n=!0;case 10:u=e;break}if(u===-1)break;r(t.subarray(h,u),s),h=e,s=-1}h===c?t=void 0:h!==0&&(t=t.subarray(h),e-=h)}}function yr(r,t,e){let s=pr(),n=new TextDecoder;return function(o,c){if(o.length===0)e==null||e(s),s=pr();else if(c>0){let h=n.decode(o.subarray(0,c)),u=c+(o[c+1]===32?2:1),d=n.decode(o.subarray(u));switch(h){case"data":s.data=s.data?s.data+` `+d:d;break;case"event":s.event=d;break;case"id":r(s.id=d);break;case"retry":let g=parseInt(d,10);isNaN(g)||t(s.retry=g);break}}}}function hn(r,t){let e=new Uint8Array(r.length+t.length);return e.set(r),e.set(t,r.length),e}function pr(){return{data:"",event:"",id:"",retry:void 0}}var un=function(r,t){var e={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&t.indexOf(s)<0&&(e[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(e[s[n]]=r[s[n]]);return e},Vt="text/event-stream",dn=1e3,Sr="last-event-id";function Ps(r,t){var{signal:e,headers:s,onopen:n,onmessage:i,onclose:o,onerror:c,openWhenHidden:h,fetch:u}=t,d=un(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,b)=>{let S=Object.assign({},s);S.accept||(S.accept=Vt);let v;function E(){v.abort(),typeof document!="undefined"&&!document.hidden&&Me()}typeof document!="undefined"&&!h&&document.addEventListener("visibilitychange",E);let A=dn,P=0;function L(){typeof document!="undefined"&&document.removeEventListener("visibilitychange",E),clearTimeout(P),v.abort()}e==null||e.addEventListener("abort",()=>{L()});let C=u!=null?u:window.fetch,_e=n!=null?n:fn;async function Me(){var ze;v=new AbortController;let At=e.aborted?e:v.signal;try{let Ge=await C(r,Object.assign(Object.assign({},d),{headers:S,signal:At}));await _e(Ge),await mr(Ge.body,gr(yr(Q=>{Q?S[Sr]=Q:delete S[Sr]},Q=>{A=Q},i))),o==null||o(),L(),g()}catch(Ge){if(At.aborted)L(),b(Ge);else if(!v.signal.aborted)try{let Q=(ze=c==null?void 0:c(Ge))!==null&&ze!==void 0?ze:A;clearTimeout(P),P=setTimeout(Me,Q)}catch(Q){L(),b(Q)}}}Me()})}function fn(r){let t=r.headers.get("content-type");if(!(t!=null&&t.startsWith(Vt)))throw new Error(`Expected content-type to be ${Vt}, Actual: ${t}`)}var Cs=class{constructor(){this.data={};this.max=250;this.storageKey="electric_expired_shapes";this.load()}getExpiredHandle(t){let e=this.data[t];return e?(e.lastUsed=Date.now(),this.save(),e.expiredHandle):null}markExpired(t,e){this.data[t]={expiredHandle:e,lastUsed:Date.now()};let s=Object.keys(this.data);if(s.length>this.max){let n=s.reduce((i,o)=>this.data[o].lastUsed<this.data[i].lastUsed?o:i);delete this.data[n]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(t){}}load(){if(typeof localStorage!="undefined")try{let t=localStorage.getItem(this.storageKey);t&&(this.data=JSON.parse(t))}catch(t){this.data={}}}clear(){this.data={},this.save()}delete(t){delete this.data[t],this.save()}},X=new Cs;var _s=class{constructor(){this.data={};this.storageKey="electric_up_to_date_tracker";this.cacheTTL=6e4;this.maxEntries=250;this.writeThrottleMs=6e4;this.lastWriteTime=0;this.load(),this.cleanup()}recordUpToDate(t,e){this.data[t]={timestamp:Date.now(),cursor:e};let s=Object.keys(this.data);if(s.length>this.maxEntries){let n=s.reduce((i,o)=>this.data[o].timestamp<this.data[i].timestamp?o:i);delete this.data[n]}this.scheduleSave()}scheduleSave(){let t=Date.now(),e=t-this.lastWriteTime;if(e>=this.writeThrottleMs)this.lastWriteTime=t,this.save();else if(!this.pendingSaveTimer){let s=this.writeThrottleMs-e;this.pendingSaveTimer=setTimeout(()=>{this.lastWriteTime=Date.now(),this.pendingSaveTimer=void 0,this.save()},s)}}shouldEnterReplayMode(t){let e=this.data[t];return!e||Date.now()-e.timestamp>=this.cacheTTL?null:e.cursor}cleanup(){let t=Date.now(),e=Object.keys(this.data),s=!1;for(let n of e)t-this.data[n].timestamp>this.cacheTTL&&(delete this.data[n],s=!0);s&&this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(t){}}load(){if(typeof localStorage!="undefined")try{let t=localStorage.getItem(this.storageKey);t&&(this.data=JSON.parse(t))}catch(t){this.data={}}}clear(){this.data={},this.pendingSaveTimer&&(clearTimeout(this.pendingSaveTimer),this.pendingSaveTimer=void 0),this.save()}delete(t){delete this.data[t],this.save()}},lt=new _s;var M,Ms,ks,Us,br,Ls,jt=class{constructor(){m(this,M);this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(t,e){p(this,M,Ms).call(this,t.snapshot_mark);let s=BigInt(t.xmax),n=BigInt(t.database_lsn);this.activeSnapshots.set(t.snapshot_mark,{xmin:BigInt(t.xmin),xmax:s,xip_list:t.xip_list.map(BigInt),keys:e,databaseLsn:n}),p(this,M,ks).call(this,this.xmaxSnapshots,s,t.snapshot_mark),p(this,M,ks).call(this,this.snapshotsByDatabaseLsn,n,t.snapshot_mark)}removeSnapshot(t){p(this,M,Ms).call(this,t),this.activeSnapshots.delete(t)}shouldRejectMessage(t){let e=t.headers.txids||[];if(e.length===0)return!1;for(let[s,n]of this.xmaxSnapshots.entries())if(p(this,M,Ls).call(this,e,s)>=s)for(let o of n)this.removeSnapshot(o);return[...this.activeSnapshots.values()].some(s=>{if(!s.keys.has(t.key))return!1;let n=p(this,M,Ls).call(this,e,s.xmax);return fs(n,s)})}lastSeenUpdate(t){for(let[e,s]of this.snapshotsByDatabaseLsn.entries())if(e<=t)for(let n of s)this.removeSnapshot(n)}};M=new WeakSet,Ms=function(t){let e=this.activeSnapshots.get(t);e&&(p(this,M,Us).call(this,this.xmaxSnapshots,e.xmax,t),p(this,M,Us).call(this,this.snapshotsByDatabaseLsn,e.databaseLsn,t))},ks=function(t,e,s){let n=t.get(e);n?n.add(s):t.set(e,new Set([s]))},Us=function(t,e,s){let n=t.get(e);n&&(n.delete(s),n.size===0&&t.delete(e))},br=function(t,e){return e+BigInt.asIntN(32,BigInt(t)-e)},Ls=function(t,e){return t.reduce((s,n)=>{let i=p(this,M,br).call(this,n,e);return i>s?i:s},BigInt(-1))};var ht=class{get isUpToDate(){return!1}get staleCacheBuster(){}get staleCacheRetryCount(){return 0}get sseFallbackToLongPolling(){return!1}get consecutiveShortSseConnections(){return 0}get replayCursor(){}canEnterReplayMode(){return!1}enterReplayMode(t){return this}shouldUseSse(t){return!1}handleSseConnectionClosed(t){return{state:this,fellBackToLongPolling:!1,wasShortConnection:!1}}applyUrlParams(t,e){}handleResponseMetadata(t){return{action:"ignored",state:this}}handleMessageBatch(t){return{state:this,suppressBatch:!1,becameUpToDate:!1}}pause(){return new pt(this)}toErrorState(t){return new Ie(this,t)}markMustRefetch(t){return new Wt({handle:t,offset:"-1",liveCacheBuster:"",lastSyncedAt:this.lastSyncedAt,schema:void 0})}},x,ut=class extends ht{constructor(e){super();m(this,x);l(this,x,e)}get handle(){return a(this,x).handle}get offset(){return a(this,x).offset}get schema(){return a(this,x).schema}get liveCacheBuster(){return a(this,x).liveCacheBuster}get lastSyncedAt(){return a(this,x).lastSyncedAt}get currentFields(){return a(this,x)}applyUrlParams(e,s){e.searchParams.set(de,a(this,x).offset),a(this,x).handle&&e.searchParams.set(ue,a(this,x).handle)}parseResponseFields(e){var u,d,g;let s=e.responseHandle,n=s&&s!==e.expiredHandle?s:a(this,x).handle,i=(u=e.responseOffset)!=null?u:a(this,x).offset,o=(d=e.responseCursor)!=null?d:a(this,x).liveCacheBuster,c=(g=a(this,x).schema)!=null?g:e.responseSchema,h=e.status===204?e.now:a(this,x).lastSyncedAt;return{handle:n,offset:i,schema:c,liveCacheBuster:o,lastSyncedAt:h}}checkStaleResponse(e){let s=e.responseHandle,n=e.expiredHandle;if(!s||s!==n)return null;let i=this.staleCacheRetryCount+1;return{action:"stale-retry",state:new Ds(_(R({},this.currentFields),{staleCacheBuster:e.createCacheBuster(),staleCacheRetryCount:i})),exceededMaxRetries:i>e.maxStaleCacheRetries}}handleMessageBatch(e){if(!e.hasMessages||!e.hasUpToDateMessage)return{state:this,suppressBatch:!1,becameUpToDate:!1};let s=a(this,x).offset;e.isSse&&e.upToDateOffset&&(s=e.upToDateOffset);let n={handle:a(this,x).handle,offset:s,schema:a(this,x).schema,liveCacheBuster:a(this,x).liveCacheBuster,lastSyncedAt:e.now};return this.onUpToDate(n,e)}onUpToDate(e,s){return{state:new ft(e),suppressBatch:!1,becameUpToDate:!0}}};x=new WeakMap;var dt=class extends ut{handleResponseMetadata(t){let e=this.checkStaleResponse(t);if(e)return e;let s=this.parseResponseFields(t);return t.status===204?{action:"accepted",state:new ft(s,{sseFallbackToLongPolling:!0})}:{action:"accepted",state:new Os(s)}}canEnterReplayMode(){return!0}enterReplayMode(t){return new Bs(_(R({},this.currentFields),{replayCursor:t}))}},Wt=class r extends dt{constructor(e){super(e);this.kind="initial"}withHandle(e){return new r(_(R({},this.currentFields),{handle:e}))}},Os=class r extends dt{constructor(e){super(e);this.kind="syncing"}withHandle(e){return new r(_(R({},this.currentFields),{handle:e}))}},me,He,Hs=class Hs extends dt{constructor(e){let o=e,{staleCacheBuster:s,staleCacheRetryCount:n}=o,i=Je(o,["staleCacheBuster","staleCacheRetryCount"]);super(i);this.kind="stale-retry";m(this,me);m(this,He);l(this,me,s),l(this,He,n)}get staleCacheBuster(){return a(this,me)}get staleCacheRetryCount(){return a(this,He)}canEnterReplayMode(){return!1}withHandle(e){return new Hs(_(R({},this.currentFields),{handle:e,staleCacheBuster:a(this,me),staleCacheRetryCount:a(this,He)}))}applyUrlParams(e,s){super.applyUrlParams(e,s),e.searchParams.set(fe,a(this,me))}};me=new WeakMap,He=new WeakMap;var Ds=Hs,ge,Z,Be=class Be extends ut{constructor(e,s){var n,i;super(e);this.kind="live";m(this,ge);m(this,Z);l(this,ge,(n=s==null?void 0:s.consecutiveShortSseConnections)!=null?n:0),l(this,Z,(i=s==null?void 0:s.sseFallbackToLongPolling)!=null?i:!1)}get isUpToDate(){return!0}get consecutiveShortSseConnections(){return a(this,ge)}get sseFallbackToLongPolling(){return a(this,Z)}withHandle(e){return new Be(_(R({},this.currentFields),{handle:e}),this.sseState)}applyUrlParams(e,s){super.applyUrlParams(e,s),s.isSnapshotRequest||(e.searchParams.set(tt,this.liveCacheBuster),s.canLongPoll&&e.searchParams.set(F,"true"))}get sseState(){return{consecutiveShortSseConnections:a(this,ge),sseFallbackToLongPolling:a(this,Z)}}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let n=this.parseResponseFields(e);return{action:"accepted",state:new Be(n,this.sseState)}}onUpToDate(e,s){return{state:new Be(e,this.sseState),suppressBatch:!1,becameUpToDate:!0}}shouldUseSse(e){return e.liveSseEnabled&&!e.isRefreshing&&!e.resumingFromPause&&!a(this,Z)}handleSseConnectionClosed(e){let s=a(this,ge),n=a(this,Z),i=!1,o=!1;return e.connectionDuration<e.minConnectionDuration&&!e.wasAborted?(o=!0,s=s+1,s>=e.maxShortConnections&&(n=!0,i=!0)):e.connectionDuration>=e.minConnectionDuration&&(s=0),{state:new Be(this.currentFields,{consecutiveShortSseConnections:s,sseFallbackToLongPolling:n}),fellBackToLongPolling:i,wasShortConnection:o}}};ge=new WeakMap,Z=new WeakMap;var ft=Be,ee,Yt=class Yt extends ut{constructor(e){let i=e,{replayCursor:s}=i,n=Je(i,["replayCursor"]);super(n);this.kind="replaying";m(this,ee);l(this,ee,s)}get replayCursor(){return a(this,ee)}withHandle(e){return new Yt(_(R({},this.currentFields),{handle:e,replayCursor:a(this,ee)}))}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let n=this.parseResponseFields(e);return{action:"accepted",state:new Yt(_(R({},n),{replayCursor:a(this,ee)}))}}onUpToDate(e,s){let n=!s.isSse&&a(this,ee)===s.currentCursor;return{state:new ft(e),suppressBatch:n,becameUpToDate:!0}}};ee=new WeakMap;var Bs=Yt,pt=class r extends ht{constructor(e){super();this.kind="paused";this.previousState=e instanceof r?e.previousState:e}get handle(){return this.previousState.handle}get offset(){return this.previousState.offset}get schema(){return this.previousState.schema}get liveCacheBuster(){return this.previousState.liveCacheBuster}get lastSyncedAt(){return this.previousState.lastSyncedAt}get isUpToDate(){return this.previousState.isUpToDate}get staleCacheBuster(){return this.previousState.staleCacheBuster}get staleCacheRetryCount(){return this.previousState.staleCacheRetryCount}get sseFallbackToLongPolling(){return this.previousState.sseFallbackToLongPolling}get consecutiveShortSseConnections(){return this.previousState.consecutiveShortSseConnections}get replayCursor(){return this.previousState.replayCursor}handleResponseMetadata(e){let s=this.previousState.handleResponseMetadata(e);if(s.action==="accepted")return{action:"accepted",state:new r(s.state)};if(s.action==="ignored")return{action:"ignored",state:this};if(s.action==="stale-retry")return{action:"stale-retry",state:new r(s.state),exceededMaxRetries:s.exceededMaxRetries};let n=s;throw new Error(`PausedState.handleResponseMetadata: unhandled transition action "${n.action}"`)}withHandle(e){return new r(this.previousState.withHandle(e))}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}pause(){return this}resume(){return this.previousState}},Ie=class r extends ht{constructor(e,s){super();this.kind="error";this.previousState=e instanceof r?e.previousState:e,this.error=s}get handle(){return this.previousState.handle}get offset(){return this.previousState.offset}get schema(){return this.previousState.schema}get liveCacheBuster(){return this.previousState.liveCacheBuster}get lastSyncedAt(){return this.previousState.lastSyncedAt}get isUpToDate(){return this.previousState.isUpToDate}get staleCacheBuster(){return this.previousState.staleCacheBuster}get staleCacheRetryCount(){return this.previousState.staleCacheRetryCount}get sseFallbackToLongPolling(){return this.previousState.sseFallbackToLongPolling}get consecutiveShortSseConnections(){return this.previousState.consecutiveShortSseConnections}get replayCursor(){return this.previousState.replayCursor}withHandle(e){return new r(this.previousState.withHandle(e),this.error)}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}retry(){return this.previousState}reset(e){return this.previousState.markMustRefetch(e)}};function Er(r){return new Wt({handle:r.handle,offset:r.offset,liveCacheBuster:"",lastSyncedAt:void 0,schema:void 0})}var H,mt,gt,Kt=class{constructor(t){m(this,H,new Set);m(this,mt);m(this,gt);l(this,mt,t.onAcquired),l(this,gt,t.onReleased)}acquire(t){if(a(this,H).has(t)){console.warn(`[Electric] PauseLock: "${t}" already held \u2014 ignoring duplicate acquire`);return}let e=a(this,H).size===0;a(this,H).add(t),e&&a(this,mt).call(this)}release(t){if(!a(this,H).delete(t)){console.warn(`[Electric] PauseLock: "${t}" not held \u2014 ignoring release (possible acquire/release mismatch)`);return}a(this,H).size===0&&a(this,gt).call(this)}get isPaused(){return a(this,H).size>0}isHeldBy(t){return a(this,H).has(t)}releaseAllMatching(t){for(let e of a(this,H))e.startsWith(t)&&a(this,H).delete(e)}};H=new WeakMap,mt=new WeakMap,gt=new WeakMap;var pn;function Rr(){return pn}var mn=new Set([tt,ue,F,de,fe]),ye="https://electric-sql.com/docs/guides/troubleshooting";function Qt(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async function Ws(r){return typeof r=="function"?r():r}async function gn(r){let t=Object.entries(r),e=await Promise.all(t.map(async([s,n])=>{if(n===void 0)return[s,void 0];let i=await Ws(n);return[s,Array.isArray(i)?i.join(","):i]}));return Object.fromEntries(e.filter(([s,n])=>n!==void 0))}async function yn(r){if(!r)return{};let t=Object.entries(r),e=await Promise.all(t.map(async([s,n])=>[s,await Ws(n)]));return Object.fromEntries(e)}var wr=r=>{if(r!==null)return r==="active"?"visible":"hidden"};function Ea(r){return{getCurrentState:()=>wr(r.currentState),subscribe:t=>{let e=r.addEventListener("change",s=>{let n=wr(s);n&&t(n)});return()=>e.remove()}}}function Sn(){var r;return(r=Rr())==null?void 0:r()}function Se(r){let t=new URL(r.origin+r.pathname);for(let[e,s]of r.searchParams)vs.includes(e)||t.searchParams.append(e,s);return t.searchParams.sort(),t.toString()}var Ne,St,Ee,Re,te,V,y,W,se,qe,I,we,re,ve,ts,f,zt,Y,$e,Ve,je,We,xe,k,q,bt,ss,rs,ns,as,Et,ne,ae,ie,$,Ye,Ke,is,os,K,Rt,Te,wt,Ae,Pe,oe,vt,xt,yt,be,xr,Fe,Tr,Gt,Ar,Fs,Jt,Pr,Cr,_r,Mr,Ns,qs,Xt,$s,Zt,kr,Ur,Lr,es,Vs,Or,Is=class{constructor(t){m(this,f);m(this,Ne,null);m(this,St);m(this,Ee);m(this,Re);m(this,te,new Map);m(this,V,!1);m(this,y);m(this,W,!1);m(this,se);m(this,qe);m(this,I);m(this,we,new WeakSet);m(this,re,0);m(this,ve,!1);m(this,ts,0);m(this,Y);m(this,$e);m(this,Ve);m(this,je,Promise.resolve([]));m(this,We,!1);m(this,xe,new jt);m(this,k);m(this,q);m(this,bt);m(this,ss,1e3);m(this,rs,3);m(this,ns,100);m(this,as,5e3);m(this,Et);m(this,ne);m(this,ae);m(this,ie,3);m(this,$,[]);m(this,Ye,500);m(this,Ke,5);m(this,is,100);m(this,os,5e3);m(this,K,0);m(this,Rt,5);m(this,Te);m(this,wt,5);m(this,Ae,null);m(this,Pe,null);m(this,oe,0);m(this,vt,50);m(this,xt);var o,c,h,u,d;this.options=R({subscribe:!0},t),wn(this.options),l(this,y,Er({offset:(o=this.options.offset)!=null?o:"-1",handle:this.options.handle})),l(this,k,new Kt({onAcquired:()=>{var g;l(this,y,a(this,y).pause()),a(this,V)&&((g=a(this,I))==null||g.abort(lr))},onReleased:()=>{var g;a(this,V)&&((g=this.options.signal)!=null&&g.aborted||p(this,f,yt).call(this).catch(()=>{}))}}));let e;if(t.columnMapper){let g=b=>{let S={};for(let[v,E]of Object.entries(b)){let A=t.columnMapper.decode(v);S[A]=E}return S};e=t.transformer?b=>t.transformer(g(b)):g}else e=t.transformer;l(this,Re,new Dt(t.parser,e)),l(this,qe,this.options.onError),l(this,se,(c=this.options.log)!=null?c:"full"),l(this,Et,(h=this.options.liveRequestTimeoutMs)!=null?h:45e3);let s=(u=t.fetchClient)!=null?u:(...g)=>fetch(...g),n=_(R({},(d=t.backoffOptions)!=null?d:qt),{onFailedAttempt:()=>{var g,b;l(this,W,!1),(b=(g=t.backoffOptions)==null?void 0:g.onFailedAttempt)==null||b.call(g)}});l(this,xt,{initialDelay:n.initialDelay,maxDelay:n.maxDelay,multiplier:n.multiplier});let i=hr(s,n);l(this,Ee,fr(dr(i))),l(this,St,ur(a(this,Ee))),p(this,f,kr).call(this)}get shapeHandle(){return a(this,y).handle}get error(){return a(this,Ne)}get isUpToDate(){return a(this,y).isUpToDate}get lastOffset(){return a(this,y).offset}get mode(){return a(this,se)}subscribe(t,e=()=>{}){let s={};return a(this,te).set(s,[t,e]),a(this,V)||p(this,f,yt).call(this),()=>{a(this,te).delete(s)}}unsubscribeAll(){var t,e;a(this,te).clear(),(t=a(this,ne))==null||t.call(this),(e=a(this,ae))==null||e.call(this)}lastSyncedAt(){return a(this,y).lastSyncedAt}lastSynced(){return a(this,y).lastSyncedAt===void 0?1/0:Date.now()-a(this,y).lastSyncedAt}isConnected(){return a(this,W)}isLoading(){return!a(this,y).isUpToDate}hasStarted(){return a(this,V)}isPaused(){return a(this,k).isPaused}async forceDisconnectAndRefresh(){z(this,re)._++,l(this,ve,!0);try{let t=a(this,I);a(this,y).isUpToDate&&t&&!t.signal.aborted&&(a(this,we).add(t),t.abort(ys)),await p(this,f,Ns).call(this)}finally{z(this,re)._--}}async requestSnapshot(t){if(a(this,se)==="full")throw new Error(`Snapshot requests are not supported in ${a(this,se)} mode, as the consumer is guaranteed to observe all data`);a(this,V)||p(this,f,yt).call(this).catch(()=>{});let e=`snapshot-${++z(this,ts)._}`;a(this,k).acquire(e);let s=setTimeout(()=>{console.warn(`[Electric] Snapshot "${e}" has held the pause lock for 30s \u2014 possible hung request or leaked lock. Current holders: ${[...new Set([e])].join(", ")}`,new Error("stack trace"))},3e4);try{let{metadata:n,data:i,responseOffset:o,responseHandle:c}=await this.fetchSnapshot(t),h=i.concat([{headers:R({control:"snapshot-end"},n)},{headers:R({control:"subset-end"},t)}]);if(a(this,xe).addSnapshot(n,new Set(i.map(u=>u.key))),await p(this,f,Jt).call(this,h,!1,{allowReentrantPublishBypass:!0}),o!==null||c!==null){let u=a(this,y).handleResponseMetadata({status:200,responseHandle:c,responseOffset:o,responseCursor:null,expiredHandle:null,now:Date.now(),maxStaleCacheRetries:a(this,ie),createCacheBuster:Qt});u.action==="accepted"?l(this,y,u.state):console.warn(`[Electric] Snapshot response metadata was not accepted by state "${a(this,y).kind}" (action: ${u.action}). Stream offset was not advanced from snapshot.`,new Error("stack trace"))}return{metadata:n,data:i}}finally{clearTimeout(s),a(this,k).release(e)}}async fetchSnapshot(t){return p(this,f,Vs).call(this,t,0)}};Ne=new WeakMap,St=new WeakMap,Ee=new WeakMap,Re=new WeakMap,te=new WeakMap,V=new WeakMap,y=new WeakMap,W=new WeakMap,se=new WeakMap,qe=new WeakMap,I=new WeakMap,we=new WeakMap,re=new WeakMap,ve=new WeakMap,ts=new WeakMap,f=new WeakSet,zt=function(){return a(this,re)>0},Y=new WeakMap,$e=new WeakMap,Ve=new WeakMap,je=new WeakMap,We=new WeakMap,xe=new WeakMap,k=new WeakMap,q=new WeakMap,bt=new WeakMap,ss=new WeakMap,rs=new WeakMap,ns=new WeakMap,as=new WeakMap,Et=new WeakMap,ne=new WeakMap,ae=new WeakMap,ie=new WeakMap,$=new WeakMap,Ye=new WeakMap,Ke=new WeakMap,is=new WeakMap,os=new WeakMap,K=new WeakMap,Rt=new WeakMap,Te=new WeakMap,wt=new WeakMap,Ae=new WeakMap,Pe=new WeakMap,oe=new WeakMap,vt=new WeakMap,xt=new WeakMap,yt=async function(){var t,e,s;l(this,V,!0),p(this,f,Lr).call(this);try{await p(this,f,Fe).call(this)}catch(n){if(l(this,Ne,n),n instanceof Error&&l(this,y,a(this,y).toErrorState(n)),a(this,qe)){let i=await a(this,qe).call(this,n),o=!(n instanceof G);if(i&&typeof i=="object"&&o){if(i.params&&(this.options.params=R(R({},(t=this.options.params)!=null?t:{}),i.params)),i.headers&&(this.options.headers=R(R({},(e=this.options.headers)!=null?e:{}),i.headers)),z(this,oe)._++,a(this,oe)>a(this,vt)){console.warn(`[Electric] onError retry loop exhausted after ${a(this,vt)} consecutive retries. The error was never resolved by the onError handler. Error: ${n instanceof Error?n.message:String(n)}`,new Error("stack trace")),n instanceof Error&&p(this,f,Xt).call(this,n),p(this,f,be).call(this);return}if(l(this,Ne,null),a(this,y)instanceof Ie&&l(this,y,a(this,y).retry()),l(this,K,0),l(this,$,[]),await p(this,f,xr).call(this,a(this,oe)),(s=this.options.signal)!=null&&s.aborted){p(this,f,be).call(this);return}return l(this,V,!1),p(this,f,yt).call(this)}n instanceof Error&&p(this,f,Xt).call(this,n),p(this,f,be).call(this);return}throw n instanceof Error&&p(this,f,Xt).call(this,n),p(this,f,be).call(this),n}p(this,f,be).call(this)},be=function(){var t,e;l(this,W,!1),(t=a(this,Ve))==null||t.call(this),(e=a(this,ae))==null||e.call(this)},xr=async function(t){let{initialDelay:e,maxDelay:s,multiplier:n}=a(this,xt),i=Math.min(s,e*Math.pow(n,t-1)),o=Math.floor(Math.random()*i),c=this.options.signal;o<=0||c!=null&&c.aborted||await new Promise(h=>{let u=!1,d=()=>{u||(u=!0,clearTimeout(g),c==null||c.removeEventListener("abort",d),h())},g=setTimeout(d,o);c==null||c.addEventListener("abort",d,{once:!0}),c!=null&&c.aborted&&d()})},Fe=async function(t){var d,g,b;if((d=this.options.signal)!=null&&d.aborted){p(this,f,be).call(this);return}if(a(this,y)instanceof Ie)throw a(this,y).error;let e=t!=null?t:a(this,Te);if(a(this,k).isPaused){e&&l(this,Te,e);return}if(!this.options.subscribe&&((g=this.options.signal)!=null&&g.aborted||a(this,y).isUpToDate))return;a(this,y).isUpToDate?(l(this,K,0),l(this,$,[])):await p(this,f,Tr).call(this);let s=!1;a(this,y)instanceof pt&&(s=!0,l(this,y,a(this,y).resume()));let{url:n,signal:i}=this.options,{fetchUrl:o,requestHeaders:c}=await p(this,f,Gt).call(this,n,s);e&&(o.searchParams.set(fe,e),o.searchParams.sort());let h=await p(this,f,Ar).call(this,i),u=a(this,I);if(a(this,k).isPaused){h&&i&&i.removeEventListener("abort",h),e&&l(this,Te,e),l(this,I,void 0);return}l(this,Te,void 0);try{await p(this,f,Pr).call(this,{fetchUrl:o,requestAbortController:u,headers:c,resumingFromPause:s})}catch(S){let v=u.signal.reason,E=a(this,we).delete(u),A=u.signal.aborted&&(E||v===ys||v===Ss||v===bs);if((S instanceof w||S instanceof O)&&A)return p(this,f,Fe).call(this);if(S instanceof O)return;if(S instanceof he)return p(this,f,Fe).call(this);if(!(S instanceof w))throw S;if(S.status==409){if(a(this,y).handle){let C=Se(o);X.markExpired(C,a(this,y).handle)}let P=S.headers[J];P||console.warn("[Electric] Received 409 response without a shape handle header. This likely indicates a proxy or CDN stripping required headers.");let L=Qt();return p(this,f,es).call(this,P),await p(this,f,qs).call(this,[{headers:{control:"must-refetch"}}]),p(this,f,Fe).call(this,L)}else throw S}finally{h&&i&&i.removeEventListener("abort",h),l(this,I,void 0)}return(b=a(this,$e))==null||b.call(this),p(this,f,Fe).call(this)},Tr=async function(){let t=Date.now(),e=a(this,y).offset;if(l(this,$,a(this,$).filter(o=>t-o.timestamp<a(this,Ye))),a(this,$).push({timestamp:t,offset:e}),a(this,$).filter(o=>o.offset===e).length<a(this,Ke))return;if(z(this,K)._++,a(this,K)>=a(this,Rt))throw new w(502,void 0,void 0,{},this.options.url,`Client is stuck in a fast retry loop (${a(this,Ke)} requests in ${a(this,Ye)}ms at the same offset, repeated ${a(this,Rt)} times). Client-side caches were cleared automatically on first detection, but the loop persists. This usually indicates a proxy or CDN misconfiguration. Common causes: - Proxy is not including query parameters (handle, offset) in its cache key - CDN is serving stale 409 responses - Proxy is stripping required Electric headers from responses For more information visit the troubleshooting guide: ${ye}`);if(a(this,K)===1){if(console.warn(`[Electric] Detected fast retry loop (${a(this,Ke)} requests in ${a(this,Ye)}ms at the same offset). Clearing client-side caches and resetting stream to recover. If this persists, check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key, and that required Electric headers are forwarded to the client. For more information visit the troubleshooting guide: ${ye}`,new Error("stack trace")),a(this,q)){let o=Se(a(this,q));X.delete(o),lt.delete(o)}else X.clear(),lt.clear();p(this,f,es).call(this),l(this,$,[]);return}let n=Math.min(a(this,os),a(this,is)*Math.pow(2,a(this,K))),i=Math.floor(Math.random()*n);await new Promise(o=>setTimeout(o,i)),l(this,$,[])},Gt=async function(t,e,s){var u,d,g,b,S,v;let[n,i]=await Promise.all([yn(this.options.headers),this.options.params?gn(vn(this.options.params)):void 0]);i&&Dr(i);let o=new URL(t);if(i){if(i.table&&D(o,ar,i.table),i.where&&typeof i.where=="string"){let A=ke(i.where,(u=this.options.columnMapper)==null?void 0:u.encode);D(o,ir,A)}if(i.columns){let A=await Ws((d=this.options.params)==null?void 0:d.columns);if(Array.isArray(A)){let P=A.map(String);this.options.columnMapper&&(P=P.map(this.options.columnMapper.encode));let L=P.map(Xe).join(",");D(o,ps,L)}else D(o,ps,i.columns)}i.replica&&D(o,or,i.replica),i.params&&D(o,cr,i.params);let E=R({},i);delete E.table,delete E.where,delete E.columns,delete E.replica,delete E.params;for(let[A,P]of Object.entries(E))D(o,A,P)}if(s){if(s.whereExpr){let E=ct(s.whereExpr,(g=this.options.columnMapper)==null?void 0:g.encode);D(o,Le,E),o.searchParams.set(Rs,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let E=ke(s.where,(b=this.options.columnMapper)==null?void 0:b.encode);D(o,Le,E)}if(s.params&&o.searchParams.set(at,It(s.params)),s.limit!==void 0&&D(o,rt,s.limit),s.offset!==void 0&&D(o,nt,s.offset),s.orderByExpr){let E=$t(s.orderByExpr,(S=this.options.columnMapper)==null?void 0:S.encode);D(o,Oe,E),o.searchParams.set(ws,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let E=ke(s.orderBy,(v=this.options.columnMapper)==null?void 0:v.encode);D(o,Oe,E)}}a(this,y).applyUrlParams(o,{isSnapshotRequest:s!==void 0,canLongPoll:!a(this,f,zt)&&!e}),o.searchParams.set(Es,a(this,se));let c=Se(o),h=X.getExpiredHandle(c);return h&&o.searchParams.set(st,h),o.searchParams.sort(),{fetchUrl:o,requestHeaders:n}},Ar=async function(t){var e;if(l(this,I,new AbortController),t){let s=()=>{var n;(n=a(this,I))==null||n.abort(t.reason)};return t.addEventListener("abort",s,{once:!0}),t.aborted&&((e=a(this,I))==null||e.abort(t.reason)),s}},Fs=async function(t){var h,u,d;let{headers:e,status:s}=t,n=e.get(J),i=a(this,q)?Se(a(this,q)):null,o=i?X.getExpiredHandle(i):null;if(a(this,Pe)){let{shapeKey:g,staleHandle:b}=a(this,Pe);l(this,Pe,null),i===g&&n===b&&console.warn(`[Electric] Self-healing retry received the same handle "${b}" that was just marked expired. This means your proxy/CDN is serving a stale cached response and ignoring cache-buster query params. The client will proceed with this stale data to avoid a permanent failure, but it may be out of date until the cache refreshes. Fix: configure your proxy/CDN to include all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: ${ye}`,new Error("stack trace"))}let c=a(this,y).handleResponseMetadata({status:s,responseHandle:n,responseOffset:e.get(Ue),responseCursor:e.get(Ft),responseSchema:vr(e),expiredHandle:o,now:Date.now(),maxStaleCacheRetries:a(this,ie),createCacheBuster:Qt});if(l(this,y,c.state),s===204&&l(this,Ae,null),c.action==="accepted"&&s===204&&l(this,oe,0),c.action==="stale-retry")throw await((h=t.body)==null?void 0:h.cancel()),c.exceededMaxRetries?i&&(X.delete(i),a(this,Ae)!==i)?(console.warn(`[Electric] Stale cache retries exhausted (${a(this,ie)} attempts). Clearing expired handle entry and attempting self-healing retry without the expired_handle parameter. For more information visit the troubleshooting guide: ${ye}`,new Error("stack trace")),l(this,Ae,i),n&&l(this,Pe,{shapeKey:i,staleHandle:n}),p(this,f,es).call(this),new he("Expired handle entry evicted for self-healing retry")):new w(502,void 0,void 0,{},(d=(u=a(this,q))==null?void 0:u.toString())!=null?d:"",`CDN continues serving stale cached responses after ${a(this,ie)} retry attempts. This indicates a severe proxy/CDN misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: ${ye}`):(console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${n}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: ${ye} Retrying with a random cache buster to bypass the stale cache (attempt ${a(this,y).staleCacheRetryCount}/${a(this,ie)}).`,new Error("stack trace")),new he(`Received stale cached response with expired handle "${n}". This indicates a proxy/CDN caching misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key.`));return c.action==="ignored"?(console.warn(`[Electric] Response was ignored by state "${a(this,y).kind}". The response body will be skipped. This may indicate a proxy/CDN caching issue or a client state machine bug.`,new Error("stack trace")),!1):!0},Jt=async function(t,e=!1,s={}){if(!Array.isArray(t)){console.warn(`[Electric] #onMessages called with non-array argument (${typeof t}). This is a client bug \u2014 please report it.`,new Error("stack trace"));return}if(t.length===0)return;l(this,oe,0);let n=t[t.length-1],i=Ht(n),o=i?sr(n):void 0,c=a(this,y).handleMessageBatch({hasMessages:!0,hasUpToDateMessage:i,isSse:e,upToDateOffset:o,now:Date.now(),currentCursor:a(this,y).liveCacheBuster});if(l(this,y,c.state),i){if(l(this,ve,!1),c.suppressBatch)return;if(a(this,q)){let u=Se(a(this,q));lt.recordUpToDate(u,a(this,y).liveCacheBuster),l(this,Ae,null)}}let h=t.filter(u=>{if(Ze(u)){let d=u.headers.lsn;return typeof d=="string"&&d&&a(this,xe).lastSeenUpdate(BigInt(d)),!a(this,xe).shouldRejectMessage(u)}if(Ht(u)){let d=u.headers.global_last_seen_lsn;typeof d=="string"&&d&&a(this,xe).lastSeenUpdate(BigInt(d))}return!0});await p(this,f,qs).call(this,h,{allowReentrantBypass:s.allowReentrantPublishBypass})},Pr=async function(t){var s;if(l(this,q,t.fetchUrl),!a(this,y).isUpToDate&&a(this,y).canEnterReplayMode()){let n=Se(t.fetchUrl),i=lt.shouldEnterReplayMode(n);i&&l(this,y,a(this,y).enterReplayMode(i))}let e=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return a(this,y).shouldUseSse({liveSseEnabled:!!e,isRefreshing:a(this,f,zt),resumingFromPause:!!t.resumingFromPause})?(t.fetchUrl.searchParams.set(ms,"true"),t.fetchUrl.searchParams.set(gs,"true"),p(this,f,Mr).call(this,t)):p(this,f,_r).call(this,t)},Cr=async function(t,e,s){let n=a(this,Et),i=s.searchParams.get(F)==="true",o=a(this,f,zt)||a(this,ve);if(n===!1||!i&&!o)return t;let c,h=new Promise((u,d)=>{c=setTimeout(()=>{e.signal.aborted||(a(this,we).add(e),e.abort(bs)),d(new O)},n)});try{return await Promise.race([t,h])}finally{c&&clearTimeout(c)}},_r=async function(t){var S;let{fetchUrl:e,requestAbortController:s,headers:n}=t,i=e.toString(),o=await p(this,f,Cr).call(this,a(this,Ee).call(this,i,{signal:s.signal,headers:n}),s,e),c=await As(o,i,s.signal);if(l(this,W,!0),!await p(this,f,Fs).call(this,c))return;let u=a(this,y).schema,g=await c.text()||"[]",b=a(this,Re).parse(g,u);if(!Array.isArray(b)){let v=(S=It(b))==null?void 0:S.slice(0,200);throw new w(c.status,`Received non-array response body from shape endpoint. This may indicate a proxy or CDN is returning an unexpected response. Expected a JSON array, got ${typeof b}: ${v}`,void 0,Object.fromEntries(c.headers.entries()),e.toString())}await p(this,f,Jt).call(this,b)},Mr=async function(t){let{fetchUrl:e,requestAbortController:s,headers:n}=t,i=a(this,Ee);l(this,bt,Date.now());let o=_(R({},n),{Accept:"text/event-stream"}),c=!1;try{let h=[];await Ps(e.toString(),{headers:o,fetch:i,onopen:async u=>{if(l(this,W,!0),!await p(this,f,Fs).call(this,u))throw c=!0,new Error("stale response ignored")},onmessage:u=>{if(u.data){let d=a(this,y).schema,g=a(this,Re).parse(u.data,d);h.push(g),Ht(g)&&(p(this,f,Jt).call(this,h,!0),h=[])}},onerror:u=>{throw u},signal:s.signal})}catch(h){if(c)return;if(s.signal.aborted)throw new O;if(h instanceof w||h instanceof he||h instanceof G)throw h}finally{let h=Date.now()-a(this,bt),u=s.signal.aborted,d=a(this,y).handleSseConnectionClosed({connectionDuration:h,wasAborted:u,minConnectionDuration:a(this,ss),maxShortConnections:a(this,rs)});if(l(this,y,d.state),d.fellBackToLongPolling)console.warn("[Electric] 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. Note: Do NOT disable caching entirely - Electric uses cache headers to enable request collapsing for efficiency.",new Error("stack trace"));else if(d.wasShortConnection){let g=Math.min(a(this,as),a(this,ns)*Math.pow(2,a(this,y).consecutiveShortSseConnections)),b=Math.floor(Math.random()*g);await new Promise(S=>setTimeout(S,b))}}},Ns=async function(){if(a(this,k).isPaused)throw new Error("Cannot wait for next tick while PauseLock is held \u2014 this would deadlock because the request loop is paused");return a(this,Y)?a(this,Y):(l(this,Y,new Promise((t,e)=>{l(this,$e,t),l(this,Ve,e)})),a(this,Y).finally(()=>{l(this,Y,void 0),l(this,$e,void 0),l(this,Ve,void 0)}).catch(()=>{}),a(this,Y))},qs=async function(t,e={}){let s=()=>Promise.all(Array.from(a(this,te).values()).map(async([n,i])=>{try{await n(t)}catch(o){queueMicrotask(()=>{throw o})}}));return a(this,We)&&e.allowReentrantBypass?s():(l(this,je,a(this,je).then(async()=>{l(this,We,!0);try{return await s()}finally{l(this,We,!1)}})),a(this,je))},Xt=function(t){a(this,te).forEach(([e,s])=>{s==null||s(t)})},$s=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},Zt=function(t){t?a(this,k).acquire("visibility"):a(this,k).isHeldBy("visibility")&&a(this,k).release("visibility")},kr=function(){var e,s;let t=(e=this.options.runtimeVisibility)!=null?e:Sn();if(t){p(this,f,Zt).call(this,((s=t.getCurrentState)==null?void 0:s.call(t))==="hidden");let n=t.subscribe(i=>{p(this,f,Zt).call(this,i==="hidden")})