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