@electric-sql/client
Version:
Postgres everywhere - your data, in sync, wherever you need it.
10 lines • 56.3 kB
JavaScript
var _r=Object.defineProperty,Mr=Object.defineProperties;var kr=Object.getOwnPropertyDescriptors;var Tt=Object.getOwnPropertySymbols;var $s=Object.prototype.hasOwnProperty,qs=Object.prototype.propertyIsEnumerable;var js=n=>{throw TypeError(n)};var Ns=(n,t,e)=>t in n?_r(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,E=(n,t)=>{for(var e in t||(t={}))$s.call(t,e)&&Ns(n,e,t[e]);if(Tt)for(var e of Tt(t))qs.call(t,e)&&Ns(n,e,t[e]);return n},_=(n,t)=>Mr(n,kr(t));var ze=(n,t)=>{var e={};for(var s in n)$s.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&Tt)for(var s of Tt(n))t.indexOf(s)<0&&qs.call(n,s)&&(e[s]=n[s]);return e};var ns=(n,t,e)=>t.has(n)||js("Cannot "+e);var r=(n,t,e)=>(ns(n,t,"read from private field"),e?e.call(n):t.get(n)),f=(n,t,e)=>t.has(n)?js("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),l=(n,t,e,s)=>(ns(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),p=(n,t,e)=>(ns(n,t,"access private method"),e);var z=(n,t,e,s)=>({set _(a){l(n,t,a,e)},get _(){return r(n,t,s)}});var x=class n extends Error{constructor(e,s,a,o,i,c){super(c||`HTTP Error ${e} at ${i}: ${s!=null?s:JSON.stringify(a)}`);this.url=i;this.name="FetchError",this.status=e,this.text=s,this.json=a,this.headers=o}static async fromResponse(e,s){let a=e.status,o=Object.fromEntries([...e.headers.entries()]),i,c,h=e.headers.get("content-type");return e.bodyUsed||(h&&h.includes("application/json")?c=await e.json():i=await e.text()),new n(a,i,c,o,s)}},$=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var At=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Ct=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Pt=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},_t=class extends Error{constructor(t){super(`Cannot use reserved Electric parameter names in custom params: ${t.join(", ")}`),this.name="ReservedParamError"}},Mt=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(a=>{s+=`- ${a}
`}),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)}},le=class extends Error{constructor(t){super(t),this.name="StaleCacheError"}};var kt=n=>Number(n),Ur=n=>n==="true"||n==="t",Or=n=>BigInt(n),Ws=n=>JSON.parse(n),Lr=n=>n,Dr={int2:kt,int4:kt,int8:Or,bool:Ur,float4:kt,float8:kt,json:Ws,jsonb:Ws};function Br(n,t){let e=0,s=null,a="",o=!1,i=0,c;function h(d,S,b){let y=d.slice(S,b);return y=y==="NULL"?null:y,t?t(y):y}function u(d){let S=[];for(;e<d.length;e++){if(s=d[e],o)s==="\\"?a+=d[++e]:s==='"'?(S.push(t?t(a):a),a="",o=d[e+1]==='"',i=e+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++e,S.push(u(d));else if(s==="}"){o=!1,i<e&&S.push(h(d,i,e)),i=e+1;break}else s===","&&c!=="}"&&c!=='"'&&(S.push(h(d,i,e)),i=e+1);c=s}return i<e&&S.push(S.push(h(d,i,e+1))),S}return u(n)[0]}var Ut=class{constructor(t,e){this.parser=E(E({},Dr),t),this.transformer=e}parse(t,e){return JSON.parse(t,(s,a)=>(s==="value"||s==="old_value")&&typeof a=="object"&&a!==null?this.transformMessageValue(a,e):a)}parseSnapshotData(t,e){return t.map(s=>{let a=s;return a.value&&typeof a.value=="object"&&a.value!==null&&(a.value=this.transformMessageValue(a.value,e)),a.old_value&&typeof a.old_value=="object"&&a.old_value!==null&&(a.old_value=this.transformMessageValue(a.old_value,e)),a})}transformMessageValue(t,e){let s=t;return Object.keys(s).forEach(a=>{s[a]=this.parseRow(a,s[a],e)}),this.transformer?this.transformer(s):s}parseRow(t,e,s){var S;let a=s[t];if(!a)return e;let d=a,{type:o,dims:i}=d,c=ze(d,["type","dims"]),h=(S=this.parser[o])!=null?S:Lr,u=Ys(h,a,t);return i&&i>0?Ys((y,R)=>Br(y,u),a,t)(e):u(e,c)}};function Ys(n,t,e){var a;let s=!((a=t.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new Mt(e!=null?e:"unknown");return null}return n(o,t)}}function Ge(n){return`"${n.replace(/"/g,'""')}"`}function as(n){var c,h,u,d;let t=(h=(c=n.match(/^_+/))==null?void 0:c[0])!=null?h:"",e=n.slice(t.length),s=(d=(u=e.match(/_+$/))==null?void 0:u[0])!=null?d:"",i=(s?e.slice(0,e.length-s.length):e).toLowerCase().replace(/_+([a-z])/g,(S,b)=>"_".repeat(S.length-2)+b.toUpperCase());return t+i+s}function Vs(n){return n.replace(/([a-z_])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ks(n){let t={};for(let[e,s]of Object.entries(n))t[s]=e;return{decode:e=>{var s;return(s=n[e])!=null?s:e},encode:e=>{var s;return(s=t[e])!=null?s:e}}}function Te(n,t){if(!n||!t)return n!=null?n:"";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=[],a=0;for(;a<n.length;){let c=n[a];if(c==="'"||c==='"'){let h=a,u=c;for(a++;a<n.length;)if(n[a]===u)if(n[a+1]===u)a+=2;else{a++;break}else a++;s.push({start:h,end:a})}else a++}let o=c=>s.some(h=>c>=h.start&&c<h.end),i=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return n.replace(i,(c,h,u)=>o(u)||e.has(c.toUpperCase())||c.startsWith("$")?c:t(c))}function Hr(n){if(n){let t={};for(let e of Object.keys(n))t[e]=as(e);return Ks(t)}return{decode:t=>as(t),encode:t=>Vs(t)}}function Je(n){return n!=null&&"key"in n}function Ot(n){return n!=null&&"headers"in n&&"control"in n.headers}function is(n){return Ot(n)&&n.headers.control==="up-to-date"}function Qs(n){if(n.headers.control!="up-to-date")return;let t=n.headers.global_last_seen_lsn;return t?`${t}_0`:void 0}function Ir(n,t){return typeof t=="bigint"?t.toString():t}function Lt(n){return JSON.stringify(n,Ir)}function zs(n){return JSON.stringify(os(n))}function os(n){if(typeof n=="bigint")return n.toString();if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(os);let t={};for(let e of Object.keys(n).sort())t[e]=os(n[e]);return t}function cs(n,t){let e=BigInt(n),s=BigInt(t.xmin),a=BigInt(t.xmax),o=t.xip_list.map(BigInt);return e<s||e<a&&!o.includes(e)}var Dt="electric-cursor",J="electric-handle",Ae="electric-offset",Xe="electric-schema",Gs="electric-up-to-date",ls="columns",Ze="cursor",et="expired_handle",he="handle",q="live",de="offset",Js="table",Xs="where",Zs="replica",er="params",hs="experimental_live_sse",ds="live_sse",us="force-disconnect-and-refresh",tr="pause-stream",fs="system-wake",ps="log",Ce="subset__where",tt="subset__limit",st="subset__offset",Pe="subset__order_by",rt="subset__params",ms="subset__where_expr",gs="subset__order_by_expr",ue="cache-buster",Ss=[q,ds,hs,he,de,Ze,et,ps,Ce,tt,st,Pe,rt,ms,gs,ue];var Fr=[429],Ht={initialDelay:1e3,maxDelay:32e3,multiplier:2,maxRetries:1/0};function Nr(n){if(!n)return 0;let t=Number(n);if(Number.isFinite(t)&&t>0)return t*1e3;let e=Date.parse(n);if(!isNaN(e)){let s=e-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function sr(n,t=Ht){let{initialDelay:e,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:c=1/0}=t;return async(...h)=>{var y;let u=h[0],d=h[1],S=e,b=0;for(;;)try{let R=await n(...h);if(R.ok)return R;throw await x.fromResponse(R,u.toString())}catch(R){if(i==null||i(),(y=d==null?void 0:d.signal)!=null&&y.aborted)throw new $;if(R instanceof x&&!Fr.includes(R.status)&&R.status>=400&&R.status<500)throw R;{if(b++,b>c)throw o&&console.log(`Max retries reached (${b}/${c}), giving up`),R;let w=R instanceof x&&R.headers?Nr(R.headers["retry-after"]):0,P=Math.random()*S,A=Math.min(P,s),k=Math.max(w,A);if(o){let C=w>0?"server+client":"client";console.log(`Retry attempt #${b} after ${k}ms (${C}, serverMin=${w}ms, clientBackoff=${A}ms)`)}await new Promise(C=>setTimeout(C,k)),S=Math.min(S*a,s)}}}}var $r=[201,204,205];function rr(n){return async(...t)=>{var a,o;let e=t[0],s=await n(...t);try{if(s.status<200||$r.includes(s.status))return s;let i=await s.text();return new Response(i,s)}catch(i){throw(o=(a=t[1])==null?void 0:a.signal)!=null&&o.aborted?new $:new x(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}}}var qr={maxChunksToPrefetch:2};function nr(n,t=qr){let{maxChunksToPrefetch:e}=t,s;return async(...o)=>{let i=o[0].toString();if(Qr(o[0],o[1])!=="GET")return s==null||s.abort(),s=void 0,n(...o);let h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort(),s=void 0;let u=await n(...o),d=Es(i,u);return d&&(s=new ys({fetchClient:n,maxPrefetchedRequests:e,url:d,requestInit:o[1]})),u}}var jr=[Ae,J],Wr=[Dt],Yr=[Xe];function ar(n){return async(...t)=>{let e=await n(...t);if(e.ok){let s=e.headers,a=[],o=d=>a.push(...d.filter(S=>!s.has(S))),c=t[0].toString(),h=new URL(c);if([Ce,rt,tt,st,Pe].some(d=>h.searchParams.has(d)))return e;if(o(jr),h.searchParams.get(q)==="true"&&o(Wr),(!h.searchParams.has(q)||h.searchParams.get(q)==="false")&&o(Yr),a.length>0)throw new G(c,a)}return e}}var nt,at,H,fe,W,_e,Bt,ys=class{constructor(t){f(this,_e);f(this,nt);f(this,at);f(this,H,new Map);f(this,fe);f(this,W);var e;l(this,nt,(e=t.fetchClient)!=null?e:(...s)=>fetch(...s)),l(this,at,t.maxPrefetchedRequests),l(this,fe,t.url.toString()),l(this,W,r(this,fe)),p(this,_e,Bt).call(this,t.url,t.requestInit)}abort(){r(this,H).forEach(([t,e])=>e.abort()),r(this,H).clear()}consume(...t){let e=t[0].toString(),s=r(this,H).get(e);if(!s||e!==r(this,fe))return;let[a,o]=s;if(o.signal.aborted){r(this,H).delete(e);return}return r(this,H).delete(e),a.then(i=>{let c=Es(e,i);l(this,fe,c),r(this,W)&&!r(this,H).has(r(this,W))&&p(this,_e,Bt).call(this,r(this,W),t[1])}).catch(()=>{}),a}};nt=new WeakMap,at=new WeakMap,H=new WeakMap,fe=new WeakMap,W=new WeakMap,_e=new WeakSet,Bt=function(...t){var a,o;let e=t[0].toString();if(r(this,H).size>=r(this,at))return;let s=new AbortController;try{let{signal:i,cleanup:c}=Vr(s,(a=t[1])==null?void 0:a.signal),h=r(this,nt).call(this,e,_(E({},(o=t[1])!=null?o:{}),{signal:i}));r(this,H).set(e,[h,s]),h.then(u=>{if(!u.ok||s.signal.aborted)return;let d=Es(e,u);if(!d||d===e){l(this,W,void 0);return}return l(this,W,d),p(this,_e,Bt).call(this,d,t[1])}).catch(()=>{}).finally(c)}catch(i){}};function Es(n,t){let e=t.headers.get(J),s=t.headers.get(Ae),a=t.headers.has(Gs);if(!e||!s||a)return;let o=new URL(n);if(o.searchParams.has(q))return;let i=o.searchParams.get(et);if(i&&e===i){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 o.searchParams.set(he,e),o.searchParams.set(de,s),o.searchParams.sort(),o.toString()}function Vr(n,t){let e=Kr;if(t)if(t.aborted)n.abort();else{let s=()=>n.abort();t.addEventListener("abort",s,{once:!0,signal:n.signal}),e=()=>t.removeEventListener("abort",s)}return{signal:n.signal,cleanup:e}}function Kr(){}function Qr(n,t){return t!=null&&t.method?t.method.toUpperCase():typeof Request!="undefined"&&n instanceof Request?n.method.toUpperCase():"GET"}function ot(n,t){switch(n.type){case"ref":{let e=t?t(n.column):n.column;return Ge(e)}case"val":return`$${n.paramIndex}`;case"func":return zr(n,t);default:{let e=n;throw new Error(`Unknown expression type: ${JSON.stringify(e)}`)}}}function zr(n,t){let e=n.args.map(s=>ot(s,t));switch(n.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: ${n.name}`)}}function It(n,t){return n.map(e=>{let s=t?t(e.column):e.column,a=Ge(s);return e.direction==="desc"&&(a+=" DESC"),e.nulls==="first"&&(a+=" NULLS FIRST"),e.nulls==="last"&&(a+=" NULLS LAST"),a}).join(", ")}async function ir(n,t){let e=n.getReader(),s;for(;!(s=await e.read()).done;)t(s.value)}function cr(n){let t,e,s,a=!1;return function(i){t===void 0?(t=i,e=0,s=-1):t=Gr(t,i);let c=t.length,h=0;for(;e<c;){a&&(t[e]===10&&(h=++e),a=!1);let u=-1;for(;e<c&&u===-1;++e)switch(t[e]){case 58:s===-1&&(s=e-h);break;case 13:a=!0;case 10:u=e;break}if(u===-1)break;n(t.subarray(h,u),s),h=e,s=-1}h===c?t=void 0:h!==0&&(t=t.subarray(h),e-=h)}}function lr(n,t,e){let s=or(),a=new TextDecoder;return function(i,c){if(i.length===0)e==null||e(s),s=or();else if(c>0){let h=a.decode(i.subarray(0,c)),u=c+(i[c+1]===32?2:1),d=a.decode(i.subarray(u));switch(h){case"data":s.data=s.data?s.data+`
`+d:d;break;case"event":s.event=d;break;case"id":n(s.id=d);break;case"retry":let S=parseInt(d,10);isNaN(S)||t(s.retry=S);break}}}}function Gr(n,t){let e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function or(){return{data:"",event:"",id:"",retry:void 0}}var Jr=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,s=Object.getOwnPropertySymbols(n);a<s.length;a++)t.indexOf(s[a])<0&&Object.prototype.propertyIsEnumerable.call(n,s[a])&&(e[s[a]]=n[s[a]]);return e},Ft="text/event-stream",Xr=1e3,hr="last-event-id";function bs(n,t){var{signal:e,headers:s,onopen:a,onmessage:o,onclose:i,onerror:c,openWhenHidden:h,fetch:u}=t,d=Jr(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((S,b)=>{let y=Object.assign({},s);y.accept||(y.accept=Ft);let R;function w(){R.abort(),typeof document!="undefined"&&!document.hidden&&ve()}typeof document!="undefined"&&!h&&document.addEventListener("visibilitychange",w);let P=Xr,A=0;function k(){typeof document!="undefined"&&document.removeEventListener("visibilitychange",w),clearTimeout(A),R.abort()}e==null||e.addEventListener("abort",()=>{k()});let C=u!=null?u:window.fetch,xt=a!=null?a:Zr;async function ve(){var Ke;R=new AbortController;let vt=e.aborted?e:R.signal;try{let Qe=await C(n,Object.assign(Object.assign({},d),{headers:y,signal:vt}));await xt(Qe),await ir(Qe.body,cr(lr(Q=>{Q?y[hr]=Q:delete y[hr]},Q=>{P=Q},o))),i==null||i(),k(),S()}catch(Qe){if(vt.aborted)k(),b(Qe);else if(!R.signal.aborted)try{let Q=(Ke=c==null?void 0:c(Qe))!==null&&Ke!==void 0?Ke:P;clearTimeout(A),A=setTimeout(ve,Q)}catch(Q){k(),b(Q)}}}ve()})}function Zr(n){let t=n.headers.get("content-type");if(!(t!=null&&t.startsWith(Ft)))throw new Error(`Expected content-type to be ${Ft}, Actual: ${t}`)}var Rs=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 a=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[a]}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 Rs;var ws=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 a=s.reduce((o,i)=>this.data[i].timestamp<this.data[o].timestamp?i:o);delete this.data[a]}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 a of e)t-this.data[a].timestamp>this.cacheTTL&&(delete this.data[a],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()}},it=new ws;var I,xs,vs,Ts,Nt=class{constructor(){f(this,I);this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(t,e){p(this,I,xs).call(this,t.snapshot_mark);let s=BigInt(t.xmax),a=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:a}),p(this,I,vs).call(this,this.xmaxSnapshots,s,t.snapshot_mark),p(this,I,vs).call(this,this.snapshotsByDatabaseLsn,a,t.snapshot_mark)}removeSnapshot(t){p(this,I,xs).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[a,o]of this.xmaxSnapshots.entries())if(s>=a)for(let i of o)this.removeSnapshot(i);return[...this.activeSnapshots.values()].some(a=>a.keys.has(t.key)&&cs(s,a))}lastSeenUpdate(t){for(let[e,s]of this.snapshotsByDatabaseLsn.entries())if(e<=t)for(let a of s)this.removeSnapshot(a)}};I=new WeakSet,xs=function(t){let e=this.activeSnapshots.get(t);e&&(p(this,I,Ts).call(this,this.xmaxSnapshots,e.xmax,t),p(this,I,Ts).call(this,this.snapshotsByDatabaseLsn,e.databaseLsn,t))},vs=function(t,e,s){let a=t.get(e);a?a.add(s):t.set(e,new Set([s]))},Ts=function(t,e,s){let a=t.get(e);a&&(a.delete(s),a.size===0&&t.delete(e))};var ct=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 ut(this)}toErrorState(t){return new Ue(this,t)}markMustRefetch(t){return new $t({handle:t,offset:"-1",liveCacheBuster:"",lastSyncedAt:this.lastSyncedAt,schema:void 0})}},v,lt=class extends ct{constructor(e){super();f(this,v);l(this,v,e)}get handle(){return r(this,v).handle}get offset(){return r(this,v).offset}get schema(){return r(this,v).schema}get liveCacheBuster(){return r(this,v).liveCacheBuster}get lastSyncedAt(){return r(this,v).lastSyncedAt}get currentFields(){return r(this,v)}applyUrlParams(e,s){e.searchParams.set(de,r(this,v).offset),r(this,v).handle&&e.searchParams.set(he,r(this,v).handle)}parseResponseFields(e){var u,d,S;let s=e.responseHandle,a=s&&s!==e.expiredHandle?s:r(this,v).handle,o=(u=e.responseOffset)!=null?u:r(this,v).offset,i=(d=e.responseCursor)!=null?d:r(this,v).liveCacheBuster,c=(S=r(this,v).schema)!=null?S:e.responseSchema,h=e.status===204?e.now:r(this,v).lastSyncedAt;return{handle:a,offset:o,schema:c,liveCacheBuster:i,lastSyncedAt:h}}checkStaleResponse(e){let s=e.responseHandle,a=e.expiredHandle;if(!s||s!==a)return null;let o=this.staleCacheRetryCount+1;return{action:"stale-retry",state:new Cs(_(E({},this.currentFields),{staleCacheBuster:e.createCacheBuster(),staleCacheRetryCount:o})),exceededMaxRetries:o>e.maxStaleCacheRetries}}handleMessageBatch(e){if(!e.hasMessages||!e.hasUpToDateMessage)return{state:this,suppressBatch:!1,becameUpToDate:!1};let s=r(this,v).offset;e.isSse&&e.upToDateOffset&&(s=e.upToDateOffset);let a={handle:r(this,v).handle,offset:s,schema:r(this,v).schema,liveCacheBuster:r(this,v).liveCacheBuster,lastSyncedAt:e.now};return this.onUpToDate(a,e)}onUpToDate(e,s){return{state:new dt(e),suppressBatch:!1,becameUpToDate:!0}}};v=new WeakMap;var ht=class extends lt{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 As(s)}}canEnterReplayMode(){return!0}enterReplayMode(t){return new Ps(_(E({},this.currentFields),{replayCursor:t}))}},$t=class n extends ht{constructor(e){super(e);this.kind="initial"}withHandle(e){return new n(_(E({},this.currentFields),{handle:e}))}},As=class n extends ht{constructor(e){super(e);this.kind="syncing"}withHandle(e){return new n(_(E({},this.currentFields),{handle:e}))}},pe,ke,_s=class _s extends ht{constructor(e){let i=e,{staleCacheBuster:s,staleCacheRetryCount:a}=i,o=ze(i,["staleCacheBuster","staleCacheRetryCount"]);super(o);this.kind="stale-retry";f(this,pe);f(this,ke);l(this,pe,s),l(this,ke,a)}get staleCacheBuster(){return r(this,pe)}get staleCacheRetryCount(){return r(this,ke)}canEnterReplayMode(){return!1}withHandle(e){return new _s(_(E({},this.currentFields),{handle:e,staleCacheBuster:r(this,pe),staleCacheRetryCount:r(this,ke)}))}applyUrlParams(e,s){super.applyUrlParams(e,s),e.searchParams.set(ue,r(this,pe))}};pe=new WeakMap,ke=new WeakMap;var Cs=_s,me,Z,Me=class Me extends lt{constructor(e,s){var a,o;super(e);this.kind="live";f(this,me);f(this,Z);l(this,me,(a=s==null?void 0:s.consecutiveShortSseConnections)!=null?a:0),l(this,Z,(o=s==null?void 0:s.sseFallbackToLongPolling)!=null?o:!1)}get isUpToDate(){return!0}get consecutiveShortSseConnections(){return r(this,me)}get sseFallbackToLongPolling(){return r(this,Z)}withHandle(e){return new Me(_(E({},this.currentFields),{handle:e}),this.sseState)}applyUrlParams(e,s){super.applyUrlParams(e,s),s.isSnapshotRequest||(e.searchParams.set(Ze,this.liveCacheBuster),s.canLongPoll&&e.searchParams.set(q,"true"))}get sseState(){return{consecutiveShortSseConnections:r(this,me),sseFallbackToLongPolling:r(this,Z)}}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new Me(a,this.sseState)}}onUpToDate(e,s){return{state:new Me(e,this.sseState),suppressBatch:!1,becameUpToDate:!0}}shouldUseSse(e){return e.liveSseEnabled&&!e.isRefreshing&&!e.resumingFromPause&&!r(this,Z)}handleSseConnectionClosed(e){let s=r(this,me),a=r(this,Z),o=!1,i=!1;return e.connectionDuration<e.minConnectionDuration&&!e.wasAborted?(i=!0,s=s+1,s>=e.maxShortConnections&&(a=!0,o=!0)):e.connectionDuration>=e.minConnectionDuration&&(s=0),{state:new Me(this.currentFields,{consecutiveShortSseConnections:s,sseFallbackToLongPolling:a}),fellBackToLongPolling:o,wasShortConnection:i}}};me=new WeakMap,Z=new WeakMap;var dt=Me,ee,qt=class qt extends lt{constructor(e){let o=e,{replayCursor:s}=o,a=ze(o,["replayCursor"]);super(a);this.kind="replaying";f(this,ee);l(this,ee,s)}get replayCursor(){return r(this,ee)}withHandle(e){return new qt(_(E({},this.currentFields),{handle:e,replayCursor:r(this,ee)}))}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new qt(_(E({},a),{replayCursor:r(this,ee)}))}}onUpToDate(e,s){let a=!s.isSse&&r(this,ee)===s.currentCursor;return{state:new dt(e),suppressBatch:a,becameUpToDate:!0}}};ee=new WeakMap;var Ps=qt,ut=class n extends ct{constructor(e){super();this.kind="paused";this.previousState=e instanceof n?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 n(s.state)};if(s.action==="ignored")return{action:"ignored",state:this};if(s.action==="stale-retry")return{action:"stale-retry",state:new n(s.state),exceededMaxRetries:s.exceededMaxRetries};let a=s;throw new Error(`PausedState.handleResponseMetadata: unhandled transition action "${a.action}"`)}withHandle(e){return new n(this.previousState.withHandle(e))}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}pause(){return this}resume(){return this.previousState}},Ue=class n extends ct{constructor(e,s){super();this.kind="error";this.previousState=e instanceof n?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 n(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 dr(n){return new $t({handle:n.handle,offset:n.offset,liveCacheBuster:"",lastSyncedAt:void 0,schema:void 0})}var D,ft,pt,jt=class{constructor(t){f(this,D,new Set);f(this,ft);f(this,pt);l(this,ft,t.onAcquired),l(this,pt,t.onReleased)}acquire(t){if(r(this,D).has(t)){console.warn(`[Electric] PauseLock: "${t}" already held \u2014 ignoring duplicate acquire`);return}let e=r(this,D).size===0;r(this,D).add(t),e&&r(this,ft).call(this)}release(t){if(!r(this,D).delete(t)){console.warn(`[Electric] PauseLock: "${t}" not held \u2014 ignoring release (possible acquire/release mismatch)`);return}r(this,D).size===0&&r(this,pt).call(this)}get isPaused(){return r(this,D).size>0}isHeldBy(t){return r(this,D).has(t)}releaseAllMatching(t){for(let e of r(this,D))e.startsWith(t)&&r(this,D).delete(e)}};D=new WeakMap,ft=new WeakMap,pt=new WeakMap;var en=new Set([Ze,he,q,de,ue]),ge="https://electric-sql.com/docs/guides/troubleshooting";function Wt(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async function Hs(n){return typeof n=="function"?n():n}async function tn(n){let t=Object.entries(n),e=await Promise.all(t.map(async([s,a])=>{if(a===void 0)return[s,void 0];let o=await Hs(a);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(e.filter(([s,a])=>a!==void 0))}async function sn(n){if(!n)return{};let t=Object.entries(n),e=await Promise.all(t.map(async([s,a])=>[s,await Hs(a)]));return Object.fromEntries(e)}function Se(n){let t=new URL(n.origin+n.pathname);for(let[e,s]of n.searchParams)Ss.includes(e)||t.searchParams.append(e,s);return t.searchParams.sort(),t.toString()}var Le,De,Be,Ee,te,j,g,Y,se,He,B,Ie,re,zt,m,ks,V,Fe,Ne,$e,qe,gt,U,F,St,Gt,Jt,Xt,Zt,je,ne,ae,N,We,Ye,es,ts,K,yt,be,Et,Re,we,oe,bt,Rt,mt,ye,fr,Oe,pr,Yt,mr,Us,Vt,gr,Sr,yr,Er,Os,Kt,Ls,br,Rr,Qt,Ds,wr,Ms=class{constructor(t){f(this,m);f(this,Le,null);f(this,De);f(this,Be);f(this,Ee);f(this,te,new Map);f(this,j,!1);f(this,g);f(this,Y,!1);f(this,se);f(this,He);f(this,B);f(this,Ie,new WeakSet);f(this,re,0);f(this,zt,0);f(this,V);f(this,Fe);f(this,Ne);f(this,$e,Promise.resolve([]));f(this,qe,!1);f(this,gt,new Nt);f(this,U);f(this,F);f(this,St);f(this,Gt,1e3);f(this,Jt,3);f(this,Xt,100);f(this,Zt,5e3);f(this,je);f(this,ne);f(this,ae,3);f(this,N,[]);f(this,We,500);f(this,Ye,5);f(this,es,100);f(this,ts,5e3);f(this,K,0);f(this,yt,5);f(this,be);f(this,Et,5);f(this,Re,null);f(this,we,null);f(this,oe,0);f(this,bt,50);f(this,Rt);var i,c,h,u;this.options=E({subscribe:!0},t),on(this.options),l(this,g,dr({offset:(i=this.options.offset)!=null?i:"-1",handle:this.options.handle})),l(this,U,new jt({onAcquired:()=>{var d;l(this,g,r(this,g).pause()),r(this,j)&&((d=r(this,B))==null||d.abort(tr))},onReleased:()=>{var d;r(this,j)&&((d=this.options.signal)!=null&&d.aborted||p(this,m,mt).call(this).catch(()=>{}))}}));let e;if(t.columnMapper){let d=S=>{let b={};for(let[y,R]of Object.entries(S)){let w=t.columnMapper.decode(y);b[w]=R}return b};e=t.transformer?S=>t.transformer(d(S)):d}else e=t.transformer;l(this,Ee,new Ut(t.parser,e)),l(this,He,this.options.onError),l(this,se,(c=this.options.log)!=null?c:"full");let s=(h=t.fetchClient)!=null?h:(...d)=>fetch(...d),a=_(E({},(u=t.backoffOptions)!=null?u:Ht),{onFailedAttempt:()=>{var d,S;l(this,Y,!1),(S=(d=t.backoffOptions)==null?void 0:d.onFailedAttempt)==null||S.call(d)}});l(this,Rt,{initialDelay:a.initialDelay,maxDelay:a.maxDelay,multiplier:a.multiplier});let o=sr(s,a);l(this,Be,ar(nr(o))),l(this,De,rr(r(this,Be))),p(this,m,br).call(this)}get shapeHandle(){return r(this,g).handle}get error(){return r(this,Le)}get isUpToDate(){return r(this,g).isUpToDate}get lastOffset(){return r(this,g).offset}get mode(){return r(this,se)}subscribe(t,e=()=>{}){let s={};return r(this,te).set(s,[t,e]),r(this,j)||p(this,m,mt).call(this),()=>{r(this,te).delete(s)}}unsubscribeAll(){var t,e;r(this,te).clear(),(t=r(this,je))==null||t.call(this),(e=r(this,ne))==null||e.call(this)}lastSyncedAt(){return r(this,g).lastSyncedAt}lastSynced(){return r(this,g).lastSyncedAt===void 0?1/0:Date.now()-r(this,g).lastSyncedAt}isConnected(){return r(this,Y)}isLoading(){return!r(this,g).isUpToDate}hasStarted(){return r(this,j)}isPaused(){return r(this,U).isPaused}async forceDisconnectAndRefresh(){z(this,re)._++;try{let t=r(this,B);r(this,g).isUpToDate&&t&&!t.signal.aborted&&(r(this,Ie).add(t),t.abort(us)),await p(this,m,Er).call(this)}finally{z(this,re)._--}}async requestSnapshot(t){if(r(this,se)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,se)} mode, as the consumer is guaranteed to observe all data`);r(this,j)||p(this,m,mt).call(this).catch(()=>{});let e=`snapshot-${++z(this,zt)._}`;r(this,U).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:a,data:o,responseOffset:i,responseHandle:c}=await this.fetchSnapshot(t),h=o.concat([{headers:E({control:"snapshot-end"},a)},{headers:E({control:"subset-end"},t)}]);if(r(this,gt).addSnapshot(a,new Set(o.map(u=>u.key))),await p(this,m,Vt).call(this,h,!1,{allowReentrantPublishBypass:!0}),i!==null||c!==null){let u=r(this,g).handleResponseMetadata({status:200,responseHandle:c,responseOffset:i,responseCursor:null,expiredHandle:null,now:Date.now(),maxStaleCacheRetries:r(this,ae),createCacheBuster:Wt});u.action==="accepted"?l(this,g,u.state):console.warn(`[Electric] Snapshot response metadata was not accepted by state "${r(this,g).kind}" (action: ${u.action}). Stream offset was not advanced from snapshot.`,new Error("stack trace"))}return{metadata:a,data:o}}finally{clearTimeout(s),r(this,U).release(e)}}async fetchSnapshot(t){return p(this,m,Ds).call(this,t,0)}};Le=new WeakMap,De=new WeakMap,Be=new WeakMap,Ee=new WeakMap,te=new WeakMap,j=new WeakMap,g=new WeakMap,Y=new WeakMap,se=new WeakMap,He=new WeakMap,B=new WeakMap,Ie=new WeakMap,re=new WeakMap,zt=new WeakMap,m=new WeakSet,ks=function(){return r(this,re)>0},V=new WeakMap,Fe=new WeakMap,Ne=new WeakMap,$e=new WeakMap,qe=new WeakMap,gt=new WeakMap,U=new WeakMap,F=new WeakMap,St=new WeakMap,Gt=new WeakMap,Jt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,je=new WeakMap,ne=new WeakMap,ae=new WeakMap,N=new WeakMap,We=new WeakMap,Ye=new WeakMap,es=new WeakMap,ts=new WeakMap,K=new WeakMap,yt=new WeakMap,be=new WeakMap,Et=new WeakMap,Re=new WeakMap,we=new WeakMap,oe=new WeakMap,bt=new WeakMap,Rt=new WeakMap,mt=async function(){var t,e,s;l(this,j,!0),p(this,m,Rr).call(this);try{await p(this,m,Oe).call(this)}catch(a){if(l(this,Le,a),a instanceof Error&&l(this,g,r(this,g).toErrorState(a)),r(this,He)){let o=await r(this,He).call(this,a),i=!(a instanceof G);if(o&&typeof o=="object"&&i){if(o.params&&(this.options.params=E(E({},(t=this.options.params)!=null?t:{}),o.params)),o.headers&&(this.options.headers=E(E({},(e=this.options.headers)!=null?e:{}),o.headers)),z(this,oe)._++,r(this,oe)>r(this,bt)){console.warn(`[Electric] onError retry loop exhausted after ${r(this,bt)} consecutive retries. The error was never resolved by the onError handler. Error: ${a instanceof Error?a.message:String(a)}`,new Error("stack trace")),a instanceof Error&&p(this,m,Kt).call(this,a),p(this,m,ye).call(this);return}if(l(this,Le,null),r(this,g)instanceof Ue&&l(this,g,r(this,g).retry()),l(this,K,0),l(this,N,[]),await p(this,m,fr).call(this,r(this,oe)),(s=this.options.signal)!=null&&s.aborted){p(this,m,ye).call(this);return}return l(this,j,!1),p(this,m,mt).call(this)}a instanceof Error&&p(this,m,Kt).call(this,a),p(this,m,ye).call(this);return}throw a instanceof Error&&p(this,m,Kt).call(this,a),p(this,m,ye).call(this),a}p(this,m,ye).call(this)},ye=function(){var t,e;l(this,Y,!1),(t=r(this,Ne))==null||t.call(this),(e=r(this,ne))==null||e.call(this)},fr=async function(t){let{initialDelay:e,maxDelay:s,multiplier:a}=r(this,Rt),o=Math.min(s,e*Math.pow(a,t-1)),i=Math.floor(Math.random()*o),c=this.options.signal;i<=0||c!=null&&c.aborted||await new Promise(h=>{let u=!1,d=()=>{u||(u=!0,clearTimeout(S),c==null||c.removeEventListener("abort",d),h())},S=setTimeout(d,i);c==null||c.addEventListener("abort",d,{once:!0}),c!=null&&c.aborted&&d()})},Oe=async function(t){var d,S,b;if((d=this.options.signal)!=null&&d.aborted){p(this,m,ye).call(this);return}if(r(this,g)instanceof Ue)throw r(this,g).error;let e=t!=null?t:r(this,be);if(r(this,U).isPaused){e&&l(this,be,e);return}if(!this.options.subscribe&&((S=this.options.signal)!=null&&S.aborted||r(this,g).isUpToDate))return;r(this,g).isUpToDate?(l(this,K,0),l(this,N,[])):await p(this,m,pr).call(this);let s=!1;r(this,g)instanceof ut&&(s=!0,l(this,g,r(this,g).resume()));let{url:a,signal:o}=this.options,{fetchUrl:i,requestHeaders:c}=await p(this,m,Yt).call(this,a,s);e&&(i.searchParams.set(ue,e),i.searchParams.sort());let h=await p(this,m,mr).call(this,o),u=r(this,B);if(r(this,U).isPaused){h&&o&&o.removeEventListener("abort",h),e&&l(this,be,e),l(this,B,void 0);return}l(this,be,void 0);try{await p(this,m,gr).call(this,{fetchUrl:i,requestAbortController:u,headers:c,resumingFromPause:s})}catch(y){let R=u.signal.reason,w=r(this,Ie).delete(u),P=u.signal.aborted&&(w||R===us||R===fs);if((y instanceof x||y instanceof $)&&P)return p(this,m,Oe).call(this);if(y instanceof $)return;if(y instanceof le)return p(this,m,Oe).call(this);if(!(y instanceof x))throw y;if(y.status==409){if(r(this,g).handle){let C=Se(i);X.markExpired(C,r(this,g).handle)}let A=y.headers[J];A||console.warn("[Electric] Received 409 response without a shape handle header. This likely indicates a proxy or CDN stripping required headers.");let k=Wt();return p(this,m,Qt).call(this,A),await p(this,m,Os).call(this,[{headers:{control:"must-refetch"}}]),p(this,m,Oe).call(this,k)}else throw y}finally{h&&o&&o.removeEventListener("abort",h),l(this,B,void 0)}return(b=r(this,Fe))==null||b.call(this),p(this,m,Oe).call(this)},pr=async function(){let t=Date.now(),e=r(this,g).offset;if(l(this,N,r(this,N).filter(i=>t-i.timestamp<r(this,We))),r(this,N).push({timestamp:t,offset:e}),r(this,N).filter(i=>i.offset===e).length<r(this,Ye))return;if(z(this,K)._++,r(this,K)>=r(this,yt))throw new x(502,void 0,void 0,{},this.options.url,`Client is stuck in a fast retry loop (${r(this,Ye)} requests in ${r(this,We)}ms at the same offset, repeated ${r(this,yt)} 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: ${ge}`);if(r(this,K)===1){if(console.warn(`[Electric] Detected fast retry loop (${r(this,Ye)} requests in ${r(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: ${ge}`,new Error("stack trace")),r(this,F)){let i=Se(r(this,F));X.delete(i),it.delete(i)}else X.clear(),it.clear();p(this,m,Qt).call(this),l(this,N,[]);return}let a=Math.min(r(this,ts),r(this,es)*Math.pow(2,r(this,K))),o=Math.floor(Math.random()*a);await new Promise(i=>setTimeout(i,o)),l(this,N,[])},Yt=async function(t,e,s){var u,d,S,b,y,R;let[a,o]=await Promise.all([sn(this.options.headers),this.options.params?tn(cn(this.options.params)):void 0]);o&&xr(o);let i=new URL(t);if(o){if(o.table&&O(i,Js,o.table),o.where&&typeof o.where=="string"){let P=Te(o.where,(u=this.options.columnMapper)==null?void 0:u.encode);O(i,Xs,P)}if(o.columns){let P=await Hs((d=this.options.params)==null?void 0:d.columns);if(Array.isArray(P)){let A=P.map(String);this.options.columnMapper&&(A=A.map(this.options.columnMapper.encode));let k=A.map(Ge).join(",");O(i,ls,k)}else O(i,ls,o.columns)}o.replica&&O(i,Zs,o.replica),o.params&&O(i,er,o.params);let w=E({},o);delete w.table,delete w.where,delete w.columns,delete w.replica,delete w.params;for(let[P,A]of Object.entries(w))O(i,P,A)}if(s){if(s.whereExpr){let w=ot(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);O(i,Ce,w),i.searchParams.set(ms,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let w=Te(s.where,(b=this.options.columnMapper)==null?void 0:b.encode);O(i,Ce,w)}if(s.params&&i.searchParams.set(rt,Lt(s.params)),s.limit!==void 0&&O(i,tt,s.limit),s.offset!==void 0&&O(i,st,s.offset),s.orderByExpr){let w=It(s.orderByExpr,(y=this.options.columnMapper)==null?void 0:y.encode);O(i,Pe,w),i.searchParams.set(gs,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let w=Te(s.orderBy,(R=this.options.columnMapper)==null?void 0:R.encode);O(i,Pe,w)}}r(this,g).applyUrlParams(i,{isSnapshotRequest:s!==void 0,canLongPoll:!r(this,m,ks)&&!e}),i.searchParams.set(ps,r(this,se));let c=Se(i),h=X.getExpiredHandle(c);return h&&i.searchParams.set(et,h),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}},mr=async function(t){var e;if(l(this,B,new AbortController),t){let s=()=>{var a;(a=r(this,B))==null||a.abort(t.reason)};return t.addEventListener("abort",s,{once:!0}),t.aborted&&((e=r(this,B))==null||e.abort(t.reason)),s}},Us=async function(t){var h,u,d;let{headers:e,status:s}=t,a=e.get(J),o=r(this,F)?Se(r(this,F)):null,i=o?X.getExpiredHandle(o):null;if(r(this,we)){let{shapeKey:S,staleHandle:b}=r(this,we);l(this,we,null),o===S&&a===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: ${ge}`,new Error("stack trace"))}let c=r(this,g).handleResponseMetadata({status:s,responseHandle:a,responseOffset:e.get(Ae),responseCursor:e.get(Dt),responseSchema:ur(e),expiredHandle:i,now:Date.now(),maxStaleCacheRetries:r(this,ae),createCacheBuster:Wt});if(l(this,g,c.state),s===204&&l(this,Re,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?o&&(X.delete(o),r(this,Re)!==o)?(console.warn(`[Electric] Stale cache retries exhausted (${r(this,ae)} attempts). Clearing expired handle entry and attempting self-healing retry without the expired_handle parameter. For more information visit the troubleshooting guide: ${ge}`,new Error("stack trace")),l(this,Re,o),a&&l(this,we,{shapeKey:o,staleHandle:a}),p(this,m,Qt).call(this),new le("Expired handle entry evicted for self-healing retry")):new x(502,void 0,void 0,{},(d=(u=r(this,F))==null?void 0:u.toString())!=null?d:"",`CDN continues serving stale cached responses after ${r(this,ae)} 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: ${ge}`):(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 "${a}" 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: ${ge} Retrying with a random cache buster to bypass the stale cache (attempt ${r(this,g).staleCacheRetryCount}/${r(this,ae)}).`,new Error("stack trace")),new le(`Received stale cached response with expired handle "${a}". 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 "${r(this,g).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},Vt=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 a=t[t.length-1],o=is(a),i=o?Qs(a):void 0,c=r(this,g).handleMessageBatch({hasMessages:!0,hasUpToDateMessage:o,isSse:e,upToDateOffset:i,now:Date.now(),currentCursor:r(this,g).liveCacheBuster});if(l(this,g,c.state),o){if(c.suppressBatch)return;if(r(this,F)){let u=Se(r(this,F));it.recordUpToDate(u,r(this,g).liveCacheBuster),l(this,Re,null)}}let h=t.filter(u=>Je(u)?!r(this,gt).shouldRejectMessage(u):!0);await p(this,m,Os).call(this,h,{allowReentrantBypass:s.allowReentrantPublishBypass})},gr=async function(t){var s;if(l(this,F,t.fetchUrl),!r(this,g).isUpToDate&&r(this,g).canEnterReplayMode()){let a=Se(t.fetchUrl),o=it.shouldEnterReplayMode(a);o&&l(this,g,r(this,g).enterReplayMode(o))}let e=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return r(this,g).shouldUseSse({liveSseEnabled:!!e,isRefreshing:r(this,m,ks),resumingFromPause:!!t.resumingFromPause})?(t.fetchUrl.searchParams.set(hs,"true"),t.fetchUrl.searchParams.set(ds,"true"),p(this,m,yr).call(this,t)):p(this,m,Sr).call(this,t)},Sr=async function(t){var S;let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=await r(this,De).call(this,e.toString(),{signal:s.signal,headers:a});if(l(this,Y,!0),!await p(this,m,Us).call(this,o))return;let c=r(this,g).schema,u=await o.text()||"[]",d=r(this,Ee).parse(u,c);if(!Array.isArray(d)){let b=(S=Lt(d))==null?void 0:S.slice(0,200);throw new x(o.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 d}: ${b}`,void 0,Object.fromEntries(o.headers.entries()),e.toString())}await p(this,m,Vt).call(this,d)},yr=async function(t){let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=r(this,Be);l(this,St,Date.now());let i=_(E({},a),{Accept:"text/event-stream"}),c=!1;try{let h=[];await bs(e.toString(),{headers:i,fetch:o,onopen:async u=>{if(l(this,Y,!0),!await p(this,m,Us).call(this,u))throw c=!0,new Error("stale response ignored")},onmessage:u=>{if(u.data){let d=r(this,g).schema,S=r(this,Ee).parse(u.data,d);h.push(S),is(S)&&(p(this,m,Vt).call(this,h,!0),h=[])}},onerror:u=>{throw u},signal:s.signal})}catch(h){if(c)return;if(s.signal.aborted)throw new $;if(h instanceof x||h instanceof le||h instanceof G)throw h}finally{let h=Date.now()-r(this,St),u=s.signal.aborted,d=r(this,g).handleSseConnectionClosed({connectionDuration:h,wasAborted:u,minConnectionDuration:r(this,Gt),maxShortConnections:r(this,Jt)});if(l(this,g,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 S=Math.min(r(this,Zt),r(this,Xt)*Math.pow(2,r(this,g).consecutiveShortSseConnections)),b=Math.floor(Math.random()*S);await new Promise(y=>setTimeout(y,b))}}},Er=async function(){if(r(this,U).isPaused)throw new Error("Cannot wait for next tick while PauseLock is held \u2014 this would deadlock because the request loop is paused");return r(this,V)?r(this,V):(l(this,V,new Promise((t,e)=>{l(this,Fe,t),l(this,Ne,e)})),r(this,V).finally(()=>{l(this,V,void 0),l(this,Fe,void 0),l(this,Ne,void 0)}),r(this,V))},Os=async function(t,e={}){let s=()=>Promise.all(Array.from(r(this,te).values()).map(async([a,o])=>{try{await a(t)}catch(i){queueMicrotask(()=>{throw i})}}));return r(this,qe)&&e.allowReentrantBypass?s():(l(this,$e,r(this,$e).then(async()=>{l(this,qe,!0);try{return await s()}finally{l(this,qe,!1)}})),r(this,$e))},Kt=function(t){r(this,te).forEach(([e,s])=>{s==null||s(t)})},Ls=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},br=function(){if(p(this,m,Ls).call(this)){let t=()=>{document.hidden?r(this,U).acquire("visibility"):r(this,U).release("visibility")};document.addEventListener("visibilitychange",t),l(this,je,()=>{document.removeEventListener("visibilitychange",t),l(this,je,void 0)})}},Rr=function(){if(p(this,m,Ls).call(this)||r(this,ne))return;let t=2e3,e=4e3,s=Date.now(),a=setInterval(()=>{let o=Date.now(),i=o-s;if(s=o,i>t+e){let c=r(this,B);!r(this,U).isPaused&&c&&!c.signal.aborted&&(z(this,re)._++,r(this,Ie).add(c),c.abort(fs),queueMicrotask(()=>{z(this,re)._--}))}},t);typeof a=="object"&&"unref"in a&&a.unref(),l(this,ne,()=>{clearInterval(a),l(this,ne,void 0)})},Qt=function(t){l(this,g,r(this,g).markMustRefetch(t)),l(this,Y,!1),r(this,U).releaseAllMatching("snapshot")},Ds=async function(t,e,s){var P,A,k;let o=((A=(P=t.method)!=null?P:this.options.subsetMethod)!=null?A:"GET")==="POST",i,c;if(o){let C=await p(this,m,Yt).call(this,this.options.url,!0);i=C.fetchUrl,c={method:"POST",headers:_(E({},C.requestHeaders),{"Content-Type":"application/json"}),body:Lt(p(this,m,wr).call(this,t))}}else{let C=await p(this,m,Yt).call(this,this.options.url,!0,t);i=C.fetchUrl,c={headers:C.requestHeaders}}s&&(i.searchParams.set(ue,s),i.searchParams.sort());let h=r(this,g).handle,u;try{u=await r(this,De).call(this,i.toString(),c)}catch(C){if(C instanceof x&&C.status===409){let xt=e+1;if(xt>r(this,Et))throw new x(502,void 0,void 0,{},i.toString(),`Snapshot request stuck in 409 retry loop after ${r(this,Et)} attempts. This indicates a proxy/CDN misconfiguration. For more information visit the troubleshooting guide: ${ge}`);if(h){let vt=Se(i);X.markExpired(vt,h)}let ve=C.headers[J];ve?l(this,g,r(this,g).withHandle(ve)):console.warn("[Electric] Received 409 response without a shape handle header. This likely indicates a proxy or CDN stripping required headers.");let Ke=Wt();return p(this,m,Ds).call(this,t,xt,Ke)}throw C}if(!u.ok)throw await x.fromResponse(u,i.toString());let d=(k=r(this,g).schema)!=null?k:ur(u.headers,{required:!0,url:i.toString()}),{metadata:S,data:b}=await u.json(),y=r(this,Ee).parseSnapshotData(b,d),R=