UNPKG

@electric-sql/client

Version:

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

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