@electric-sql/client 1.5.7 → 1.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,11 @@
1
- var Zs=Object.defineProperty,er=Object.defineProperties;var tr=Object.getOwnPropertyDescriptors;var rt=Object.getOwnPropertySymbols;var us=Object.prototype.hasOwnProperty,ds=Object.prototype.propertyIsEnumerable;var ps=r=>{throw TypeError(r)};var hs=(r,t,e)=>t in r?Zs(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,y=(r,t)=>{for(var e in t||(t={}))us.call(t,e)&&hs(r,e,t[e]);if(rt)for(var e of rt(t))ds.call(t,e)&&hs(r,e,t[e]);return r},P=(r,t)=>er(r,tr(t));var Ue=(r,t)=>{var e={};for(var s in r)us.call(r,s)&&t.indexOf(s)<0&&(e[s]=r[s]);if(r!=null&&rt)for(var s of rt(r))t.indexOf(s)<0&&ds.call(r,s)&&(e[s]=r[s]);return e};var Ut=(r,t,e)=>t.has(r)||ps("Cannot "+e);var n=(r,t,e)=>(Ut(r,t,"read from private field"),e?e.call(r):t.get(r)),f=(r,t,e)=>t.has(r)?ps("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),d=(r,t,e,s)=>(Ut(r,t,"write to private field"),s?s.call(r,e):t.set(r,e),e),g=(r,t,e)=>(Ut(r,t,"access private method"),e);var ce=(r,t,e,s)=>({set _(a){d(r,t,a,e)},get _(){return n(r,t,s)}});var A=class r extends Error{constructor(e,s,a,o,i,l){super(l||`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,l,h=e.headers.get("content-type");return e.bodyUsed||(h&&h.includes("application/json")?l=await e.json():i=await e.text()),new r(a,i,l,o,s)}},I=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var nt=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},at=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},ot=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},it=class extends Error{constructor(t){super(`Cannot use reserved Electric parameter names in custom params: ${t.join(", ")}`),this.name="ReservedParamError"}},ct=class extends Error{constructor(t){super(`Column "${t!=null?t:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Y=class extends Error{constructor(t,e){let s=`The response for the shape request to ${t} didn't include the following required headers:
1
+ var cr=Object.defineProperty,lr=Object.defineProperties;var hr=Object.getOwnPropertyDescriptors;var lt=Object.getOwnPropertySymbols;var Rs=Object.prototype.hasOwnProperty,bs=Object.prototype.propertyIsEnumerable;var ws=n=>{throw TypeError(n)};var Es=(n,t,e)=>t in n?cr(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,y=(n,t)=>{for(var e in t||(t={}))Rs.call(t,e)&&Es(n,e,t[e]);if(lt)for(var e of lt(t))bs.call(t,e)&&Es(n,e,t[e]);return n},C=(n,t)=>lr(n,hr(t));var De=(n,t)=>{var e={};for(var s in n)Rs.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&lt)for(var s of lt(n))t.indexOf(s)<0&&bs.call(n,s)&&(e[s]=n[s]);return e};var Nt=(n,t,e)=>t.has(n)||ws("Cannot "+e);var r=(n,t,e)=>(Nt(n,t,"read from private field"),e?e.call(n):t.get(n)),p=(n,t,e)=>t.has(n)?ws("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),d=(n,t,e,s)=>(Nt(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),g=(n,t,e)=>(Nt(n,t,"access private method"),e);var se=(n,t,e,s)=>({set _(a){d(n,t,a,e)},get _(){return r(n,t,s)}});var v=class n extends Error{constructor(e,s,a,o,i,l){super(l||`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,l,h=e.headers.get("content-type");return e.bodyUsed||(h&&h.includes("application/json")?l=await e.json():i=await e.text()),new n(a,i,l,o,s)}},N=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var ht=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},dt=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},ut=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},pt=class extends Error{constructor(t){super(`Cannot use reserved Electric parameter names in custom params: ${t.join(", ")}`),this.name="ReservedParamError"}},ft=class extends Error{constructor(t){super(`Column "${t!=null?t:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var W=class extends Error{constructor(t,e){let s=`The response for the shape request to ${t} didn't include the following required headers:
2
2
  `;e.forEach(a=>{s+=`- ${a}
3
3
  `}),s+=`
4
4
  This is often due to a proxy not setting CORS correctly so that all Electric headers can be read by the client.`,s+=`
5
- 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 lt=r=>Number(r),sr=r=>r==="true"||r==="t",rr=r=>BigInt(r),fs=r=>JSON.parse(r),nr=r=>r,ar={int2:lt,int4:lt,int8:rr,bool:sr,float4:lt,float8:lt,json:fs,jsonb:fs};function or(r,t){let e=0,s=null,a="",o=!1,i=0,l;function h(c,S,x){let b=c.slice(S,x);return b=b==="NULL"?null:b,t?t(b):b}function u(c){let S=[];for(;e<c.length;e++){if(s=c[e],o)s==="\\"?a+=c[++e]:s==='"'?(S.push(t?t(a):a),a="",o=c[e+1]==='"',i=e+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++e,S.push(u(c));else if(s==="}"){o=!1,i<e&&S.push(h(c,i,e)),i=e+1;break}else s===","&&l!=="}"&&l!=='"'&&(S.push(h(c,i,e)),i=e+1);l=s}return i<e&&S.push(S.push(h(c,i,e+1))),S}return u(r)[0]}var ht=class{constructor(t,e){this.parser=y(y({},ar),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 c=a,{type:o,dims:i}=c,l=Ue(c,["type","dims"]),h=(S=this.parser[o])!=null?S:nr,u=ms(h,a,t);return i&&i>0?ms((b,E)=>or(b,u),a,t)(e):u(e,l)}};function ms(r,t,e){var a;let s=!((a=t.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new ct(e!=null?e:"unknown");return null}return r(o,t)}}function ke(r){return`"${r.replace(/"/g,'""')}"`}function kt(r){var l,h,u,c;let t=(h=(l=r.match(/^_+/))==null?void 0:l[0])!=null?h:"",e=r.slice(t.length),s=(c=(u=e.match(/_+$/))==null?void 0:u[0])!=null?c:"",i=(s?e.slice(0,e.length-s.length):e).toLowerCase().replace(/_+([a-z])/g,(S,x)=>x.toUpperCase());return t+i+s}function gs(r){return r.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ss(r){let t={};for(let[e,s]of Object.entries(r))t[s]=e;return{decode:e=>{var s;return(s=r[e])!=null?s:e},encode:e=>{var s;return(s=t[e])!=null?s:e}}}function he(r,t){if(!r||!t)return r!=null?r:"";let e=new Set(["SELECT","FROM","WHERE","AND","OR","NOT","IN","IS","NULL","NULLS","FIRST","LAST","TRUE","FALSE","LIKE","ILIKE","BETWEEN","ASC","DESC","LIMIT","OFFSET","ORDER","BY","GROUP","HAVING","DISTINCT","AS","ON","JOIN","LEFT","RIGHT","INNER","OUTER","CROSS","CASE","WHEN","THEN","ELSE","END","CAST","LOWER","UPPER","COALESCE","NULLIF"]),s=[],a=0;for(;a<r.length;){let l=r[a];if(l==="'"||l==='"'){let h=a,u=l;for(a++;a<r.length;)if(r[a]===u)if(r[a+1]===u)a+=2;else{a++;break}else a++;s.push({start:h,end:a})}else a++}let o=l=>s.some(h=>l>=h.start&&l<h.end),i=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(i,(l,h,u)=>o(u)||e.has(l.toUpperCase())||l.startsWith("$")?l:t(l))}function ir(r){if(r){let t={};for(let e of Object.keys(r))t[e]=kt(e);return Ss(t)}return{decode:t=>kt(t),encode:t=>gs(t)}}function ue(r){return r!=null&&"key"in r}function ut(r){return r!=null&&!ue(r)}function Ot(r){return ut(r)&&r.headers.control==="up-to-date"}function ys(r){if(r.headers.control!="up-to-date")return;let t=r.headers.global_last_seen_lsn;return t?`${t}_0`:void 0}function cr(r,t){return typeof t=="bigint"?t.toString():t}function de(r){return JSON.stringify(r,cr)}function Lt(r,t){let e=BigInt(r),s=BigInt(t.xmin),a=BigInt(t.xmax),o=t.xip_list.map(BigInt);return e<s||e<a&&!o.includes(e)}var Es="electric-cursor",ee="electric-handle",Oe="electric-offset",Bt="electric-schema",Rs="electric-up-to-date",Dt="columns",Le="cursor",Be="expired_handle",te="handle",D="live",se="offset",bs="table",xs="where",ws="replica",Ts="params",As="experimental_live_sse",Ht="live_sse",It="force-disconnect-and-refresh",vs="pause-stream",Ft="system-wake",Nt="log",pe="subset__where",De="subset__limit",He="subset__offset",fe="subset__order_by",Ie="subset__params",qt="subset__where_expr",$t="subset__order_by_expr",Fe="cache-buster",jt=[D,Ht,te,se,Le,Be,Nt,pe,De,He,fe,Ie,qt,$t,Fe];var lr=[429],pt={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function hr(r){if(!r)return 0;let t=Number(r);if(Number.isFinite(t)&&t>0)return t*1e3;let e=Date.parse(r);if(!isNaN(e)){let s=e-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function Ps(r,t=pt){let{initialDelay:e,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:l=1/0}=t;return async(...h)=>{var b;let u=h[0],c=h[1],S=e,x=0;for(;;)try{let E=await r(...h);if(E.ok)return E;throw await A.fromResponse(E,u.toString())}catch(E){if(i==null||i(),(b=c==null?void 0:c.signal)!=null&&b.aborted)throw new I;if(E instanceof A&&!lr.includes(E.status)&&E.status>=400&&E.status<500)throw E;{if(x++,x>l)throw o&&console.log(`Max retries reached (${x}/${l}), giving up`),E;let R=E instanceof A&&E.headers?hr(E.headers["retry-after"]):0,C=Math.random()*S,T=Math.min(C,s),L=Math.max(R,T);if(o){let Z=R>0?"server+client":"client";console.log(`Retry attempt #${x} after ${L}ms (${Z}, serverMin=${R}ms, clientBackoff=${T}ms)`)}await new Promise(Z=>setTimeout(Z,L)),S=Math.min(S*a,s)}}}}var ur=[201,204,205];function Cs(r){return async(...t)=>{var a,o;let e=t[0],s=await r(...t);try{if(s.status<200||ur.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 I:new A(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 dr={maxChunksToPrefetch:2};function _s(r,t=dr){let{maxChunksToPrefetch:e}=t,s;return async(...o)=>{let i=o[0].toString();if(yr(o[0],o[1])!=="GET")return s==null||s.abort(),s=void 0,r(...o);let h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort(),s=void 0;let u=await r(...o),c=Vt(i,u);return c&&(s=new Yt({fetchClient:r,maxPrefetchedRequests:e,url:c,requestInit:o[1]})),u}}var pr=["electric-offset","electric-handle"],fr=["electric-cursor"],mr=["electric-schema"];function Ms(r){return async(...t)=>{let e=await r(...t);if(e.ok){let s=e.headers,a=[],o=c=>a.push(...c.filter(S=>!s.has(S))),l=t[0].toString(),h=new URL(l);if([pe,Ie,De,He,fe].some(c=>h.searchParams.has(c)))return e;if(o(pr),h.searchParams.get(D)==="true"&&o(fr),(!h.searchParams.has(D)||h.searchParams.get(D)==="false")&&o(mr),a.length>0)throw new Y(l,a)}return e}}var Ne,qe,B,re,F,me,dt,Yt=class{constructor(t){f(this,me);f(this,Ne);f(this,qe);f(this,B,new Map);f(this,re);f(this,F);var e;d(this,Ne,(e=t.fetchClient)!=null?e:(...s)=>fetch(...s)),d(this,qe,t.maxPrefetchedRequests),d(this,re,t.url.toString()),d(this,F,n(this,re)),g(this,me,dt).call(this,t.url,t.requestInit)}abort(){n(this,B).forEach(([t,e])=>e.abort()),n(this,B).clear()}consume(...t){let e=t[0].toString(),s=n(this,B).get(e);if(!s||e!==n(this,re))return;let[a,o]=s;if(o.signal.aborted){n(this,B).delete(e);return}return n(this,B).delete(e),a.then(i=>{let l=Vt(e,i);d(this,re,l),n(this,F)&&!n(this,B).has(n(this,F))&&g(this,me,dt).call(this,n(this,F),t[1])}).catch(()=>{}),a}};Ne=new WeakMap,qe=new WeakMap,B=new WeakMap,re=new WeakMap,F=new WeakMap,me=new WeakSet,dt=function(...t){var a,o;let e=t[0].toString();if(n(this,B).size>=n(this,qe))return;let s=new AbortController;try{let{signal:i,cleanup:l}=gr(s,(a=t[1])==null?void 0:a.signal),h=n(this,Ne).call(this,e,P(y({},(o=t[1])!=null?o:{}),{signal:i}));n(this,B).set(e,[h,s]),h.then(u=>{if(!u.ok||s.signal.aborted)return;let c=Vt(e,u);if(!c||c===e){d(this,F,void 0);return}return d(this,F,c),g(this,me,dt).call(this,c,t[1])}).catch(()=>{}).finally(l)}catch(i){}};function Vt(r,t){let e=t.headers.get(ee),s=t.headers.get(Oe),a=t.headers.has(Rs);if(!e||!s||a)return;let o=new URL(r);if(o.searchParams.has(D))return;let i=o.searchParams.get(Be);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(te,e),o.searchParams.set(se,s),o.searchParams.sort(),o.toString()}function gr(r,t){let e=Sr;if(t)if(t.aborted)r.abort();else{let s=()=>r.abort();t.addEventListener("abort",s,{once:!0,signal:r.signal}),e=()=>t.removeEventListener("abort",s)}return{signal:r.signal,cleanup:e}}function Sr(){}function yr(r,t){return t!=null&&t.method?t.method.toUpperCase():typeof Request!="undefined"&&r instanceof Request?r.method.toUpperCase():"GET"}function $e(r,t){switch(r.type){case"ref":{let e=t?t(r.column):r.column;return ke(e)}case"val":return`$${r.paramIndex}`;case"func":return Er(r,t);default:{let e=r;throw new Error(`Unknown expression type: ${JSON.stringify(e)}`)}}}function Er(r,t){let e=r.args.map(s=>$e(s,t));switch(r.name){case"eq":return`${e[0]} = ${e[1]}`;case"gt":return`${e[0]} > ${e[1]}`;case"gte":return`${e[0]} >= ${e[1]}`;case"lt":return`${e[0]} < ${e[1]}`;case"lte":return`${e[0]} <= ${e[1]}`;case"and":return e.map(s=>`(${s})`).join(" AND ");case"or":return e.map(s=>`(${s})`).join(" OR ");case"not":return`NOT (${e[0]})`;case"in":return`${e[0]} = ANY(${e[1]})`;case"like":return`${e[0]} LIKE ${e[1]}`;case"ilike":return`${e[0]} ILIKE ${e[1]}`;case"isNull":case"isUndefined":return`${e[0]} IS NULL`;case"upper":return`UPPER(${e[0]})`;case"lower":return`LOWER(${e[0]})`;case"length":return`LENGTH(${e[0]})`;case"concat":return`CONCAT(${e.join(", ")})`;case"coalesce":return`COALESCE(${e.join(", ")})`;default:throw new Error(`Unknown function: ${r.name}`)}}function ft(r,t){return r.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 ks(r,t){let e=r.getReader(),s;for(;!(s=await e.read()).done;)t(s.value)}function Os(r){let t,e,s,a=!1;return function(i){t===void 0?(t=i,e=0,s=-1):t=Rr(t,i);let l=t.length,h=0;for(;e<l;){a&&(t[e]===10&&(h=++e),a=!1);let u=-1;for(;e<l&&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;r(t.subarray(h,u),s),h=e,s=-1}h===l?t=void 0:h!==0&&(t=t.subarray(h),e-=h)}}function Ls(r,t,e){let s=Us(),a=new TextDecoder;return function(i,l){if(i.length===0)e==null||e(s),s=Us();else if(l>0){let h=a.decode(i.subarray(0,l)),u=l+(i[l+1]===32?2:1),c=a.decode(i.subarray(u));switch(h){case"data":s.data=s.data?s.data+`
6
- `+c:c;break;case"event":s.event=c;break;case"id":r(s.id=c);break;case"retry":let S=parseInt(c,10);isNaN(S)||t(s.retry=S);break}}}}function Rr(r,t){let e=new Uint8Array(r.length+t.length);return e.set(r),e.set(t,r.length),e}function Us(){return{data:"",event:"",id:"",retry:void 0}}var br=function(r,t){var e={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&t.indexOf(s)<0&&(e[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,s=Object.getOwnPropertySymbols(r);a<s.length;a++)t.indexOf(s[a])<0&&Object.prototype.propertyIsEnumerable.call(r,s[a])&&(e[s[a]]=r[s[a]]);return e},mt="text/event-stream",xr=1e3,Bs="last-event-id";function Wt(r,t){var{signal:e,headers:s,onopen:a,onmessage:o,onclose:i,onerror:l,openWhenHidden:h,fetch:u}=t,c=br(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((S,x)=>{let b=Object.assign({},s);b.accept||(b.accept=mt);let E;function R(){E.abort(),typeof document!="undefined"&&!document.hidden&&_t()}typeof document!="undefined"&&!h&&document.addEventListener("visibilitychange",R);let C=xr,T=0;function L(){typeof document!="undefined"&&document.removeEventListener("visibilitychange",R),clearTimeout(T),E.abort()}e==null||e.addEventListener("abort",()=>{L()});let Z=u!=null?u:window.fetch,Xs=a!=null?a:wr;async function _t(){var Mt;E=new AbortController;let ls=e.aborted?e:E.signal;try{let Me=await Z(r,Object.assign(Object.assign({},c),{headers:b,signal:ls}));await Xs(Me),await ks(Me.body,Os(Ls(j=>{j?b[Bs]=j:delete b[Bs]},j=>{C=j},o))),i==null||i(),L(),S()}catch(Me){if(ls.aborted)L(),x(Me);else if(!E.signal.aborted)try{let j=(Mt=l==null?void 0:l(Me))!==null&&Mt!==void 0?Mt:C;clearTimeout(T),T=setTimeout(_t,j)}catch(j){L(),x(j)}}}_t()})}function wr(r){let t=r.headers.get("content-type");if(!(t!=null&&t.startsWith(mt)))throw new Error(`Expected content-type to be ${mt}, Actual: ${t}`)}var Kt=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()}},je=new Kt;var Qt=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()}},zt=new Qt;var gt=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(t,e){var o,i,l,h;this.activeSnapshots.set(t.snapshot_mark,{xmin:BigInt(t.xmin),xmax:BigInt(t.xmax),xip_list:t.xip_list.map(BigInt),keys:e});let s=(i=(o=this.xmaxSnapshots.get(BigInt(t.xmax)))==null?void 0:o.add(t.snapshot_mark))!=null?i:new Set([t.snapshot_mark]);this.xmaxSnapshots.set(BigInt(t.xmax),s);let a=(h=(l=this.snapshotsByDatabaseLsn.get(BigInt(t.database_lsn)))==null?void 0:l.add(t.snapshot_mark))!=null?h:new Set([t.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(t.database_lsn),a)}removeSnapshot(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)&&Lt(s,a))}lastSeenUpdate(t){for(let[e,s]of this.snapshotsByDatabaseLsn.entries())if(e<=t)for(let a of s)this.removeSnapshot(a)}};var Ye=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 Qe(this)}toErrorState(t){return new ze(this,t)}markMustRefetch(t){return new St({handle:t,offset:"-1",liveCacheBuster:"",lastSyncedAt:this.lastSyncedAt,schema:void 0})}},w,Ve=class extends Ye{constructor(e){super();f(this,w);d(this,w,e)}get handle(){return n(this,w).handle}get offset(){return n(this,w).offset}get schema(){return n(this,w).schema}get liveCacheBuster(){return n(this,w).liveCacheBuster}get lastSyncedAt(){return n(this,w).lastSyncedAt}get currentFields(){return n(this,w)}applyUrlParams(e,s){e.searchParams.set(se,n(this,w).offset),n(this,w).handle&&e.searchParams.set(te,n(this,w).handle)}parseResponseFields(e){var u,c,S;let s=e.responseHandle,a=s&&s!==e.expiredHandle?s:n(this,w).handle,o=(u=e.responseOffset)!=null?u:n(this,w).offset,i=(c=e.responseCursor)!=null?c:n(this,w).liveCacheBuster,l=(S=n(this,w).schema)!=null?S:e.responseSchema,h=e.status===204?e.now:n(this,w).lastSyncedAt;return{handle:a,offset:o,schema:l,liveCacheBuster:i,lastSyncedAt:h}}checkStaleResponse(e){let s=e.responseHandle,a=e.expiredHandle;if(!s||s!==a)return null;if(n(this,w).handle===void 0||n(this,w).handle===a){let o=this.staleCacheRetryCount+1;return{action:"stale-retry",state:new Jt(P(y({},this.currentFields),{staleCacheBuster:e.createCacheBuster(),staleCacheRetryCount:o})),exceededMaxRetries:o>e.maxStaleCacheRetries}}return{action:"ignored",state:this}}handleMessageBatch(e){if(!e.hasMessages||!e.hasUpToDateMessage)return{state:this,suppressBatch:!1,becameUpToDate:!1};let s=n(this,w).offset;e.isSse&&e.upToDateOffset&&(s=e.upToDateOffset);let a={handle:n(this,w).handle,offset:s,schema:n(this,w).schema,liveCacheBuster:n(this,w).liveCacheBuster,lastSyncedAt:e.now};return this.onUpToDate(a,e)}onUpToDate(e,s){return{state:new Ke(e),suppressBatch:!1,becameUpToDate:!0}}};w=new WeakMap;var We=class extends Ve{handleResponseMetadata(t){let e=this.checkStaleResponse(t);if(e)return e;let s=this.parseResponseFields(t);return t.status===204?{action:"accepted",state:new Ke(s,{sseFallbackToLongPolling:!0})}:{action:"accepted",state:new Gt(s)}}canEnterReplayMode(){return!0}enterReplayMode(t){return new Xt(P(y({},this.currentFields),{replayCursor:t}))}},St=class r extends We{constructor(e){super(e);this.kind="initial"}withHandle(e){return new r(P(y({},this.currentFields),{handle:e}))}},Gt=class r extends We{constructor(e){super(e);this.kind="syncing"}withHandle(e){return new r(P(y({},this.currentFields),{handle:e}))}},ne,Se,Zt=class Zt extends We{constructor(e){let i=e,{staleCacheBuster:s,staleCacheRetryCount:a}=i,o=Ue(i,["staleCacheBuster","staleCacheRetryCount"]);super(o);this.kind="stale-retry";f(this,ne);f(this,Se);d(this,ne,s),d(this,Se,a)}get staleCacheBuster(){return n(this,ne)}get staleCacheRetryCount(){return n(this,Se)}canEnterReplayMode(){return!1}withHandle(e){return new Zt(P(y({},this.currentFields),{handle:e,staleCacheBuster:n(this,ne),staleCacheRetryCount:n(this,Se)}))}applyUrlParams(e,s){super.applyUrlParams(e,s),e.searchParams.set(Fe,n(this,ne))}};ne=new WeakMap,Se=new WeakMap;var Jt=Zt,ae,V,ge=class ge extends Ve{constructor(e,s){var a,o;super(e);this.kind="live";f(this,ae);f(this,V);d(this,ae,(a=s==null?void 0:s.consecutiveShortSseConnections)!=null?a:0),d(this,V,(o=s==null?void 0:s.sseFallbackToLongPolling)!=null?o:!1)}get isUpToDate(){return!0}get consecutiveShortSseConnections(){return n(this,ae)}get sseFallbackToLongPolling(){return n(this,V)}withHandle(e){return new ge(P(y({},this.currentFields),{handle:e}),this.sseState)}applyUrlParams(e,s){super.applyUrlParams(e,s),s.isSnapshotRequest||(e.searchParams.set(Le,this.liveCacheBuster),s.canLongPoll&&e.searchParams.set(D,"true"))}get sseState(){return{consecutiveShortSseConnections:n(this,ae),sseFallbackToLongPolling:n(this,V)}}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new ge(a,this.sseState)}}onUpToDate(e,s){return{state:new ge(e,this.sseState),suppressBatch:!1,becameUpToDate:!0}}shouldUseSse(e){return e.liveSseEnabled&&!e.isRefreshing&&!e.resumingFromPause&&!n(this,V)}handleSseConnectionClosed(e){let s=n(this,ae),a=n(this,V),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 ge(this.currentFields,{consecutiveShortSseConnections:s,sseFallbackToLongPolling:a}),fellBackToLongPolling:o,wasShortConnection:i}}};ae=new WeakMap,V=new WeakMap;var Ke=ge,W,yt=class yt extends Ve{constructor(e){let o=e,{replayCursor:s}=o,a=Ue(o,["replayCursor"]);super(a);this.kind="replaying";f(this,W);d(this,W,s)}get replayCursor(){return n(this,W)}withHandle(e){return new yt(P(y({},this.currentFields),{handle:e,replayCursor:n(this,W)}))}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new yt(P(y({},a),{replayCursor:n(this,W)}))}}onUpToDate(e,s){let a=!s.isSse&&n(this,W)===s.currentCursor;return{state:new Ke(e),suppressBatch:a,becameUpToDate:!0}}};W=new WeakMap;var Xt=yt,Qe=class r extends Ye{constructor(e){super();this.kind="paused";this.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);return s.action==="accepted"?{action:"accepted",state:new r(s.state)}:s}withHandle(e){return new r(this.previousState.withHandle(e))}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}pause(){return this}resume(){return this.previousState}},ze=class r extends Ye{constructor(e,s){super();this.kind="error";this.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}withHandle(e){return new r(this.previousState.withHandle(e),this.error)}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}retry(){return this.previousState}reset(e){return this.previousState.markMustRefetch(e)}};function Ds(r){return new St({handle:r.handle,offset:r.offset,liveCacheBuster:"",lastSyncedAt:void 0,schema:void 0})}var O,Ge,Je,Et=class{constructor(t){f(this,O,new Set);f(this,Ge);f(this,Je);d(this,Ge,t.onAcquired),d(this,Je,t.onReleased)}acquire(t){if(n(this,O).has(t)){console.warn(`[Electric] PauseLock: "${t}" already held \u2014 ignoring duplicate acquire`);return}let e=n(this,O).size===0;n(this,O).add(t),e&&n(this,Ge).call(this)}release(t){if(!n(this,O).delete(t)){console.warn(`[Electric] PauseLock: "${t}" not held \u2014 ignoring release (possible acquire/release mismatch)`);return}n(this,O).size===0&&n(this,Je).call(this)}get isPaused(){return n(this,O).size>0}isHeldBy(t){return n(this,O).has(t)}releaseAllMatching(t){for(let e of n(this,O))e.startsWith(t)&&n(this,O).delete(e)}};O=new WeakMap,Ge=new WeakMap,Je=new WeakMap;var Tr=new Set([Le,te,D,se,Fe]);async function os(r){return typeof r=="function"?r():r}async function Ar(r){let t=Object.entries(r),e=await Promise.all(t.map(async([s,a])=>{if(a===void 0)return[s,void 0];let o=await os(a);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(e.filter(([s,a])=>a!==void 0))}async function vr(r){if(!r)return{};let t=Object.entries(r),e=await Promise.all(t.map(async([s,a])=>[s,await os(a)]));return Object.fromEntries(e)}function ye(r){let t=new URL(r.origin+r.pathname);for(let[e,s]of r.searchParams)jt.includes(e)||t.searchParams.set(e,s);return t.searchParams.sort(),t.toString()}var Re,be,xe,oe,K,H,m,N,Q,we,_,z,wt,p,ts,q,Te,Ae,ve,Ze,M,$,et,Tt,At,vt,Pt,tt,Pe,ie,Xe,Rt,Ee,bt,Is,ss,xt,Fs,Ns,qs,$s,rs,ns,as,js,Ys,Vs,Ws,es=class{constructor(t){f(this,p);f(this,Re,null);f(this,be);f(this,xe);f(this,oe);f(this,K,new Map);f(this,H,!1);f(this,m);f(this,N,!1);f(this,Q);f(this,we);f(this,_);f(this,z,0);f(this,wt,0);f(this,q);f(this,Te);f(this,Ae);f(this,ve,Promise.resolve([]));f(this,Ze,new gt);f(this,M);f(this,$);f(this,et);f(this,Tt,1e3);f(this,At,3);f(this,vt,100);f(this,Pt,5e3);f(this,tt);f(this,Pe);f(this,ie,3);var i,l,h,u;this.options=y({subscribe:!0},t),Pr(this.options),d(this,m,Ds({offset:(i=this.options.offset)!=null?i:"-1",handle:this.options.handle})),d(this,M,new Et({onAcquired:()=>{var c;d(this,m,n(this,m).pause()),n(this,H)&&((c=n(this,_))==null||c.abort(vs))},onReleased:()=>{var c;n(this,H)&&((c=this.options.signal)!=null&&c.aborted||g(this,p,Xe).call(this).catch(()=>{}))}}));let e;if(t.columnMapper){let c=S=>{let x={};for(let[b,E]of Object.entries(S)){let R=t.columnMapper.decode(b);x[R]=E}return x};e=t.transformer?S=>t.transformer(c(S)):c}else e=t.transformer;d(this,oe,new ht(t.parser,e)),d(this,we,this.options.onError),d(this,Q,(l=this.options.log)!=null?l:"full");let s=(h=t.fetchClient)!=null?h:(...c)=>fetch(...c),a=P(y({},(u=t.backoffOptions)!=null?u:pt),{onFailedAttempt:()=>{var c,S;d(this,N,!1),(S=(c=t.backoffOptions)==null?void 0:c.onFailedAttempt)==null||S.call(c)}}),o=Ps(s,a);d(this,xe,Ms(_s(o))),d(this,be,Cs(n(this,xe))),g(this,p,js).call(this),g(this,p,Ys).call(this)}get shapeHandle(){return n(this,m).handle}get error(){return n(this,Re)}get isUpToDate(){return n(this,m).isUpToDate}get lastOffset(){return n(this,m).offset}get mode(){return n(this,Q)}subscribe(t,e=()=>{}){let s={};return n(this,K).set(s,[t,e]),n(this,H)||g(this,p,Xe).call(this),()=>{n(this,K).delete(s)}}unsubscribeAll(){var t,e;n(this,K).clear(),(t=n(this,tt))==null||t.call(this),(e=n(this,Pe))==null||e.call(this)}lastSyncedAt(){return n(this,m).lastSyncedAt}lastSynced(){return n(this,m).lastSyncedAt===void 0?1/0:Date.now()-n(this,m).lastSyncedAt}isConnected(){return n(this,N)}isLoading(){return!n(this,m).isUpToDate}hasStarted(){return n(this,H)}isPaused(){return n(this,M).isPaused}async forceDisconnectAndRefresh(){var t,e;ce(this,z)._++;try{n(this,m).isUpToDate&&!((t=n(this,_))!=null&&t.signal.aborted)&&((e=n(this,_))==null||e.abort(It)),await g(this,p,$s).call(this)}finally{ce(this,z)._--}}async requestSnapshot(t){if(n(this,Q)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,Q)} mode, as the consumer is guaranteed to observe all data`);n(this,H)||g(this,p,Xe).call(this).catch(()=>{});let e=`snapshot-${++ce(this,wt)._}`;n(this,M).acquire(e);let s=setTimeout(()=>{console.warn(`[Electric] Snapshot "${e}" has held the pause lock for 30s \u2014 possible hung request or leaked lock. Current holders: ${[...new Set([e])].join(", ")}`)},3e4);try{let{metadata:a,data:o,responseOffset:i,responseHandle:l}=await this.fetchSnapshot(t),h=o.concat([{headers:y({control:"snapshot-end"},a)},{headers:y({control:"subset-end"},t)}]);if(n(this,Ze).addSnapshot(a,new Set(o.map(u=>u.key))),g(this,p,xt).call(this,h,!1),i!==null||l!==null){let u=n(this,m).handleResponseMetadata({status:200,responseHandle:l,responseOffset:i,responseCursor:null,expiredHandle:null,now:Date.now(),maxStaleCacheRetries:n(this,ie),createCacheBuster:()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`});u.action==="accepted"?d(this,m,u.state):console.warn(`[Electric] Snapshot response metadata was not accepted by state "${n(this,m).kind}" (action: ${u.action}). Stream offset was not advanced from snapshot.`)}return{metadata:a,data:o}}finally{clearTimeout(s),n(this,M).release(e)}}async fetchSnapshot(t){var E,R,C;let s=((R=(E=t.method)!=null?E:this.options.subsetMethod)!=null?R:"GET")==="POST",a,o;if(s){let T=await g(this,p,bt).call(this,this.options.url,!0);a=T.fetchUrl,o={method:"POST",headers:P(y({},T.requestHeaders),{"Content-Type":"application/json"}),body:de(g(this,p,Ws).call(this,t))}}else{let T=await g(this,p,bt).call(this,this.options.url,!0,t);a=T.fetchUrl,o={headers:T.requestHeaders}}let i=n(this,m).handle,l;try{l=await n(this,be).call(this,a.toString(),o)}catch(T){if(T instanceof A&&T.status===409){if(i){let Z=ye(a);je.markExpired(Z,i)}let L=T.headers[ee]||`${i!=null?i:"handle"}-next`;return d(this,m,n(this,m).withHandle(L)),this.fetchSnapshot(t)}throw T}if(!l.ok)throw await A.fromResponse(l,a.toString());let h=(C=n(this,m).schema)!=null?C:Hs(l.headers,{required:!0,url:a.toString()}),{metadata:u,data:c}=await l.json(),S=n(this,oe).parseSnapshotData(c,h),x=l.headers.get(Oe)||null,b=l.headers.get(ee);return{metadata:u,data:S,responseOffset:x,responseHandle:b}}};Re=new WeakMap,be=new WeakMap,xe=new WeakMap,oe=new WeakMap,K=new WeakMap,H=new WeakMap,m=new WeakMap,N=new WeakMap,Q=new WeakMap,we=new WeakMap,_=new WeakMap,z=new WeakMap,wt=new WeakMap,p=new WeakSet,ts=function(){return n(this,z)>0},q=new WeakMap,Te=new WeakMap,Ae=new WeakMap,ve=new WeakMap,Ze=new WeakMap,M=new WeakMap,$=new WeakMap,et=new WeakMap,Tt=new WeakMap,At=new WeakMap,vt=new WeakMap,Pt=new WeakMap,tt=new WeakMap,Pe=new WeakMap,ie=new WeakMap,Xe=async function(){var t,e;d(this,H,!0);try{await g(this,p,Ee).call(this)}catch(s){if(d(this,Re,s),s instanceof Error&&d(this,m,n(this,m).toErrorState(s)),n(this,we)){let a=await n(this,we).call(this,s),o=!(s instanceof Y);if(a&&typeof a=="object"&&o){a.params&&(this.options.params=y(y({},(t=this.options.params)!=null?t:{}),a.params)),a.headers&&(this.options.headers=y(y({},(e=this.options.headers)!=null?e:{}),a.headers)),d(this,Re,null),n(this,m)instanceof ze&&d(this,m,n(this,m).retry()),d(this,H,!1),await g(this,p,Xe).call(this);return}s instanceof Error&&g(this,p,ns).call(this,s),g(this,p,Rt).call(this);return}throw s instanceof Error&&g(this,p,ns).call(this,s),g(this,p,Rt).call(this),s}g(this,p,Rt).call(this)},Rt=function(){var t,e;d(this,N,!1),(t=n(this,Ae))==null||t.call(this),(e=n(this,Pe))==null||e.call(this)},Ee=async function(){var h,u;if(n(this,M).isPaused||!this.options.subscribe&&((h=this.options.signal)!=null&&h.aborted||n(this,m).isUpToDate))return;let t=!1;n(this,m)instanceof Qe&&(t=!0,d(this,m,n(this,m).resume()));let{url:e,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=await g(this,p,bt).call(this,e,t),i=await g(this,p,Is).call(this,s),l=n(this,_);if(n(this,M).isPaused){i&&s&&s.removeEventListener("abort",i),d(this,_,void 0);return}try{await g(this,p,Fs).call(this,{fetchUrl:a,requestAbortController:l,headers:o,resumingFromPause:t})}catch(c){let S=l.signal.reason,x=l.signal.aborted&&(S===It||S===Ft);if((c instanceof A||c instanceof I)&&x)return g(this,p,Ee).call(this);if(c instanceof I)return;if(c instanceof le)return g(this,p,Ee).call(this);if(!(c instanceof A))throw c;if(c.status==409){if(n(this,m).handle){let R=ye(a);je.markExpired(R,n(this,m).handle)}let b=c.headers[ee]||`${n(this,m).handle}-next`;g(this,p,Vs).call(this,b);let E=Array.isArray(c.json)?c.json:c.json!=null?[c.json]:[];return await g(this,p,rs).call(this,E),g(this,p,Ee).call(this)}else throw c}finally{i&&s&&s.removeEventListener("abort",i),d(this,_,void 0)}return(u=n(this,Te))==null||u.call(this),g(this,p,Ee).call(this)},bt=async function(t,e,s){var u,c,S,x,b,E;let[a,o]=await Promise.all([vr(this.options.headers),this.options.params?Ar(Cr(this.options.params)):void 0]);o&&Ks(o);let i=new URL(t);if(o){if(o.table&&U(i,bs,o.table),o.where&&typeof o.where=="string"){let C=he(o.where,(u=this.options.columnMapper)==null?void 0:u.encode);U(i,xs,C)}if(o.columns){let C=await os((c=this.options.params)==null?void 0:c.columns);if(Array.isArray(C)){let T=C.map(String);this.options.columnMapper&&(T=T.map(this.options.columnMapper.encode));let L=T.map(ke).join(",");U(i,Dt,L)}else U(i,Dt,o.columns)}o.replica&&U(i,ws,o.replica),o.params&&U(i,Ts,o.params);let R=y({},o);delete R.table,delete R.where,delete R.columns,delete R.replica,delete R.params;for(let[C,T]of Object.entries(R))U(i,C,T)}if(s){if(s.whereExpr){let R=$e(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);U(i,pe,R),i.searchParams.set(qt,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let R=he(s.where,(x=this.options.columnMapper)==null?void 0:x.encode);U(i,pe,R)}if(s.params&&i.searchParams.set(Ie,de(s.params)),s.limit&&U(i,De,s.limit),s.offset&&U(i,He,s.offset),s.orderByExpr){let R=ft(s.orderByExpr,(b=this.options.columnMapper)==null?void 0:b.encode);U(i,fe,R),i.searchParams.set($t,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let R=he(s.orderBy,(E=this.options.columnMapper)==null?void 0:E.encode);U(i,fe,R)}}n(this,m).applyUrlParams(i,{isSnapshotRequest:s!==void 0,canLongPoll:!n(this,p,ts)&&!e}),i.searchParams.set(Nt,n(this,Q));let l=ye(i),h=je.getExpiredHandle(l);return h&&i.searchParams.set(Be,h),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}},Is=async function(t){var e;if(d(this,_,new AbortController),t){let s=()=>{var a;(a=n(this,_))==null||a.abort(t.reason)};return t.addEventListener("abort",s,{once:!0}),t.aborted&&((e=n(this,_))==null||e.abort(t.reason)),s}},ss=async function(t){var h,u,c;let{headers:e,status:s}=t,a=e.get(ee),o=n(this,$)?ye(n(this,$)):null,i=o?je.getExpiredHandle(o):null,l=n(this,m).handleResponseMetadata({status:s,responseHandle:a,responseOffset:e.get(Oe),responseCursor:e.get(Es),responseSchema:Hs(e),expiredHandle:i,now:Date.now(),maxStaleCacheRetries:n(this,ie),createCacheBuster:()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`});if(d(this,m,l.state),l.action==="stale-retry")throw await((h=t.body)==null?void 0:h.cancel()),l.exceededMaxRetries?new A(502,void 0,void 0,{},(c=(u=n(this,$))==null?void 0:u.toString())!=null?c:"",`CDN continues serving stale cached responses after ${n(this,ie)} retry attempts. This indicates a severe proxy/CDN misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: https://electric-sql.com/docs/guides/troubleshooting`):(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: https://electric-sql.com/docs/guides/troubleshooting Retrying with a random cache buster to bypass the stale cache (attempt ${n(this,m).staleCacheRetryCount}/${n(this,ie)}).`),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 l.action==="ignored"?(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. Ignoring the stale response and continuing with handle "${n(this,m).handle}".`),!1):!0},xt=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.`);return}if(t.length===0)return;let s=t[t.length-1],a=Ot(s),o=a?ys(s):void 0,i=n(this,m).handleMessageBatch({hasMessages:!0,hasUpToDateMessage:a,isSse:e,upToDateOffset:o,now:Date.now(),currentCursor:n(this,m).liveCacheBuster});if(d(this,m,i.state),a){if(i.suppressBatch)return;if(n(this,$)){let h=ye(n(this,$));zt.recordUpToDate(h,n(this,m).liveCacheBuster)}}let l=t.filter(h=>ue(h)?!n(this,Ze).shouldRejectMessage(h):!0);await g(this,p,rs).call(this,l)},Fs=async function(t){var s;if(d(this,$,t.fetchUrl),!n(this,m).isUpToDate&&n(this,m).canEnterReplayMode()){let a=ye(t.fetchUrl),o=zt.shouldEnterReplayMode(a);o&&d(this,m,n(this,m).enterReplayMode(o))}let e=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,m).shouldUseSse({liveSseEnabled:!!e,isRefreshing:n(this,p,ts),resumingFromPause:!!t.resumingFromPause})?(t.fetchUrl.searchParams.set(As,"true"),t.fetchUrl.searchParams.set(Ht,"true"),g(this,p,qs).call(this,t)):g(this,p,Ns).call(this,t)},Ns=async function(t){var S;let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=await n(this,be).call(this,e.toString(),{signal:s.signal,headers:a});if(d(this,N,!0),!await g(this,p,ss).call(this,o))return;let l=n(this,m).schema,u=await o.text()||"[]",c=n(this,oe).parse(u,l);if(!Array.isArray(c)){let x=(S=de(c))==null?void 0:S.slice(0,200);throw new A(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 c}: ${x}`,void 0,Object.fromEntries(o.headers.entries()),e.toString())}await g(this,p,xt).call(this,c)},qs=async function(t){let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=n(this,xe);d(this,et,Date.now());let i=P(y({},a),{Accept:"text/event-stream"}),l=!1;try{let h=[];await Wt(e.toString(),{headers:i,fetch:o,onopen:async u=>{if(d(this,N,!0),!await g(this,p,ss).call(this,u))throw l=!0,new Error("stale response ignored")},onmessage:u=>{if(u.data){let c=n(this,m).schema,S=n(this,oe).parse(u.data,c);h.push(S),Ot(S)&&(g(this,p,xt).call(this,h,!0),h=[])}},onerror:u=>{throw u},signal:s.signal})}catch(h){if(l)return;if(s.signal.aborted)throw new I;if(h instanceof A||h instanceof le||h instanceof Y)throw h}finally{let h=Date.now()-n(this,et),u=s.signal.aborted,c=n(this,m).handleSseConnectionClosed({connectionDuration:h,wasAborted:u,minConnectionDuration:n(this,Tt),maxShortConnections:n(this,At)});if(d(this,m,c.state),c.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.");else if(c.wasShortConnection){let S=Math.min(n(this,Pt),n(this,vt)*Math.pow(2,n(this,m).consecutiveShortSseConnections)),x=Math.floor(Math.random()*S);await new Promise(b=>setTimeout(b,x))}}},$s=async function(){if(n(this,M).isPaused)throw new Error("Cannot wait for next tick while PauseLock is held \u2014 this would deadlock because the request loop is paused");return n(this,q)?n(this,q):(d(this,q,new Promise((t,e)=>{d(this,Te,t),d(this,Ae,e)})),n(this,q).finally(()=>{d(this,q,void 0),d(this,Te,void 0),d(this,Ae,void 0)}),n(this,q))},rs=async function(t){return d(this,ve,n(this,ve).then(()=>Promise.all(Array.from(n(this,K).values()).map(async([e,s])=>{try{await e(t)}catch(a){queueMicrotask(()=>{throw a})}})))),n(this,ve)},ns=function(t){n(this,K).forEach(([e,s])=>{s==null||s(t)})},as=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},js=function(){if(g(this,p,as).call(this)){let t=()=>{document.hidden?n(this,M).acquire("visibility"):n(this,M).release("visibility")};document.addEventListener("visibilitychange",t),d(this,tt,()=>{document.removeEventListener("visibilitychange",t)})}},Ys=function(){if(g(this,p,as).call(this))return;let t=2e3,e=4e3,s=Date.now(),a=setInterval(()=>{let o=Date.now(),i=o-s;s=o,i>t+e&&!n(this,M).isPaused&&n(this,_)&&(ce(this,z)._++,n(this,_).abort(Ft),queueMicrotask(()=>{ce(this,z)._--}))},t);typeof a=="object"&&"unref"in a&&a.unref(),d(this,Pe,()=>{clearInterval(a)})},Vs=function(t){d(this,m,n(this,m).markMustRefetch(t)),d(this,N,!1),n(this,M).releaseAllMatching("snapshot")},Ws=function(t){var s,a,o,i;let e={};return t.whereExpr?(e.where=$e(t.whereExpr,(s=this.options.columnMapper)==null?void 0:s.encode),e.where_expr=t.whereExpr):t.where&&typeof t.where=="string"&&(e.where=he(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=ft(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=he(t.orderBy,(i=this.options.columnMapper)==null?void 0:i.encode)),e},es.Replica={FULL:"full",DEFAULT:"default"};function Hs(r,t){let e=r.get(Bt);if(!e){if(t!=null&&t.required&&(t!=null&&t.url))throw new Y(t.url,[Bt]);return{}}return JSON.parse(e)}function Ks(r){if(!r)return;let t=Object.keys(r).filter(e=>Tr.has(e));if(t.length>0)throw new it(t)}function Pr(r){if(!r.url)throw new nt;if(r.signal&&!(r.signal instanceof AbortSignal))throw new at;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new ot;Ks(r.params)}function U(r,t,e){if(!(e===void 0||e==null))if(typeof e=="string")r.searchParams.set(t,e);else if(typeof e=="object")for(let[s,a]of Object.entries(e))r.searchParams.set(`${t}[${s}]`,a);else r.searchParams.set(t,e.toString())}function Cr(r){return Array.isArray(r.params)?P(y({},r),{params:Object.fromEntries(r.params.map((t,e)=>[e+1,t]))}):r}var k,G,J,st,Ce,_e,X,v,zs,Gs,is,Ct,Js,cs,Qs=class{constructor(t){f(this,v);f(this,k,new Map);f(this,G,new Map);f(this,J,new Set);f(this,st,new Set);f(this,Ce,!1);f(this,_e,"syncing");f(this,X,!1);this.stream=t,this.stream.subscribe(g(this,v,zs).bind(this),g(this,v,Js).bind(this))}get isUpToDate(){return n(this,_e)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(t=>Array.from(t.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((t,e)=>{if(this.stream.isUpToDate)t(this.currentValue);else{let s=this.subscribe(({value:a})=>{s(),n(this,X)&&e(n(this,X)),t(a)})}})}get currentValue(){return n(this,k)}get error(){return n(this,X)}lastSyncedAt(){return this.stream.lastSyncedAt()}lastSynced(){return this.stream.lastSynced()}isLoading(){return this.stream.isLoading()}isConnected(){return this.stream.isConnected()}get mode(){return this.stream.mode}async requestSnapshot(t){let e=de(t);n(this,st).add(e),await g(this,v,is).call(this),await this.stream.requestSnapshot(t)}subscribe(t){let e={};return n(this,G).set(e,t),()=>{n(this,G).delete(e)}}unsubscribeAll(){n(this,G).clear()}get numSubscribers(){return n(this,G).size}};k=new WeakMap,G=new WeakMap,J=new WeakMap,st=new WeakMap,Ce=new WeakMap,_e=new WeakMap,X=new WeakMap,v=new WeakSet,zs=function(t){let e=!1;t.forEach(s=>{if(ue(s))if(e=g(this,v,Ct).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,k).set(s.key,s.value);break;case"update":n(this,k).set(s.key,y(y({},n(this,k).get(s.key)),s.value));break;case"delete":n(this,k).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,J).add(s.key),n(this,k).set(s.key,s.value);break;case"update":n(this,J).has(s.key)&&n(this,k).set(s.key,y(y({},n(this,k).get(s.key)),s.value));break;case"delete":n(this,J).has(s.key)&&(n(this,k).delete(s.key),n(this,J).delete(s.key));break}if(ut(s))switch(s.headers.control){case"up-to-date":e=g(this,v,Ct).call(this,"up-to-date"),n(this,Ce)&&(d(this,Ce,!1),g(this,v,Gs).call(this));break;case"must-refetch":n(this,k).clear(),n(this,J).clear(),d(this,X,!1),e=g(this,v,Ct).call(this,"syncing"),d(this,Ce,!0);break}}),e&&g(this,v,cs).call(this)},Gs=async function(){await g(this,v,is).call(this),await Promise.all(Array.from(n(this,st)).map(async t=>{try{let e=JSON.parse(t);await this.stream.requestSnapshot(e)}catch(e){}}))},is=async function(){this.stream.isUpToDate||await new Promise(t=>{let e=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),t())},s=setInterval(e,10),a=this.stream.subscribe(()=>e(),()=>e());e()})},Ct=function(t){let e=n(this,_e)!==t;return d(this,_e,t),e&&t==="up-to-date"},Js=function(t){t instanceof A&&(d(this,X,t),g(this,v,cs).call(this))},cs=function(){n(this,G).forEach(t=>{t({value:this.currentValue,rows:this.currentRows})})};export{pt as BackoffDefaults,jt as ELECTRIC_PROTOCOL_QUERY_PARAMS,A as FetchError,Qs as Shape,es as ShapeStream,gs as camelToSnake,$e as compileExpression,ft as compileOrderBy,Ss as createColumnMapper,ue as isChangeMessage,ut as isControlMessage,Lt as isVisibleInSnapshot,os as resolveValue,ir as snakeCamelMapper,kt as snakeToCamel};
5
+ For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}},pe=class extends Error{constructor(t){super(t),this.name="StaleCacheError"}};var mt=n=>Number(n),dr=n=>n==="true"||n==="t",ur=n=>BigInt(n),xs=n=>JSON.parse(n),pr=n=>n,fr={int2:mt,int4:mt,int8:ur,bool:dr,float4:mt,float8:mt,json:xs,jsonb:xs};function mr(n,t){let e=0,s=null,a="",o=!1,i=0,l;function h(c,S,w){let b=c.slice(S,w);return b=b==="NULL"?null:b,t?t(b):b}function u(c){let S=[];for(;e<c.length;e++){if(s=c[e],o)s==="\\"?a+=c[++e]:s==='"'?(S.push(t?t(a):a),a="",o=c[e+1]==='"',i=e+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++e,S.push(u(c));else if(s==="}"){o=!1,i<e&&S.push(h(c,i,e)),i=e+1;break}else s===","&&l!=="}"&&l!=='"'&&(S.push(h(c,i,e)),i=e+1);l=s}return i<e&&S.push(S.push(h(c,i,e+1))),S}return u(n)[0]}var gt=class{constructor(t,e){this.parser=y(y({},fr),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 c=a,{type:o,dims:i}=c,l=De(c,["type","dims"]),h=(S=this.parser[o])!=null?S:pr,u=Ts(h,a,t);return i&&i>0?Ts((b,E)=>mr(b,u),a,t)(e):u(e,l)}};function Ts(n,t,e){var a;let s=!((a=t.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new ft(e!=null?e:"unknown");return null}return n(o,t)}}function Be(n){return`"${n.replace(/"/g,'""')}"`}function $t(n){var l,h,u,c;let t=(h=(l=n.match(/^_+/))==null?void 0:l[0])!=null?h:"",e=n.slice(t.length),s=(c=(u=e.match(/_+$/))==null?void 0:u[0])!=null?c:"",i=(s?e.slice(0,e.length-s.length):e).toLowerCase().replace(/_+([a-z])/g,(S,w)=>w.toUpperCase());return t+i+s}function vs(n){return n.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function As(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 fe(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 l=n[a];if(l==="'"||l==='"'){let h=a,u=l;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=l=>s.some(h=>l>=h.start&&l<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,(l,h,u)=>o(u)||e.has(l.toUpperCase())||l.startsWith("$")?l:t(l))}function gr(n){if(n){let t={};for(let e of Object.keys(n))t[e]=$t(e);return As(t)}return{decode:t=>$t(t),encode:t=>vs(t)}}function He(n){return n!=null&&"key"in n}function St(n){return n!=null&&"headers"in n&&"control"in n.headers}function qt(n){return St(n)&&n.headers.control==="up-to-date"}function Cs(n){if(n.headers.control!="up-to-date")return;let t=n.headers.global_last_seen_lsn;return t?`${t}_0`:void 0}function Sr(n,t){return typeof t=="bigint"?t.toString():t}function me(n){return JSON.stringify(n,Sr)}function jt(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 Ps="electric-cursor",re="electric-handle",Ie="electric-offset",Yt="electric-schema",_s="electric-up-to-date",Vt="columns",Fe="cursor",Ne="expired_handle",ne="handle",I="live",ae="offset",Ms="table",ks="where",Us="replica",Os="params",Ls="experimental_live_sse",Wt="live_sse",Kt="force-disconnect-and-refresh",Ds="pause-stream",Qt="system-wake",Gt="log",ge="subset__where",$e="subset__limit",qe="subset__offset",Se="subset__order_by",je="subset__params",zt="subset__where_expr",Jt="subset__order_by_expr",Ye="cache-buster",Xt=[I,Wt,ne,ae,Fe,Ne,Gt,ge,$e,qe,Se,je,zt,Jt,Ye];var yr=[429],Et={initialDelay:1e3,maxDelay:32e3,multiplier:2,maxRetries:1/0};function Er(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 Bs(n,t=Et){let{initialDelay:e,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:l=1/0}=t;return async(...h)=>{var b;let u=h[0],c=h[1],S=e,w=0;for(;;)try{let E=await n(...h);if(E.ok)return E;throw await v.fromResponse(E,u.toString())}catch(E){if(i==null||i(),(b=c==null?void 0:c.signal)!=null&&b.aborted)throw new N;if(E instanceof v&&!yr.includes(E.status)&&E.status>=400&&E.status<500)throw E;{if(w++,w>l)throw o&&console.log(`Max retries reached (${w}/${l}), giving up`),E;let R=E instanceof v&&E.headers?Er(E.headers["retry-after"]):0,P=Math.random()*S,T=Math.min(P,s),L=Math.max(R,T);if(o){let te=R>0?"server+client":"client";console.log(`Retry attempt #${w} after ${L}ms (${te}, serverMin=${R}ms, clientBackoff=${T}ms)`)}await new Promise(te=>setTimeout(te,L)),S=Math.min(S*a,s)}}}}var Rr=[201,204,205];function Hs(n){return async(...t)=>{var a,o;let e=t[0],s=await n(...t);try{if(s.status<200||Rr.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 N:new v(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 br={maxChunksToPrefetch:2};function Is(n,t=br){let{maxChunksToPrefetch:e}=t,s;return async(...o)=>{let i=o[0].toString();if(Cr(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),c=es(i,u);return c&&(s=new Zt({fetchClient:n,maxPrefetchedRequests:e,url:c,requestInit:o[1]})),u}}var wr=["electric-offset","electric-handle"],xr=["electric-cursor"],Tr=["electric-schema"];function Fs(n){return async(...t)=>{let e=await n(...t);if(e.ok){let s=e.headers,a=[],o=c=>a.push(...c.filter(S=>!s.has(S))),l=t[0].toString(),h=new URL(l);if([ge,je,$e,qe,Se].some(c=>h.searchParams.has(c)))return e;if(o(wr),h.searchParams.get(I)==="true"&&o(xr),(!h.searchParams.has(I)||h.searchParams.get(I)==="false")&&o(Tr),a.length>0)throw new W(l,a)}return e}}var Ve,We,D,oe,$,ye,yt,Zt=class{constructor(t){p(this,ye);p(this,Ve);p(this,We);p(this,D,new Map);p(this,oe);p(this,$);var e;d(this,Ve,(e=t.fetchClient)!=null?e:(...s)=>fetch(...s)),d(this,We,t.maxPrefetchedRequests),d(this,oe,t.url.toString()),d(this,$,r(this,oe)),g(this,ye,yt).call(this,t.url,t.requestInit)}abort(){r(this,D).forEach(([t,e])=>e.abort()),r(this,D).clear()}consume(...t){let e=t[0].toString(),s=r(this,D).get(e);if(!s||e!==r(this,oe))return;let[a,o]=s;if(o.signal.aborted){r(this,D).delete(e);return}return r(this,D).delete(e),a.then(i=>{let l=es(e,i);d(this,oe,l),r(this,$)&&!r(this,D).has(r(this,$))&&g(this,ye,yt).call(this,r(this,$),t[1])}).catch(()=>{}),a}};Ve=new WeakMap,We=new WeakMap,D=new WeakMap,oe=new WeakMap,$=new WeakMap,ye=new WeakSet,yt=function(...t){var a,o;let e=t[0].toString();if(r(this,D).size>=r(this,We))return;let s=new AbortController;try{let{signal:i,cleanup:l}=vr(s,(a=t[1])==null?void 0:a.signal),h=r(this,Ve).call(this,e,C(y({},(o=t[1])!=null?o:{}),{signal:i}));r(this,D).set(e,[h,s]),h.then(u=>{if(!u.ok||s.signal.aborted)return;let c=es(e,u);if(!c||c===e){d(this,$,void 0);return}return d(this,$,c),g(this,ye,yt).call(this,c,t[1])}).catch(()=>{}).finally(l)}catch(i){}};function es(n,t){let e=t.headers.get(re),s=t.headers.get(Ie),a=t.headers.has(_s);if(!e||!s||a)return;let o=new URL(n);if(o.searchParams.has(I))return;let i=o.searchParams.get(Ne);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(ne,e),o.searchParams.set(ae,s),o.searchParams.sort(),o.toString()}function vr(n,t){let e=Ar;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 Ar(){}function Cr(n,t){return t!=null&&t.method?t.method.toUpperCase():typeof Request!="undefined"&&n instanceof Request?n.method.toUpperCase():"GET"}function Ke(n,t){switch(n.type){case"ref":{let e=t?t(n.column):n.column;return Be(e)}case"val":return`$${n.paramIndex}`;case"func":return Pr(n,t);default:{let e=n;throw new Error(`Unknown expression type: ${JSON.stringify(e)}`)}}}function Pr(n,t){let e=n.args.map(s=>Ke(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 Rt(n,t){return n.map(e=>{let s=t?t(e.column):e.column,a=Be(s);return e.direction==="desc"&&(a+=" DESC"),e.nulls==="first"&&(a+=" NULLS FIRST"),e.nulls==="last"&&(a+=" NULLS LAST"),a}).join(", ")}async function $s(n,t){let e=n.getReader(),s;for(;!(s=await e.read()).done;)t(s.value)}function qs(n){let t,e,s,a=!1;return function(i){t===void 0?(t=i,e=0,s=-1):t=_r(t,i);let l=t.length,h=0;for(;e<l;){a&&(t[e]===10&&(h=++e),a=!1);let u=-1;for(;e<l&&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===l?t=void 0:h!==0&&(t=t.subarray(h),e-=h)}}function js(n,t,e){let s=Ns(),a=new TextDecoder;return function(i,l){if(i.length===0)e==null||e(s),s=Ns();else if(l>0){let h=a.decode(i.subarray(0,l)),u=l+(i[l+1]===32?2:1),c=a.decode(i.subarray(u));switch(h){case"data":s.data=s.data?s.data+`
6
+ `+c:c;break;case"event":s.event=c;break;case"id":n(s.id=c);break;case"retry":let S=parseInt(c,10);isNaN(S)||t(s.retry=S);break}}}}function _r(n,t){let e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function Ns(){return{data:"",event:"",id:"",retry:void 0}}var Mr=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},bt="text/event-stream",kr=1e3,Ys="last-event-id";function ts(n,t){var{signal:e,headers:s,onopen:a,onmessage:o,onclose:i,onerror:l,openWhenHidden:h,fetch:u}=t,c=Mr(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((S,w)=>{let b=Object.assign({},s);b.accept||(b.accept=bt);let E;function R(){E.abort(),typeof document!="undefined"&&!document.hidden&&It()}typeof document!="undefined"&&!h&&document.addEventListener("visibilitychange",R);let P=kr,T=0;function L(){typeof document!="undefined"&&document.removeEventListener("visibilitychange",R),clearTimeout(T),E.abort()}e==null||e.addEventListener("abort",()=>{L()});let te=u!=null?u:window.fetch,ir=a!=null?a:Ur;async function It(){var Ft;E=new AbortController;let ys=e.aborted?e:E.signal;try{let Le=await te(n,Object.assign(Object.assign({},c),{headers:b,signal:ys}));await ir(Le),await $s(Le.body,qs(js(V=>{V?b[Ys]=V:delete b[Ys]},V=>{P=V},o))),i==null||i(),L(),S()}catch(Le){if(ys.aborted)L(),w(Le);else if(!E.signal.aborted)try{let V=(Ft=l==null?void 0:l(Le))!==null&&Ft!==void 0?Ft:P;clearTimeout(T),T=setTimeout(It,V)}catch(V){L(),w(V)}}}It()})}function Ur(n){let t=n.headers.get("content-type");if(!(t!=null&&t.startsWith(bt)))throw new Error(`Expected content-type to be ${bt}, Actual: ${t}`)}var ss=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()}},ie=new ss;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()}},Qe=new rs;var wt=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(t,e){var o,i,l,h;this.activeSnapshots.set(t.snapshot_mark,{xmin:BigInt(t.xmin),xmax:BigInt(t.xmax),xip_list:t.xip_list.map(BigInt),keys:e});let s=(i=(o=this.xmaxSnapshots.get(BigInt(t.xmax)))==null?void 0:o.add(t.snapshot_mark))!=null?i:new Set([t.snapshot_mark]);this.xmaxSnapshots.set(BigInt(t.xmax),s);let a=(h=(l=this.snapshotsByDatabaseLsn.get(BigInt(t.database_lsn)))==null?void 0:l.add(t.snapshot_mark))!=null?h:new Set([t.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(t.database_lsn),a)}removeSnapshot(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)&&jt(s,a))}lastSeenUpdate(t){for(let[e,s]of this.snapshotsByDatabaseLsn.entries())if(e<=t)for(let a of s)this.removeSnapshot(a)}};var Ge=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 Ze(this)}toErrorState(t){return new et(this,t)}markMustRefetch(t){return new xt({handle:t,offset:"-1",liveCacheBuster:"",lastSyncedAt:this.lastSyncedAt,schema:void 0})}},x,ze=class extends Ge{constructor(e){super();p(this,x);d(this,x,e)}get handle(){return r(this,x).handle}get offset(){return r(this,x).offset}get schema(){return r(this,x).schema}get liveCacheBuster(){return r(this,x).liveCacheBuster}get lastSyncedAt(){return r(this,x).lastSyncedAt}get currentFields(){return r(this,x)}applyUrlParams(e,s){e.searchParams.set(ae,r(this,x).offset),r(this,x).handle&&e.searchParams.set(ne,r(this,x).handle)}parseResponseFields(e){var u,c,S;let s=e.responseHandle,a=s&&s!==e.expiredHandle?s:r(this,x).handle,o=(u=e.responseOffset)!=null?u:r(this,x).offset,i=(c=e.responseCursor)!=null?c:r(this,x).liveCacheBuster,l=(S=r(this,x).schema)!=null?S:e.responseSchema,h=e.status===204?e.now:r(this,x).lastSyncedAt;return{handle:a,offset:o,schema:l,liveCacheBuster:i,lastSyncedAt:h}}checkStaleResponse(e){let s=e.responseHandle,a=e.expiredHandle;if(!s||s!==a)return null;if(r(this,x).handle===void 0||r(this,x).handle===a){let o=this.staleCacheRetryCount+1;return{action:"stale-retry",state:new as(C(y({},this.currentFields),{staleCacheBuster:e.createCacheBuster(),staleCacheRetryCount:o})),exceededMaxRetries:o>e.maxStaleCacheRetries}}return{action:"ignored",state:this}}handleMessageBatch(e){if(!e.hasMessages||!e.hasUpToDateMessage)return{state:this,suppressBatch:!1,becameUpToDate:!1};let s=r(this,x).offset;e.isSse&&e.upToDateOffset&&(s=e.upToDateOffset);let a={handle:r(this,x).handle,offset:s,schema:r(this,x).schema,liveCacheBuster:r(this,x).liveCacheBuster,lastSyncedAt:e.now};return this.onUpToDate(a,e)}onUpToDate(e,s){return{state:new Xe(e),suppressBatch:!1,becameUpToDate:!0}}};x=new WeakMap;var Je=class extends ze{handleResponseMetadata(t){let e=this.checkStaleResponse(t);if(e)return e;let s=this.parseResponseFields(t);return t.status===204?{action:"accepted",state:new Xe(s,{sseFallbackToLongPolling:!0})}:{action:"accepted",state:new ns(s)}}canEnterReplayMode(){return!0}enterReplayMode(t){return new os(C(y({},this.currentFields),{replayCursor:t}))}},xt=class n extends Je{constructor(e){super(e);this.kind="initial"}withHandle(e){return new n(C(y({},this.currentFields),{handle:e}))}},ns=class n extends Je{constructor(e){super(e);this.kind="syncing"}withHandle(e){return new n(C(y({},this.currentFields),{handle:e}))}},ce,Re,is=class is extends Je{constructor(e){let i=e,{staleCacheBuster:s,staleCacheRetryCount:a}=i,o=De(i,["staleCacheBuster","staleCacheRetryCount"]);super(o);this.kind="stale-retry";p(this,ce);p(this,Re);d(this,ce,s),d(this,Re,a)}get staleCacheBuster(){return r(this,ce)}get staleCacheRetryCount(){return r(this,Re)}canEnterReplayMode(){return!1}withHandle(e){return new is(C(y({},this.currentFields),{handle:e,staleCacheBuster:r(this,ce),staleCacheRetryCount:r(this,Re)}))}applyUrlParams(e,s){super.applyUrlParams(e,s),e.searchParams.set(Ye,r(this,ce))}};ce=new WeakMap,Re=new WeakMap;var as=is,le,K,Ee=class Ee extends ze{constructor(e,s){var a,o;super(e);this.kind="live";p(this,le);p(this,K);d(this,le,(a=s==null?void 0:s.consecutiveShortSseConnections)!=null?a:0),d(this,K,(o=s==null?void 0:s.sseFallbackToLongPolling)!=null?o:!1)}get isUpToDate(){return!0}get consecutiveShortSseConnections(){return r(this,le)}get sseFallbackToLongPolling(){return r(this,K)}withHandle(e){return new Ee(C(y({},this.currentFields),{handle:e}),this.sseState)}applyUrlParams(e,s){super.applyUrlParams(e,s),s.isSnapshotRequest||(e.searchParams.set(Fe,this.liveCacheBuster),s.canLongPoll&&e.searchParams.set(I,"true"))}get sseState(){return{consecutiveShortSseConnections:r(this,le),sseFallbackToLongPolling:r(this,K)}}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new Ee(a,this.sseState)}}onUpToDate(e,s){return{state:new Ee(e,this.sseState),suppressBatch:!1,becameUpToDate:!0}}shouldUseSse(e){return e.liveSseEnabled&&!e.isRefreshing&&!e.resumingFromPause&&!r(this,K)}handleSseConnectionClosed(e){let s=r(this,le),a=r(this,K),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 Ee(this.currentFields,{consecutiveShortSseConnections:s,sseFallbackToLongPolling:a}),fellBackToLongPolling:o,wasShortConnection:i}}};le=new WeakMap,K=new WeakMap;var Xe=Ee,Q,Tt=class Tt extends ze{constructor(e){let o=e,{replayCursor:s}=o,a=De(o,["replayCursor"]);super(a);this.kind="replaying";p(this,Q);d(this,Q,s)}get replayCursor(){return r(this,Q)}withHandle(e){return new Tt(C(y({},this.currentFields),{handle:e,replayCursor:r(this,Q)}))}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new Tt(C(y({},a),{replayCursor:r(this,Q)}))}}onUpToDate(e,s){let a=!s.isSse&&r(this,Q)===s.currentCursor;return{state:new Xe(e),suppressBatch:a,becameUpToDate:!0}}};Q=new WeakMap;var os=Tt,Ze=class n extends Ge{constructor(e){super();this.kind="paused";this.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);return s.action==="accepted"?{action:"accepted",state:new n(s.state)}:s}withHandle(e){return new n(this.previousState.withHandle(e))}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}pause(){return this}resume(){return this.previousState}},et=class n extends Ge{constructor(e,s){super();this.kind="error";this.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}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 Vs(n){return new xt({handle:n.handle,offset:n.offset,liveCacheBuster:"",lastSyncedAt:void 0,schema:void 0})}var O,tt,st,vt=class{constructor(t){p(this,O,new Set);p(this,tt);p(this,st);d(this,tt,t.onAcquired),d(this,st,t.onReleased)}acquire(t){if(r(this,O).has(t)){console.warn(`[Electric] PauseLock: "${t}" already held \u2014 ignoring duplicate acquire`);return}let e=r(this,O).size===0;r(this,O).add(t),e&&r(this,tt).call(this)}release(t){if(!r(this,O).delete(t)){console.warn(`[Electric] PauseLock: "${t}" not held \u2014 ignoring release (possible acquire/release mismatch)`);return}r(this,O).size===0&&r(this,st).call(this)}get isPaused(){return r(this,O).size>0}isHeldBy(t){return r(this,O).has(t)}releaseAllMatching(t){for(let e of r(this,O))e.startsWith(t)&&r(this,O).delete(e)}};O=new WeakMap,tt=new WeakMap,st=new WeakMap;var Or=new Set([Fe,ne,I,ae,Ye]),At="https://electric-sql.com/docs/guides/troubleshooting";async function ms(n){return typeof n=="function"?n():n}async function Lr(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 ms(a);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(e.filter(([s,a])=>a!==void 0))}async function Dr(n){if(!n)return{};let t=Object.entries(n),e=await Promise.all(t.map(async([s,a])=>[s,await ms(a)]));return Object.fromEntries(e)}function he(n){let t=new URL(n.origin+n.pathname);for(let[e,s]of n.searchParams)Xt.includes(e)||t.searchParams.set(e,s);return t.searchParams.sort(),t.toString()}var we,xe,Te,de,G,F,m,q,z,ve,_,J,Mt,f,ls,j,Ae,Ce,Pe,nt,M,B,at,kt,Ut,Ot,Lt,ot,_e,ue,H,Me,ke,Dt,Bt,Y,it,rt,Ct,be,Ks,Pt,Qs,hs,_t,Gs,zs,Js,Xs,ds,us,ps,Zs,er,fs,tr,cs=class{constructor(t){p(this,f);p(this,we,null);p(this,xe);p(this,Te);p(this,de);p(this,G,new Map);p(this,F,!1);p(this,m);p(this,q,!1);p(this,z);p(this,ve);p(this,_);p(this,J,0);p(this,Mt,0);p(this,j);p(this,Ae);p(this,Ce);p(this,Pe,Promise.resolve([]));p(this,nt,new wt);p(this,M);p(this,B);p(this,at);p(this,kt,1e3);p(this,Ut,3);p(this,Ot,100);p(this,Lt,5e3);p(this,ot);p(this,_e);p(this,ue,3);p(this,H,[]);p(this,Me,500);p(this,ke,5);p(this,Dt,100);p(this,Bt,5e3);p(this,Y,0);p(this,it,5);var i,l,h,u;this.options=y({subscribe:!0},t),Br(this.options),d(this,m,Vs({offset:(i=this.options.offset)!=null?i:"-1",handle:this.options.handle})),d(this,M,new vt({onAcquired:()=>{var c;d(this,m,r(this,m).pause()),r(this,F)&&((c=r(this,_))==null||c.abort(Ds))},onReleased:()=>{var c;r(this,F)&&((c=this.options.signal)!=null&&c.aborted||g(this,f,rt).call(this).catch(()=>{}))}}));let e;if(t.columnMapper){let c=S=>{let w={};for(let[b,E]of Object.entries(S)){let R=t.columnMapper.decode(b);w[R]=E}return w};e=t.transformer?S=>t.transformer(c(S)):c}else e=t.transformer;d(this,de,new gt(t.parser,e)),d(this,ve,this.options.onError),d(this,z,(l=this.options.log)!=null?l:"full");let s=(h=t.fetchClient)!=null?h:(...c)=>fetch(...c),a=C(y({},(u=t.backoffOptions)!=null?u:Et),{onFailedAttempt:()=>{var c,S;d(this,q,!1),(S=(c=t.backoffOptions)==null?void 0:c.onFailedAttempt)==null||S.call(c)}}),o=Bs(s,a);d(this,Te,Fs(Is(o))),d(this,xe,Hs(r(this,Te))),g(this,f,Zs).call(this),g(this,f,er).call(this)}get shapeHandle(){return r(this,m).handle}get error(){return r(this,we)}get isUpToDate(){return r(this,m).isUpToDate}get lastOffset(){return r(this,m).offset}get mode(){return r(this,z)}subscribe(t,e=()=>{}){let s={};return r(this,G).set(s,[t,e]),r(this,F)||g(this,f,rt).call(this),()=>{r(this,G).delete(s)}}unsubscribeAll(){var t,e;r(this,G).clear(),(t=r(this,ot))==null||t.call(this),(e=r(this,_e))==null||e.call(this)}lastSyncedAt(){return r(this,m).lastSyncedAt}lastSynced(){return r(this,m).lastSyncedAt===void 0?1/0:Date.now()-r(this,m).lastSyncedAt}isConnected(){return r(this,q)}isLoading(){return!r(this,m).isUpToDate}hasStarted(){return r(this,F)}isPaused(){return r(this,M).isPaused}async forceDisconnectAndRefresh(){var t,e;se(this,J)._++;try{r(this,m).isUpToDate&&!((t=r(this,_))!=null&&t.signal.aborted)&&((e=r(this,_))==null||e.abort(Kt)),await g(this,f,Xs).call(this)}finally{se(this,J)._--}}async requestSnapshot(t){if(r(this,z)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,z)} mode, as the consumer is guaranteed to observe all data`);r(this,F)||g(this,f,rt).call(this).catch(()=>{});let e=`snapshot-${++se(this,Mt)._}`;r(this,M).acquire(e);let s=setTimeout(()=>{console.warn(`[Electric] Snapshot "${e}" has held the pause lock for 30s \u2014 possible hung request or leaked lock. Current holders: ${[...new Set([e])].join(", ")}`)},3e4);try{let{metadata:a,data:o,responseOffset:i,responseHandle:l}=await this.fetchSnapshot(t),h=o.concat([{headers:y({control:"snapshot-end"},a)},{headers:y({control:"subset-end"},t)}]);if(r(this,nt).addSnapshot(a,new Set(o.map(u=>u.key))),g(this,f,_t).call(this,h,!1),i!==null||l!==null){let u=r(this,m).handleResponseMetadata({status:200,responseHandle:l,responseOffset:i,responseCursor:null,expiredHandle:null,now:Date.now(),maxStaleCacheRetries:r(this,ue),createCacheBuster:()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`});u.action==="accepted"?d(this,m,u.state):console.warn(`[Electric] Snapshot response metadata was not accepted by state "${r(this,m).kind}" (action: ${u.action}). Stream offset was not advanced from snapshot.`)}return{metadata:a,data:o}}finally{clearTimeout(s),r(this,M).release(e)}}async fetchSnapshot(t){var E,R,P;let s=((R=(E=t.method)!=null?E:this.options.subsetMethod)!=null?R:"GET")==="POST",a,o;if(s){let T=await g(this,f,Pt).call(this,this.options.url,!0);a=T.fetchUrl,o={method:"POST",headers:C(y({},T.requestHeaders),{"Content-Type":"application/json"}),body:me(g(this,f,tr).call(this,t))}}else{let T=await g(this,f,Pt).call(this,this.options.url,!0,t);a=T.fetchUrl,o={headers:T.requestHeaders}}let i=r(this,m).handle,l;try{l=await r(this,xe).call(this,a.toString(),o)}catch(T){if(T instanceof v&&T.status===409){if(i){let te=he(a);ie.markExpired(te,i)}let L=T.headers[re]||`${i!=null?i:"handle"}-next`;return d(this,m,r(this,m).withHandle(L)),this.fetchSnapshot(t)}throw T}if(!l.ok)throw await v.fromResponse(l,a.toString());let h=(P=r(this,m).schema)!=null?P:Ws(l.headers,{required:!0,url:a.toString()}),{metadata:u,data:c}=await l.json(),S=r(this,de).parseSnapshotData(c,h),w=l.headers.get(Ie)||null,b=l.headers.get(re);return{metadata:u,data:S,responseOffset:w,responseHandle:b}}};we=new WeakMap,xe=new WeakMap,Te=new WeakMap,de=new WeakMap,G=new WeakMap,F=new WeakMap,m=new WeakMap,q=new WeakMap,z=new WeakMap,ve=new WeakMap,_=new WeakMap,J=new WeakMap,Mt=new WeakMap,f=new WeakSet,ls=function(){return r(this,J)>0},j=new WeakMap,Ae=new WeakMap,Ce=new WeakMap,Pe=new WeakMap,nt=new WeakMap,M=new WeakMap,B=new WeakMap,at=new WeakMap,kt=new WeakMap,Ut=new WeakMap,Ot=new WeakMap,Lt=new WeakMap,ot=new WeakMap,_e=new WeakMap,ue=new WeakMap,H=new WeakMap,Me=new WeakMap,ke=new WeakMap,Dt=new WeakMap,Bt=new WeakMap,Y=new WeakMap,it=new WeakMap,rt=async function(){var t,e;d(this,F,!0);try{await g(this,f,be).call(this)}catch(s){if(d(this,we,s),s instanceof Error&&d(this,m,r(this,m).toErrorState(s)),r(this,ve)){let a=await r(this,ve).call(this,s),o=!(s instanceof W);if(a&&typeof a=="object"&&o){a.params&&(this.options.params=y(y({},(t=this.options.params)!=null?t:{}),a.params)),a.headers&&(this.options.headers=y(y({},(e=this.options.headers)!=null?e:{}),a.headers)),d(this,we,null),r(this,m)instanceof et&&d(this,m,r(this,m).retry()),d(this,Y,0),d(this,H,[]),d(this,F,!1),await g(this,f,rt).call(this);return}s instanceof Error&&g(this,f,us).call(this,s),g(this,f,Ct).call(this);return}throw s instanceof Error&&g(this,f,us).call(this,s),g(this,f,Ct).call(this),s}g(this,f,Ct).call(this)},Ct=function(){var t,e;d(this,q,!1),(t=r(this,Ce))==null||t.call(this),(e=r(this,_e))==null||e.call(this)},be=async function(){var h,u;if(r(this,M).isPaused||!this.options.subscribe&&((h=this.options.signal)!=null&&h.aborted||r(this,m).isUpToDate))return;r(this,m).isUpToDate?(d(this,Y,0),d(this,H,[])):await g(this,f,Ks).call(this);let t=!1;r(this,m)instanceof Ze&&(t=!0,d(this,m,r(this,m).resume()));let{url:e,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=await g(this,f,Pt).call(this,e,t),i=await g(this,f,Qs).call(this,s),l=r(this,_);if(r(this,M).isPaused){i&&s&&s.removeEventListener("abort",i),d(this,_,void 0);return}try{await g(this,f,Gs).call(this,{fetchUrl:a,requestAbortController:l,headers:o,resumingFromPause:t})}catch(c){let S=l.signal.reason,w=l.signal.aborted&&(S===Kt||S===Qt);if((c instanceof v||c instanceof N)&&w)return g(this,f,be).call(this);if(c instanceof N)return;if(c instanceof pe)return g(this,f,be).call(this);if(!(c instanceof v))throw c;if(c.status==409){if(r(this,m).handle){let R=he(a);ie.markExpired(R,r(this,m).handle)}let b=c.headers[re]||`${r(this,m).handle}-next`;g(this,f,fs).call(this,b);let E=Array.isArray(c.json)?c.json:c.json!=null?[c.json]:[];return await g(this,f,ds).call(this,E),g(this,f,be).call(this)}else throw c}finally{i&&s&&s.removeEventListener("abort",i),d(this,_,void 0)}return(u=r(this,Ae))==null||u.call(this),g(this,f,be).call(this)},Ks=async function(){let t=Date.now(),e=r(this,m).offset;if(d(this,H,r(this,H).filter(i=>t-i.timestamp<r(this,Me))),r(this,H).push({timestamp:t,offset:e}),r(this,H).filter(i=>i.offset===e).length<r(this,ke))return;if(se(this,Y)._++,r(this,Y)>=r(this,it))throw new v(502,void 0,void 0,{},this.options.url,`Client is stuck in a fast retry loop (${r(this,ke)} requests in ${r(this,Me)}ms at the same offset, repeated ${r(this,it)} times). Client-side caches were cleared automatically on first detection, but the loop persists. This usually indicates a proxy or CDN misconfiguration. Common causes:
7
+ - Proxy is not including query parameters (handle, offset) in its cache key
8
+ - CDN is serving stale 409 responses
9
+ - Proxy is stripping required Electric headers from responses
10
+ For more information visit the troubleshooting guide: ${At}`);if(r(this,Y)===1){if(console.warn(`[Electric] Detected fast retry loop (${r(this,ke)} requests in ${r(this,Me)}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: ${At}`),r(this,B)){let i=he(r(this,B));ie.delete(i),Qe.delete(i)}else ie.clear(),Qe.clear();g(this,f,fs).call(this),d(this,H,[]);return}let a=Math.min(r(this,Bt),r(this,Dt)*Math.pow(2,r(this,Y))),o=Math.floor(Math.random()*a);await new Promise(i=>setTimeout(i,o)),d(this,H,[])},Pt=async function(t,e,s){var u,c,S,w,b,E;let[a,o]=await Promise.all([Dr(this.options.headers),this.options.params?Lr(Hr(this.options.params)):void 0]);o&&sr(o);let i=new URL(t);if(o){if(o.table&&k(i,Ms,o.table),o.where&&typeof o.where=="string"){let P=fe(o.where,(u=this.options.columnMapper)==null?void 0:u.encode);k(i,ks,P)}if(o.columns){let P=await ms((c=this.options.params)==null?void 0:c.columns);if(Array.isArray(P)){let T=P.map(String);this.options.columnMapper&&(T=T.map(this.options.columnMapper.encode));let L=T.map(Be).join(",");k(i,Vt,L)}else k(i,Vt,o.columns)}o.replica&&k(i,Us,o.replica),o.params&&k(i,Os,o.params);let R=y({},o);delete R.table,delete R.where,delete R.columns,delete R.replica,delete R.params;for(let[P,T]of Object.entries(R))k(i,P,T)}if(s){if(s.whereExpr){let R=Ke(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);k(i,ge,R),i.searchParams.set(zt,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let R=fe(s.where,(w=this.options.columnMapper)==null?void 0:w.encode);k(i,ge,R)}if(s.params&&i.searchParams.set(je,me(s.params)),s.limit&&k(i,$e,s.limit),s.offset&&k(i,qe,s.offset),s.orderByExpr){let R=Rt(s.orderByExpr,(b=this.options.columnMapper)==null?void 0:b.encode);k(i,Se,R),i.searchParams.set(Jt,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let R=fe(s.orderBy,(E=this.options.columnMapper)==null?void 0:E.encode);k(i,Se,R)}}r(this,m).applyUrlParams(i,{isSnapshotRequest:s!==void 0,canLongPoll:!r(this,f,ls)&&!e}),i.searchParams.set(Gt,r(this,z));let l=he(i),h=ie.getExpiredHandle(l);return h&&i.searchParams.set(Ne,h),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}},Qs=async function(t){var e;if(d(this,_,new AbortController),t){let s=()=>{var a;(a=r(this,_))==null||a.abort(t.reason)};return t.addEventListener("abort",s,{once:!0}),t.aborted&&((e=r(this,_))==null||e.abort(t.reason)),s}},hs=async function(t){var h,u,c;let{headers:e,status:s}=t,a=e.get(re),o=r(this,B)?he(r(this,B)):null,i=o?ie.getExpiredHandle(o):null,l=r(this,m).handleResponseMetadata({status:s,responseHandle:a,responseOffset:e.get(Ie),responseCursor:e.get(Ps),responseSchema:Ws(e),expiredHandle:i,now:Date.now(),maxStaleCacheRetries:r(this,ue),createCacheBuster:()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`});if(d(this,m,l.state),l.action==="stale-retry")throw await((h=t.body)==null?void 0:h.cancel()),l.exceededMaxRetries?new v(502,void 0,void 0,{},(c=(u=r(this,B))==null?void 0:u.toString())!=null?c:"",`CDN continues serving stale cached responses after ${r(this,ue)} 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: ${At}`):(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: ${At} Retrying with a random cache buster to bypass the stale cache (attempt ${r(this,m).staleCacheRetryCount}/${r(this,ue)}).`),new pe(`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 l.action==="ignored"?(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. Ignoring the stale response and continuing with handle "${r(this,m).handle}".`),!1):!0},_t=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.`);return}if(t.length===0)return;let s=t[t.length-1],a=qt(s),o=a?Cs(s):void 0,i=r(this,m).handleMessageBatch({hasMessages:!0,hasUpToDateMessage:a,isSse:e,upToDateOffset:o,now:Date.now(),currentCursor:r(this,m).liveCacheBuster});if(d(this,m,i.state),a){if(i.suppressBatch)return;if(r(this,B)){let h=he(r(this,B));Qe.recordUpToDate(h,r(this,m).liveCacheBuster)}}let l=t.filter(h=>He(h)?!r(this,nt).shouldRejectMessage(h):!0);await g(this,f,ds).call(this,l)},Gs=async function(t){var s;if(d(this,B,t.fetchUrl),!r(this,m).isUpToDate&&r(this,m).canEnterReplayMode()){let a=he(t.fetchUrl),o=Qe.shouldEnterReplayMode(a);o&&d(this,m,r(this,m).enterReplayMode(o))}let e=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return r(this,m).shouldUseSse({liveSseEnabled:!!e,isRefreshing:r(this,f,ls),resumingFromPause:!!t.resumingFromPause})?(t.fetchUrl.searchParams.set(Ls,"true"),t.fetchUrl.searchParams.set(Wt,"true"),g(this,f,Js).call(this,t)):g(this,f,zs).call(this,t)},zs=async function(t){var S;let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=await r(this,xe).call(this,e.toString(),{signal:s.signal,headers:a});if(d(this,q,!0),!await g(this,f,hs).call(this,o))return;let l=r(this,m).schema,u=await o.text()||"[]",c=r(this,de).parse(u,l);if(!Array.isArray(c)){let w=(S=me(c))==null?void 0:S.slice(0,200);throw new v(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 c}: ${w}`,void 0,Object.fromEntries(o.headers.entries()),e.toString())}await g(this,f,_t).call(this,c)},Js=async function(t){let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=r(this,Te);d(this,at,Date.now());let i=C(y({},a),{Accept:"text/event-stream"}),l=!1;try{let h=[];await ts(e.toString(),{headers:i,fetch:o,onopen:async u=>{if(d(this,q,!0),!await g(this,f,hs).call(this,u))throw l=!0,new Error("stale response ignored")},onmessage:u=>{if(u.data){let c=r(this,m).schema,S=r(this,de).parse(u.data,c);h.push(S),qt(S)&&(g(this,f,_t).call(this,h,!0),h=[])}},onerror:u=>{throw u},signal:s.signal})}catch(h){if(l)return;if(s.signal.aborted)throw new N;if(h instanceof v||h instanceof pe||h instanceof W)throw h}finally{let h=Date.now()-r(this,at),u=s.signal.aborted,c=r(this,m).handleSseConnectionClosed({connectionDuration:h,wasAborted:u,minConnectionDuration:r(this,kt),maxShortConnections:r(this,Ut)});if(d(this,m,c.state),c.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.");else if(c.wasShortConnection){let S=Math.min(r(this,Lt),r(this,Ot)*Math.pow(2,r(this,m).consecutiveShortSseConnections)),w=Math.floor(Math.random()*S);await new Promise(b=>setTimeout(b,w))}}},Xs=async function(){if(r(this,M).isPaused)throw new Error("Cannot wait for next tick while PauseLock is held \u2014 this would deadlock because the request loop is paused");return r(this,j)?r(this,j):(d(this,j,new Promise((t,e)=>{d(this,Ae,t),d(this,Ce,e)})),r(this,j).finally(()=>{d(this,j,void 0),d(this,Ae,void 0),d(this,Ce,void 0)}),r(this,j))},ds=async function(t){return d(this,Pe,r(this,Pe).then(()=>Promise.all(Array.from(r(this,G).values()).map(async([e,s])=>{try{await e(t)}catch(a){queueMicrotask(()=>{throw a})}})))),r(this,Pe)},us=function(t){r(this,G).forEach(([e,s])=>{s==null||s(t)})},ps=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},Zs=function(){if(g(this,f,ps).call(this)){let t=()=>{document.hidden?r(this,M).acquire("visibility"):r(this,M).release("visibility")};document.addEventListener("visibilitychange",t),d(this,ot,()=>{document.removeEventListener("visibilitychange",t)})}},er=function(){if(g(this,f,ps).call(this))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,M).isPaused&&r(this,_)&&(se(this,J)._++,r(this,_).abort(Qt),queueMicrotask(()=>{se(this,J)._--}))},t);typeof a=="object"&&"unref"in a&&a.unref(),d(this,_e,()=>{clearInterval(a)})},fs=function(t){d(this,m,r(this,m).markMustRefetch(t)),d(this,q,!1),r(this,M).releaseAllMatching("snapshot")},tr=function(t){var s,a,o,i;let e={};return t.whereExpr?(e.where=Ke(t.whereExpr,(s=this.options.columnMapper)==null?void 0:s.encode),e.where_expr=t.whereExpr):t.where&&typeof t.where=="string"&&(e.where=fe(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=Rt(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=fe(t.orderBy,(i=this.options.columnMapper)==null?void 0:i.encode)),e},cs.Replica={FULL:"full",DEFAULT:"default"};function Ws(n,t){let e=n.get(Yt);if(!e){if(t!=null&&t.required&&(t!=null&&t.url))throw new W(t.url,[Yt]);return{}}return JSON.parse(e)}function sr(n){if(!n)return;let t=Object.keys(n).filter(e=>Or.has(e));if(t.length>0)throw new pt(t)}function Br(n){if(!n.url)throw new ht;if(n.signal&&!(n.signal instanceof AbortSignal))throw new dt;if(n.offset!==void 0&&n.offset!=="-1"&&n.offset!=="now"&&!n.handle)throw new ut;sr(n.params)}function k(n,t,e){if(!(e===void 0||e==null))if(typeof e=="string")n.searchParams.set(t,e);else if(typeof e=="object")for(let[s,a]of Object.entries(e))n.searchParams.set(`${t}[${s}]`,a);else n.searchParams.set(t,e.toString())}function Hr(n){return Array.isArray(n.params)?C(y({},n),{params:Object.fromEntries(n.params.map((t,e)=>[e+1,t]))}):n}var U,X,Z,ct,Ue,Oe,ee,A,nr,ar,gs,Ht,or,Ss,rr=class{constructor(t){p(this,A);p(this,U,new Map);p(this,X,new Map);p(this,Z,new Set);p(this,ct,new Set);p(this,Ue,!1);p(this,Oe,"syncing");p(this,ee,!1);this.stream=t,this.stream.subscribe(g(this,A,nr).bind(this),g(this,A,or).bind(this))}get isUpToDate(){return r(this,Oe)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(t=>Array.from(t.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((t,e)=>{if(this.stream.isUpToDate)t(this.currentValue);else{let s=this.subscribe(({value:a})=>{s(),r(this,ee)&&e(r(this,ee)),t(a)})}})}get currentValue(){return r(this,U)}get error(){return r(this,ee)}lastSyncedAt(){return this.stream.lastSyncedAt()}lastSynced(){return this.stream.lastSynced()}isLoading(){return this.stream.isLoading()}isConnected(){return this.stream.isConnected()}get mode(){return this.stream.mode}async requestSnapshot(t){let e=me(t);r(this,ct).add(e),await g(this,A,gs).call(this),await this.stream.requestSnapshot(t)}subscribe(t){let e={};return r(this,X).set(e,t),()=>{r(this,X).delete(e)}}unsubscribeAll(){r(this,X).clear()}get numSubscribers(){return r(this,X).size}};U=new WeakMap,X=new WeakMap,Z=new WeakMap,ct=new WeakMap,Ue=new WeakMap,Oe=new WeakMap,ee=new WeakMap,A=new WeakSet,nr=function(t){let e=!1;t.forEach(s=>{if(He(s))if(e=g(this,A,Ht).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":r(this,U).set(s.key,s.value);break;case"update":r(this,U).set(s.key,y(y({},r(this,U).get(s.key)),s.value));break;case"delete":r(this,U).delete(s.key);break}else switch(s.headers.operation){case"insert":r(this,Z).add(s.key),r(this,U).set(s.key,s.value);break;case"update":r(this,Z).has(s.key)&&r(this,U).set(s.key,y(y({},r(this,U).get(s.key)),s.value));break;case"delete":r(this,Z).has(s.key)&&(r(this,U).delete(s.key),r(this,Z).delete(s.key));break}if(St(s))switch(s.headers.control){case"up-to-date":e=g(this,A,Ht).call(this,"up-to-date"),r(this,Ue)&&(d(this,Ue,!1),g(this,A,ar).call(this));break;case"must-refetch":r(this,U).clear(),r(this,Z).clear(),d(this,ee,!1),e=g(this,A,Ht).call(this,"syncing"),d(this,Ue,!0);break}}),e&&g(this,A,Ss).call(this)},ar=async function(){await g(this,A,gs).call(this),await Promise.all(Array.from(r(this,ct)).map(async t=>{try{let e=JSON.parse(t);await this.stream.requestSnapshot(e)}catch(e){}}))},gs=async function(){this.stream.isUpToDate||await new Promise(t=>{let e=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),t())},s=setInterval(e,10),a=this.stream.subscribe(()=>e(),()=>e());e()})},Ht=function(t){let e=r(this,Oe)!==t;return d(this,Oe,t),e&&t==="up-to-date"},or=function(t){t instanceof v&&(d(this,ee,t),g(this,A,Ss).call(this))},Ss=function(){r(this,X).forEach(t=>{t({value:this.currentValue,rows:this.currentRows})})};export{Et as BackoffDefaults,Xt as ELECTRIC_PROTOCOL_QUERY_PARAMS,v as FetchError,rr as Shape,cs as ShapeStream,vs as camelToSnake,Ke as compileExpression,Rt as compileOrderBy,As as createColumnMapper,He as isChangeMessage,St as isControlMessage,jt as isVisibleInSnapshot,ms as resolveValue,gr as snakeCamelMapper,$t as snakeToCamel};
7
11
  //# sourceMappingURL=index.browser.mjs.map