@electric-sql/client
Version:
Postgres everywhere - your data, in sync, wherever you need it.
10 lines • 58.7 kB
JavaScript
var Ir=Object.defineProperty,Fr=Object.defineProperties;var Nr=Object.getOwnPropertyDescriptors;var Pt=Object.getOwnPropertySymbols;var Qs=Object.prototype.hasOwnProperty,zs=Object.prototype.propertyIsEnumerable;var Gs=r=>{throw TypeError(r)};var Ks=(r,t,e)=>t in r?Ir(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,R=(r,t)=>{for(var e in t||(t={}))Qs.call(t,e)&&Ks(r,e,t[e]);if(Pt)for(var e of Pt(t))zs.call(t,e)&&Ks(r,e,t[e]);return r},_=(r,t)=>Fr(r,Nr(t));var Ge=(r,t)=>{var e={};for(var s in r)Qs.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&&zs.call(r,s)&&(e[s]=r[s]);return e};var ls=(r,t,e)=>t.has(r)||Gs("Cannot "+e);var a=(r,t,e)=>(ls(r,t,"read from private field"),e?e.call(r):t.get(r)),f=(r,t,e)=>t.has(r)?Gs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),l=(r,t,e,s)=>(ls(r,t,"write to private field"),s?s.call(r,e):t.set(r,e),e),p=(r,t,e)=>(ls(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"}},Ot=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 Lt=r=>Number(r),qr=r=>r==="true"||r==="t",$r=r=>BigInt(r),Js=r=>JSON.parse(r),Vr=r=>r,jr={int2:Lt,int4:Lt,int8:$r,bool:qr,float4:Lt,float8:Lt,json:Js,jsonb:Js};function Wr(r,t){let e=0,s=null,n="",i=!1,o=0,c;function h(m,g,b){let S=m.slice(g,b);return S=S==="NULL"?null:S,t?t(S):S}function u(m){let g=[];for(;e<m.length;e++){if(s=m[e],i)s==="\\"?n+=m[++e]:s==='"'?(g.push(t?t(n):n),n="",i=m[e+1]==='"',o=e+2):n+=s;else if(s==='"')i=!0;else if(s==="{")o=++e,g.push(u(m));else if(s==="}"){i=!1,o<e&&g.push(h(m,o,e)),o=e+1;break}else s===","&&c!=="}"&&c!=='"'&&(g.push(h(m,o,e)),o=e+1);c=s}return o<e&&g.push(g.push(h(m,o,e+1))),g}return u(r)[0]}var Dt=class{constructor(t,e){this.parser=R(R({},jr),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 m=n,{type:i,dims:o}=m,c=Ge(m,["type","dims"]),h=(g=this.parser[i])!=null?g:Vr,u=Xs(h,n,t);return o&&o>0?Xs((S,v)=>Wr(S,u),n,t)(e):u(e,c)}};function Xs(r,t,e){var n;let s=!((n=t.not_null)!=null&&n);return i=>{if(i===null){if(!s)throw new Ot(e!=null?e:"unknown");return null}return r(i,t)}}function Je(r){return`"${r.replace(/"/g,'""')}"`}function hs(r){var c,h,u,m;let t=(h=(c=r.match(/^_+/))==null?void 0:c[0])!=null?h:"",e=r.slice(t.length),s=(m=(u=e.match(/_+$/))==null?void 0:u[0])!=null?m:"",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 Zs(r){return r.replace(/([a-z_])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function er(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 Me(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 Yr(r){if(r){let t={};for(let e of Object.keys(r))t[e]=hs(e);return er(t)}return{decode:t=>hs(t),encode:t=>Zs(t)}}function Xe(r){return r!=null&&"key"in r}function Bt(r){return r!=null&&"headers"in r&&"control"in r.headers}function ds(r){return Bt(r)&&r.headers.control==="up-to-date"}function tr(r){if(r.headers.control!="up-to-date")return;let t=r.headers.global_last_seen_lsn;return t?`${t}_0`:void 0}function Kr(r,t){return typeof t=="bigint"?t.toString():t}function Ht(r){return JSON.stringify(r,Kr)}function sr(r){return JSON.stringify(us(r))}function us(r){if(typeof r=="bigint")return r.toString();if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(us);let t={};for(let e of Object.keys(r).sort())t[e]=us(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 It="electric-cursor",J="electric-handle",ke="electric-offset",Ze="electric-schema",rr="electric-up-to-date",ps="columns",et="cursor",tt="expired_handle",ue="handle",I="live",de="offset",nr="table",ar="where",ir="replica",or="params",ms="experimental_live_sse",gs="live_sse",ys="force-disconnect-and-refresh",cr="pause-stream",Ss="system-wake",bs="live-request-timeout",Es="log",Ue="subset__where",st="subset__limit",rt="subset__offset",Oe="subset__order_by",nt="subset__params",Rs="subset__where_expr",ws="subset__order_by_expr",fe="cache-buster",vs=[I,gs,ms,ue,de,et,tt,Es,Ue,st,rt,Oe,nt,Rs,ws,fe];var Qr=[429],Nt={initialDelay:1e3,maxDelay:32e3,multiplier:2,maxRetries:1/0};function zr(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 Gr(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 lr(r,t=Nt){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],m=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=m==null?void 0:m.signal)!=null&&S.aborted)throw new O;if(E instanceof w&&!Qr.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?zr(E.headers["retry-after"]):0,P=Math.random()*g,U=Math.min(P,s),C=Math.max(A,U);if(i){let Ce=A>0?"server+client":"client";console.log(`Retry attempt #${b} after ${C}ms (${Ce}, serverMin=${A}ms, clientBackoff=${U}ms)`)}await Gr(C,(v=m==null?void 0:m.signal)!=null?v:void 0),g=Math.min(g*n,s)}}}}var Jr=[201,204,205];async function As(r,t,e){try{if(r.status<200||Jr.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 hr(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 Xr={maxChunksToPrefetch:2};function ur(r,t=Xr){let{maxChunksToPrefetch:e}=t,s;return async(...i)=>{let o=i[0].toString();if(nn(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),m=Ts(o,u);return m&&(s=new xs({fetchClient:r,maxPrefetchedRequests:e,url:m,requestInit:i[1]})),u}}var Zr=[ke,J],en=[It],tn=[Ze];function dr(r){return async(...t)=>{let e=await r(...t);if(e.ok){let s=e.headers,n=[],i=m=>n.push(...m.filter(g=>!s.has(g))),c=t[0].toString(),h=new URL(c);if([Ue,nt,st,rt,Oe].some(m=>h.searchParams.has(m)))return e;if(i(Zr),h.searchParams.get(I)==="true"&&i(en),(!h.searchParams.has(I)||h.searchParams.get(I)==="false")&&i(tn),n.length>0)throw new G(c,n)}return e}}var at,it,F,pe,j,Le,Ft,xs=class{constructor(t){f(this,Le);f(this,at);f(this,it);f(this,F,new Map);f(this,pe);f(this,j);var e;l(this,at,(e=t.fetchClient)!=null?e:(...s)=>fetch(...s)),l(this,it,t.maxPrefetchedRequests),l(this,pe,t.url.toString()),l(this,j,a(this,pe)),p(this,Le,Ft).call(this,t.url,t.requestInit)}abort(){a(this,F).forEach(([t,e])=>e.abort()),a(this,F).clear()}consume(...t){let e=t[0].toString(),s=a(this,F).get(e);if(!s||e!==a(this,pe))return;let[n,i]=s;if(i.signal.aborted){a(this,F).delete(e);return}return a(this,F).delete(e),n.then(o=>{let c=Ts(e,o);l(this,pe,c),a(this,j)&&!a(this,F).has(a(this,j))&&p(this,Le,Ft).call(this,a(this,j),t[1])}).catch(()=>{}),n}};at=new WeakMap,it=new WeakMap,F=new WeakMap,pe=new WeakMap,j=new WeakMap,Le=new WeakSet,Ft=function(...t){var n,i;let e=t[0].toString();if(a(this,F).size>=a(this,it))return;let s=new AbortController;try{let{signal:o,cleanup:c}=sn(s,(n=t[1])==null?void 0:n.signal),h=a(this,at).call(this,e,_(R({},(i=t[1])!=null?i:{}),{signal:o}));a(this,F).set(e,[h,s]),h.then(u=>{if(!u.ok||s.signal.aborted)return;let m=Ts(e,u);if(!m||m===e){l(this,j,void 0);return}return l(this,j,m),p(this,Le,Ft).call(this,m,t[1])}).catch(()=>{}).finally(c)}catch(o){}};function Ts(r,t){let e=t.headers.get(J),s=t.headers.get(ke),n=t.headers.has(rr);if(!e||!s||n)return;let i=new URL(r);if(i.searchParams.has(I))return;let o=i.searchParams.get(tt);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 sn(r,t){let e=rn;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 rn(){}function nn(r,t){return t!=null&&t.method?t.method.toUpperCase():typeof Request!="undefined"&&r instanceof Request?r.method.toUpperCase():"GET"}function ot(r,t){switch(r.type){case"ref":{let e=t?t(r.column):r.column;return Je(e)}case"val":return`$${r.paramIndex}`;case"func":return an(r,t);default:{let e=r;throw new Error(`Unknown expression type: ${JSON.stringify(e)}`)}}}function an(r,t){let e=r.args.map(s=>ot(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 qt(r,t){return r.map(e=>{let s=t?t(e.column):e.column,n=Je(s);return e.direction==="desc"&&(n+=" DESC"),e.nulls==="first"&&(n+=" NULLS FIRST"),e.nulls==="last"&&(n+=" NULLS LAST"),n}).join(", ")}async function pr(r,t){let e=r.getReader(),s;for(;!(s=await e.read()).done;)t(s.value)}function mr(r){let t,e,s,n=!1;return function(o){t===void 0?(t=o,e=0,s=-1):t=on(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 gr(r,t,e){let s=fr(),n=new TextDecoder;return function(o,c){if(o.length===0)e==null||e(s),s=fr();else if(c>0){let h=n.decode(o.subarray(0,c)),u=c+(o[c+1]===32?2:1),m=n.decode(o.subarray(u));switch(h){case"data":s.data=s.data?s.data+`
`+m:m;break;case"event":s.event=m;break;case"id":r(s.id=m);break;case"retry":let g=parseInt(m,10);isNaN(g)||t(s.retry=g);break}}}}function on(r,t){let e=new Uint8Array(r.length+t.length);return e.set(r),e.set(t,r.length),e}function fr(){return{data:"",event:"",id:"",retry:void 0}}var cn=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},$t="text/event-stream",ln=1e3,yr="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,m=cn(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,b)=>{let S=Object.assign({},s);S.accept||(S.accept=$t);let v;function E(){v.abort(),typeof document!="undefined"&&!document.hidden&&_e()}typeof document!="undefined"&&!h&&document.addEventListener("visibilitychange",E);let A=ln,P=0;function U(){typeof document!="undefined"&&document.removeEventListener("visibilitychange",E),clearTimeout(P),v.abort()}e==null||e.addEventListener("abort",()=>{U()});let C=u!=null?u:window.fetch,Ce=n!=null?n:hn;async function _e(){var Qe;v=new AbortController;let At=e.aborted?e:v.signal;try{let ze=await C(r,Object.assign(Object.assign({},m),{headers:S,signal:At}));await Ce(ze),await pr(ze.body,mr(gr(Q=>{Q?S[yr]=Q:delete S[yr]},Q=>{A=Q},i))),o==null||o(),U(),g()}catch(ze){if(At.aborted)U(),b(ze);else if(!v.signal.aborted)try{let Q=(Qe=c==null?void 0:c(ze))!==null&&Qe!==void 0?Qe:A;clearTimeout(P),P=setTimeout(_e,Q)}catch(Q){U(),b(Q)}}}_e()})}function hn(r){let t=r.headers.get("content-type");if(!(t!=null&&t.startsWith($t)))throw new Error(`Expected content-type to be ${$t}, 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()}},ct=new _s;var N,Ms,ks,Us,Vt=class{constructor(){f(this,N);this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(t,e){p(this,N,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,N,ks).call(this,this.xmaxSnapshots,s,t.snapshot_mark),p(this,N,ks).call(this,this.snapshotsByDatabaseLsn,n,t.snapshot_mark)}removeSnapshot(t){p(this,N,Ms).call(this,t),this.activeSnapshots.delete(t)}shouldRejectMessage(t){let e=t.headers.txids||[];if(e.length===0)return!1;let s=Math.max(...e);for(let[n,i]of this.xmaxSnapshots.entries())if(s>=n)for(let o of i)this.removeSnapshot(o);return[...this.activeSnapshots.values()].some(n=>n.keys.has(t.key)&&fs(s,n))}lastSeenUpdate(t){for(let[e,s]of this.snapshotsByDatabaseLsn.entries())if(e<=t)for(let n of s)this.removeSnapshot(n)}};N=new WeakSet,Ms=function(t){let e=this.activeSnapshots.get(t);e&&(p(this,N,Us).call(this,this.xmaxSnapshots,e.xmax,t),p(this,N,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))};var lt=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 ft(this)}toErrorState(t){return new He(this,t)}markMustRefetch(t){return new jt({handle:t,offset:"-1",liveCacheBuster:"",lastSyncedAt:this.lastSyncedAt,schema:void 0})}},x,ht=class extends lt{constructor(e){super();f(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,m,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=(m=e.responseCursor)!=null?m: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 Ls(_(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 dt(e),suppressBatch:!1,becameUpToDate:!0}}};x=new WeakMap;var ut=class extends ht{handleResponseMetadata(t){let e=this.checkStaleResponse(t);if(e)return e;let s=this.parseResponseFields(t);return t.status===204?{action:"accepted",state:new dt(s,{sseFallbackToLongPolling:!0})}:{action:"accepted",state:new Os(s)}}canEnterReplayMode(){return!0}enterReplayMode(t){return new Ds(_(R({},this.currentFields),{replayCursor:t}))}},jt=class r extends ut{constructor(e){super(e);this.kind="initial"}withHandle(e){return new r(_(R({},this.currentFields),{handle:e}))}},Os=class r extends ut{constructor(e){super(e);this.kind="syncing"}withHandle(e){return new r(_(R({},this.currentFields),{handle:e}))}},me,Be,Bs=class Bs extends ut{constructor(e){let o=e,{staleCacheBuster:s,staleCacheRetryCount:n}=o,i=Ge(o,["staleCacheBuster","staleCacheRetryCount"]);super(i);this.kind="stale-retry";f(this,me);f(this,Be);l(this,me,s),l(this,Be,n)}get staleCacheBuster(){return a(this,me)}get staleCacheRetryCount(){return a(this,Be)}canEnterReplayMode(){return!1}withHandle(e){return new Bs(_(R({},this.currentFields),{handle:e,staleCacheBuster:a(this,me),staleCacheRetryCount:a(this,Be)}))}applyUrlParams(e,s){super.applyUrlParams(e,s),e.searchParams.set(fe,a(this,me))}};me=new WeakMap,Be=new WeakMap;var Ls=Bs,ge,Z,De=class De extends ht{constructor(e,s){var n,i;super(e);this.kind="live";f(this,ge);f(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 De(_(R({},this.currentFields),{handle:e}),this.sseState)}applyUrlParams(e,s){super.applyUrlParams(e,s),s.isSnapshotRequest||(e.searchParams.set(et,this.liveCacheBuster),s.canLongPoll&&e.searchParams.set(I,"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 De(n,this.sseState)}}onUpToDate(e,s){return{state:new De(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 De(this.currentFields,{consecutiveShortSseConnections:s,sseFallbackToLongPolling:n}),fellBackToLongPolling:i,wasShortConnection:o}}};ge=new WeakMap,Z=new WeakMap;var dt=De,ee,Wt=class Wt extends ht{constructor(e){let i=e,{replayCursor:s}=i,n=Ge(i,["replayCursor"]);super(n);this.kind="replaying";f(this,ee);l(this,ee,s)}get replayCursor(){return a(this,ee)}withHandle(e){return new Wt(_(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 Wt(_(R({},n),{replayCursor:a(this,ee)}))}}onUpToDate(e,s){let n=!s.isSse&&a(this,ee)===s.currentCursor;return{state:new dt(e),suppressBatch:n,becameUpToDate:!0}}};ee=new WeakMap;var Ds=Wt,ft=class r extends lt{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}},He=class r extends lt{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 Sr(r){return new jt({handle:r.handle,offset:r.offset,liveCacheBuster:"",lastSyncedAt:void 0,schema:void 0})}var B,pt,mt,Yt=class{constructor(t){f(this,B,new Set);f(this,pt);f(this,mt);l(this,pt,t.onAcquired),l(this,mt,t.onReleased)}acquire(t){if(a(this,B).has(t)){console.warn(`[Electric] PauseLock: "${t}" already held \u2014 ignoring duplicate acquire`);return}let e=a(this,B).size===0;a(this,B).add(t),e&&a(this,pt).call(this)}release(t){if(!a(this,B).delete(t)){console.warn(`[Electric] PauseLock: "${t}" not held \u2014 ignoring release (possible acquire/release mismatch)`);return}a(this,B).size===0&&a(this,mt).call(this)}get isPaused(){return a(this,B).size>0}isHeldBy(t){return a(this,B).has(t)}releaseAllMatching(t){for(let e of a(this,B))e.startsWith(t)&&a(this,B).delete(e)}};B=new WeakMap,pt=new WeakMap,mt=new WeakMap;var un=new Set([et,ue,I,de,fe]),ye="https://electric-sql.com/docs/guides/troubleshooting";function Kt(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async function js(r){return typeof r=="function"?r():r}async function dn(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 js(n);return[s,Array.isArray(i)?i.join(","):i]}));return Object.fromEntries(e.filter(([s,n])=>n!==void 0))}async function fn(r){if(!r)return{};let t=Object.entries(r),e=await Promise.all(t.map(async([s,n])=>[s,await js(n)]));return Object.fromEntries(e)}var br=r=>{if(r!==null)return r==="active"?"visible":"hidden"};function pn(r){return{getCurrentState:()=>br(r.currentState),subscribe:t=>{let e=r.addEventListener("change",s=>{let n=br(s);n&&t(n)});return()=>e.remove()}}}function mn(){return typeof navigator=="object"&&"product"in navigator&&navigator.product==="ReactNative"}function gn(){let r=globalThis.require;if(typeof r=="function")return r;try{return Function('return typeof require === "function" ? require : undefined')()}catch(t){return}}function yn(){if(mn())try{let r=gn(),t=r==null?void 0:r("react-native");return t!=null&&t.AppState?pn(t.AppState):void 0}catch(r){return}}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 Fe,yt,Ee,Re,te,V,y,W,se,Ne,H,we,re,ve,es,d,Qt,Y,qe,$e,Ve,je,St,M,q,bt,ts,ss,rs,ns,Et,ne,ae,ie,$,We,Ye,as,is,K,Rt,xe,wt,Te,Ae,oe,vt,xt,gt,be,Rr,Ie,wr,zt,vr,Is,Gt,xr,Tr,Ar,Pr,Fs,Ns,Jt,qs,Xt,Cr,_r,Mr,Zt,$s,kr,Hs=class{constructor(t){f(this,d);f(this,Fe,null);f(this,yt);f(this,Ee);f(this,Re);f(this,te,new Map);f(this,V,!1);f(this,y);f(this,W,!1);f(this,se);f(this,Ne);f(this,H);f(this,we,new WeakSet);f(this,re,0);f(this,ve,!1);f(this,es,0);f(this,Y);f(this,qe);f(this,$e);f(this,Ve,Promise.resolve([]));f(this,je,!1);f(this,St,new Vt);f(this,M);f(this,q);f(this,bt);f(this,ts,1e3);f(this,ss,3);f(this,rs,100);f(this,ns,5e3);f(this,Et);f(this,ne);f(this,ae);f(this,ie,3);f(this,$,[]);f(this,We,500);f(this,Ye,5);f(this,as,100);f(this,is,5e3);f(this,K,0);f(this,Rt,5);f(this,xe);f(this,wt,5);f(this,Te,null);f(this,Ae,null);f(this,oe,0);f(this,vt,50);f(this,xt);var o,c,h,u,m;this.options=R({subscribe:!0},t),Rn(this.options),l(this,y,Sr({offset:(o=this.options.offset)!=null?o:"-1",handle:this.options.handle})),l(this,M,new Yt({onAcquired:()=>{var g;l(this,y,a(this,y).pause()),a(this,V)&&((g=a(this,H))==null||g.abort(cr))},onReleased:()=>{var g;a(this,V)&&((g=this.options.signal)!=null&&g.aborted||p(this,d,gt).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,Ne,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({},(m=t.backoffOptions)!=null?m:Nt),{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=lr(s,n);l(this,Ee,dr(ur(i))),l(this,yt,hr(a(this,Ee))),p(this,d,Cr).call(this)}get shapeHandle(){return a(this,y).handle}get error(){return a(this,Fe)}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,d,gt).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,M).isPaused}async forceDisconnectAndRefresh(){z(this,re)._++,l(this,ve,!0);try{let t=a(this,H);a(this,y).isUpToDate&&t&&!t.signal.aborted&&(a(this,we).add(t),t.abort(ys)),await p(this,d,Fs).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,d,gt).call(this).catch(()=>{});let e=`snapshot-${++z(this,es)._}`;a(this,M).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,St).addSnapshot(n,new Set(i.map(u=>u.key))),await p(this,d,Gt).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:Kt});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,M).release(e)}}async fetchSnapshot(t){return p(this,d,$s).call(this,t,0)}};Fe=new WeakMap,yt=new WeakMap,Ee=new WeakMap,Re=new WeakMap,te=new WeakMap,V=new WeakMap,y=new WeakMap,W=new WeakMap,se=new WeakMap,Ne=new WeakMap,H=new WeakMap,we=new WeakMap,re=new WeakMap,ve=new WeakMap,es=new WeakMap,d=new WeakSet,Qt=function(){return a(this,re)>0},Y=new WeakMap,qe=new WeakMap,$e=new WeakMap,Ve=new WeakMap,je=new WeakMap,St=new WeakMap,M=new WeakMap,q=new WeakMap,bt=new WeakMap,ts=new WeakMap,ss=new WeakMap,rs=new WeakMap,ns=new WeakMap,Et=new WeakMap,ne=new WeakMap,ae=new WeakMap,ie=new WeakMap,$=new WeakMap,We=new WeakMap,Ye=new WeakMap,as=new WeakMap,is=new WeakMap,K=new WeakMap,Rt=new WeakMap,xe=new WeakMap,wt=new WeakMap,Te=new WeakMap,Ae=new WeakMap,oe=new WeakMap,vt=new WeakMap,xt=new WeakMap,gt=async function(){var t,e,s;l(this,V,!0),p(this,d,Mr).call(this);try{await p(this,d,Ie).call(this)}catch(n){if(l(this,Fe,n),n instanceof Error&&l(this,y,a(this,y).toErrorState(n)),a(this,Ne)){let i=await a(this,Ne).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,d,Jt).call(this,n),p(this,d,be).call(this);return}if(l(this,Fe,null),a(this,y)instanceof He&&l(this,y,a(this,y).retry()),l(this,K,0),l(this,$,[]),await p(this,d,Rr).call(this,a(this,oe)),(s=this.options.signal)!=null&&s.aborted){p(this,d,be).call(this);return}return l(this,V,!1),p(this,d,gt).call(this)}n instanceof Error&&p(this,d,Jt).call(this,n),p(this,d,be).call(this);return}throw n instanceof Error&&p(this,d,Jt).call(this,n),p(this,d,be).call(this),n}p(this,d,be).call(this)},be=function(){var t,e;l(this,W,!1),(t=a(this,$e))==null||t.call(this),(e=a(this,ae))==null||e.call(this)},Rr=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,m=()=>{u||(u=!0,clearTimeout(g),c==null||c.removeEventListener("abort",m),h())},g=setTimeout(m,o);c==null||c.addEventListener("abort",m,{once:!0}),c!=null&&c.aborted&&m()})},Ie=async function(t){var m,g,b;if((m=this.options.signal)!=null&&m.aborted){p(this,d,be).call(this);return}if(a(this,y)instanceof He)throw a(this,y).error;let e=t!=null?t:a(this,xe);if(a(this,M).isPaused){e&&l(this,xe,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,d,wr).call(this);let s=!1;a(this,y)instanceof ft&&(s=!0,l(this,y,a(this,y).resume()));let{url:n,signal:i}=this.options,{fetchUrl:o,requestHeaders:c}=await p(this,d,zt).call(this,n,s);e&&(o.searchParams.set(fe,e),o.searchParams.sort());let h=await p(this,d,vr).call(this,i),u=a(this,H);if(a(this,M).isPaused){h&&i&&i.removeEventListener("abort",h),e&&l(this,xe,e),l(this,H,void 0);return}l(this,xe,void 0);try{await p(this,d,xr).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,d,Ie).call(this);if(S instanceof O)return;if(S instanceof he)return p(this,d,Ie).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 U=Kt();return p(this,d,Zt).call(this,P),await p(this,d,Ns).call(this,[{headers:{control:"must-refetch"}}]),p(this,d,Ie).call(this,U)}else throw S}finally{h&&i&&i.removeEventListener("abort",h),l(this,H,void 0)}return(b=a(this,qe))==null||b.call(this),p(this,d,Ie).call(this)},wr=async function(){let t=Date.now(),e=a(this,y).offset;if(l(this,$,a(this,$).filter(o=>t-o.timestamp<a(this,We))),a(this,$).push({timestamp:t,offset:e}),a(this,$).filter(o=>o.offset===e).length<a(this,Ye))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,Ye)} requests in ${a(this,We)}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,Ye)} requests in ${a(this,We)}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),ct.delete(o)}else X.clear(),ct.clear();p(this,d,Zt).call(this),l(this,$,[]);return}let n=Math.min(a(this,is),a(this,as)*Math.pow(2,a(this,K))),i=Math.floor(Math.random()*n);await new Promise(o=>setTimeout(o,i)),l(this,$,[])},zt=async function(t,e,s){var u,m,g,b,S,v;let[n,i]=await Promise.all([fn(this.options.headers),this.options.params?dn(wn(this.options.params)):void 0]);i&&Ur(i);let o=new URL(t);if(i){if(i.table&&L(o,nr,i.table),i.where&&typeof i.where=="string"){let A=Me(i.where,(u=this.options.columnMapper)==null?void 0:u.encode);L(o,ar,A)}if(i.columns){let A=await js((m=this.options.params)==null?void 0:m.columns);if(Array.isArray(A)){let P=A.map(String);this.options.columnMapper&&(P=P.map(this.options.columnMapper.encode));let U=P.map(Je).join(",");L(o,ps,U)}else L(o,ps,i.columns)}i.replica&&L(o,ir,i.replica),i.params&&L(o,or,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))L(o,A,P)}if(s){if(s.whereExpr){let E=ot(s.whereExpr,(g=this.options.columnMapper)==null?void 0:g.encode);L(o,Ue,E),o.searchParams.set(Rs,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let E=Me(s.where,(b=this.options.columnMapper)==null?void 0:b.encode);L(o,Ue,E)}if(s.params&&o.searchParams.set(nt,Ht(s.params)),s.limit!==void 0&&L(o,st,s.limit),s.offset!==void 0&&L(o,rt,s.offset),s.orderByExpr){let E=qt(s.orderByExpr,(S=this.options.columnMapper)==null?void 0:S.encode);L(o,Oe,E),o.searchParams.set(ws,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let E=Me(s.orderBy,(v=this.options.columnMapper)==null?void 0:v.encode);L(o,Oe,E)}}a(this,y).applyUrlParams(o,{isSnapshotRequest:s!==void 0,canLongPoll:!a(this,d,Qt)&&!e}),o.searchParams.set(Es,a(this,se));let c=Se(o),h=X.getExpiredHandle(c);return h&&o.searchParams.set(tt,h),o.searchParams.sort(),{fetchUrl:o,requestHeaders:n}},vr=async function(t){var e;if(l(this,H,new AbortController),t){let s=()=>{var n;(n=a(this,H))==null||n.abort(t.reason)};return t.addEventListener("abort",s,{once:!0}),t.aborted&&((e=a(this,H))==null||e.abort(t.reason)),s}},Is=async function(t){var h,u,m;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,Ae)){let{shapeKey:g,staleHandle:b}=a(this,Ae);l(this,Ae,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(ke),responseCursor:e.get(It),responseSchema:Er(e),expiredHandle:o,now:Date.now(),maxStaleCacheRetries:a(this,ie),createCacheBuster:Kt});if(l(this,y,c.state),s===204&&l(this,Te,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,Te)!==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,Te,i),n&&l(this,Ae,{shapeKey:i,staleHandle:n}),p(this,d,Zt).call(this),new he("Expired handle entry evicted for self-healing retry")):new w(502,void 0,void 0,{},(m=(u=a(this,q))==null?void 0:u.toString())!=null?m:"",`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},Gt=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=ds(n),o=i?tr(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));ct.recordUpToDate(u,a(this,y).liveCacheBuster),l(this,Te,null)}}let h=t.filter(u=>Xe(u)?!a(this,St).shouldRejectMessage(u):!0);await p(this,d,Ns).call(this,h,{allowReentrantBypass:s.allowReentrantPublishBypass})},xr=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=ct.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,d,Qt),resumingFromPause:!!t.resumingFromPause})?(t.fetchUrl.searchParams.set(ms,"true"),t.fetchUrl.searchParams.set(gs,"true"),p(this,d,Pr).call(this,t)):p(this,d,Ar).call(this,t)},Tr=async function(t,e,s){let n=a(this,Et),i=s.searchParams.get(I)==="true",o=a(this,d,Qt)||a(this,ve);if(n===!1||!i&&!o)return t;let c,h=new Promise((u,m)=>{c=setTimeout(()=>{e.signal.aborted||(a(this,we).add(e),e.abort(bs)),m(new O)},n)});try{return await Promise.race([t,h])}finally{c&&clearTimeout(c)}},Ar=async function(t){var S;let{fetchUrl:e,requestAbortController:s,headers:n}=t,i=e.toString(),o=await p(this,d,Tr).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,d,Is).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=Ht(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,d,Gt).call(this,b)},Pr=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,d,Is).call(this,u))throw c=!0,new Error("stale response ignored")},onmessage:u=>{if(u.data){let m=a(this,y).schema,g=a(this,Re).parse(u.data,m);h.push(g),ds(g)&&(p(this,d,Gt).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,m=a(this,y).handleSseConnectionClosed({connectionDuration:h,wasAborted:u,minConnectionDuration:a(this,ts),maxShortConnections:a(this,ss)});if(l(this,y,m.state),m.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(m.wasShortConnection){let g=Math.min(a(this,ns),a(this,rs)*Math.pow(2,a(this,y).consecutiveShortSseConnections)),b=Math.floor(Math.random()*g);await new Promise(S=>setTimeout(S,b))}}},Fs=async function(){if(a(this,M).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,qe,t),l(this,$e,e)})),a(this,Y).finally(()=>{l(this,Y,void 0),l(this,qe,void 0),l(this,$e,void 0)}).catch(()=>{}),a(this,Y))},Ns=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,je)&&e.allowReentrantBypass?s():(l(this,Ve,a(this,Ve).then(async()=>{l(this,je,!0);try{return await s()}finally{l(this,je,!1)}})),a(this,Ve))},Jt=function(t){a(this,te).forEach(([e,s])=>{s==null||s(t)})},qs=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},Xt=function(t){t?a(this,M).acquire("visibility"):a(this,M).isHeldBy("visibility")&&a(this,M).release("visibility")},Cr=function(){var e,s;let t=(e=this.options.runtimeVisibility)!=null?e:yn();if(t){p(this,d,Xt).call(this,((s=t.getCurrentState)==null?void 0:s.call(t))==="hidden");let n=t.subscribe(i=>{p(this,d,Xt).call(this,i==="hidden")});l(this,ne,()=>{n(),l(this,ne,void 0)});return}if(p(this,d,qs).call(this)){let n=()=>{p(this,d,Xt).call(