@electric-sql/client 1.5.1 → 1.5.2

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,6 +1,6 @@
1
- var Ts=Object.defineProperty,Ps=Object.defineProperties;var Ms=Object.getOwnPropertyDescriptors;var Qe=Object.getOwnPropertySymbols;var Vt=Object.prototype.hasOwnProperty,Wt=Object.prototype.propertyIsEnumerable;var Kt=r=>{throw TypeError(r)};var Yt=(r,e,t)=>e in r?Ts(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,E=(r,e)=>{for(var t in e||(e={}))Vt.call(e,t)&&Yt(r,t,e[t]);if(Qe)for(var t of Qe(e))Wt.call(e,t)&&Yt(r,t,e[t]);return r},re=(r,e)=>Ps(r,Ms(e));var Qt=(r,e)=>{var t={};for(var s in r)Vt.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&Qe)for(var s of Qe(r))e.indexOf(s)<0&&Wt.call(r,s)&&(t[s]=r[s]);return t};var gt=(r,e,t)=>e.has(r)||Kt("Cannot "+t);var n=(r,e,t)=>(gt(r,e,"read from private field"),t?t.call(r):e.get(r)),u=(r,e,t)=>e.has(r)?Kt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),c=(r,e,t,s)=>(gt(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),p=(r,e,t)=>(gt(r,e,"access private method"),t);var ke=(r,e,t,s)=>({set _(i){c(r,e,i,t)},get _(){return n(r,e,s)}});var A=class r extends Error{constructor(t,s,i,o,a,h){super(h||`HTTP Error ${t} at ${a}: ${s!=null?s:JSON.stringify(i)}`);this.url=a;this.name="FetchError",this.status=t,this.text=s,this.json=i,this.headers=o}static async fromResponse(t,s){let i=t.status,o=Object.fromEntries([...t.headers.entries()]),a,h,d=t.headers.get("content-type");return t.bodyUsed||(d&&d.includes("application/json")?h=await t.json():a=await t.text()),new r(i,a,h,o,s)}},D=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var Ge=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},ze=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Je=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Xe=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},Ze=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var ne=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
1
+ var Cs=Object.defineProperty,ks=Object.defineProperties;var Us=Object.getOwnPropertyDescriptors;var Ge=Object.getOwnPropertySymbols;var Qt=Object.prototype.hasOwnProperty,Gt=Object.prototype.propertyIsEnumerable;var zt=r=>{throw TypeError(r)};var Kt=(r,e,t)=>e in r?Cs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e)=>{for(var t in e||(e={}))Qt.call(e,t)&&Kt(r,t,e[t]);if(Ge)for(var t of Ge(e))Gt.call(e,t)&&Kt(r,t,e[t]);return r},ie=(r,e)=>ks(r,Us(e));var Jt=(r,e)=>{var t={};for(var s in r)Qt.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&Ge)for(var s of Ge(r))e.indexOf(s)<0&&Gt.call(r,s)&&(t[s]=r[s]);return t};var Et=(r,e,t)=>e.has(r)||zt("Cannot "+t);var n=(r,e,t)=>(Et(r,e,"read from private field"),t?t.call(r):e.get(r)),f=(r,e,t)=>e.has(r)?zt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),c=(r,e,t,s)=>(Et(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),p=(r,e,t)=>(Et(r,e,"access private method"),t);var Ue=(r,e,t,s)=>({set _(i){c(r,e,i,t)},get _(){return n(r,e,s)}});var w=class r extends Error{constructor(t,s,i,o,a,h){super(h||`HTTP Error ${t} at ${a}: ${s!=null?s:JSON.stringify(i)}`);this.url=a;this.name="FetchError",this.status=t,this.text=s,this.json=i,this.headers=o}static async fromResponse(t,s){let i=t.status,o=Object.fromEntries([...t.headers.entries()]),a,h,u=t.headers.get("content-type");return t.bodyUsed||(u&&u.includes("application/json")?h=await t.json():a=await t.text()),new r(i,a,h,o,s)}},D=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var ze=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Je=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Xe=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Ze=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},et=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var ae=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
2
2
  `;t.forEach(i=>{s+=`- ${i}
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)}},Ue=class extends Error{constructor(e){super(e),this.name="StaleCacheError"}};var et=r=>Number(r),vs=r=>r==="true"||r==="t",Cs=r=>BigInt(r),Gt=r=>JSON.parse(r),ks=r=>r,Us={int2:et,int4:et,int8:Cs,bool:vs,float4:et,float8:et,json:Gt,jsonb:Gt};function Os(r,e){let t=0,s=null,i="",o=!1,a=0,h;function d(l,g,y){let b=l.slice(g,y);return b=b==="NULL"?null:b,e?e(b):b}function m(l){let g=[];for(;t<l.length;t++){if(s=l[t],o)s==="\\"?i+=l[++t]:s==='"'?(g.push(e?e(i):i),i="",o=l[t+1]==='"',a=t+2):i+=s;else if(s==='"')o=!0;else if(s==="{")a=++t,g.push(m(l));else if(s==="}"){o=!1,a<t&&g.push(d(l,a,t)),a=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(g.push(d(l,a,t)),a=t+1);h=s}return a<t&&g.push(g.push(d(l,a,t+1))),g}return m(r)[0]}var tt=class{constructor(e,t){this.parser=E(E({},Us),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,i)=>(s==="value"||s==="old_value")&&typeof i=="object"&&i!==null?this.transformMessageValue(i,t):i)}parseSnapshotData(e,t){return e.map(s=>{let i=s;return i.value&&typeof i.value=="object"&&i.value!==null&&(i.value=this.transformMessageValue(i.value,t)),i.old_value&&typeof i.old_value=="object"&&i.old_value!==null&&(i.old_value=this.transformMessageValue(i.old_value,t)),i})}transformMessageValue(e,t){let s=e;return Object.keys(s).forEach(i=>{s[i]=this.parseRow(i,s[i],t)}),this.transformer?this.transformer(s):s}parseRow(e,t,s){var g;let i=s[e];if(!i)return t;let l=i,{type:o,dims:a}=l,h=Qt(l,["type","dims"]),d=(g=this.parser[o])!=null?g:ks,m=zt(d,i,e);return a&&a>0?zt((b,S)=>Os(b,m),i,e)(t):m(t,h)}};function zt(r,e,t){var i;let s=!((i=e.not_null)!=null&&i);return o=>{if(o===null){if(!s)throw new Ze(t!=null?t:"unknown");return null}return r(o,e)}}function Oe(r){return`"${r.replace(/"/g,'""')}"`}function Et(r){var h,d,m,l;let e=(d=(h=r.match(/^_+/))==null?void 0:h[0])!=null?d:"",t=r.slice(e.length),s=(l=(m=t.match(/_+$/))==null?void 0:m[0])!=null?l:"",a=(s?t.slice(0,t.length-s.length):t).toLowerCase().replace(/_+([a-z])/g,(g,y)=>y.toUpperCase());return e+a+s}function Jt(r){return r.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Xt(r){let e={};for(let[t,s]of Object.entries(r))e[s]=t;return{decode:t=>{var s;return(s=r[t])!=null?s:t},encode:t=>{var s;return(s=e[t])!=null?s:t}}}function he(r,e){if(!r||!e)return r!=null?r:"";let t=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=[],i=0;for(;i<r.length;){let h=r[i];if(h==="'"||h==='"'){let d=i,m=h;for(i++;i<r.length;)if(r[i]===m)if(r[i+1]===m)i+=2;else{i++;break}else i++;s.push({start:d,end:i})}else i++}let o=h=>s.some(d=>h>=d.start&&h<d.end),a=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(a,(h,d,m)=>o(m)||t.has(h.toUpperCase())||h.startsWith("$")?h:e(h))}function Ls(r){if(r){let e={};for(let t of Object.keys(r))e[t]=Et(t);return Xt(e)}return{decode:e=>Et(e),encode:e=>Jt(e)}}function le(r){return"key"in r}function st(r){return!le(r)}function yt(r){return st(r)&&r.headers.control==="up-to-date"}function Zt(r){if(r.headers.control!="up-to-date")return;let e=r.headers.global_last_seen_lsn;return e?`${e}_0`:void 0}function St(r,e){let t=BigInt(r),s=BigInt(e.xmin),i=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<i&&!o.includes(t)}var es="electric-cursor",de="electric-handle",rt="electric-offset",Rt="electric-schema",ts="electric-up-to-date",bt="columns",nt="cursor",Le="expired_handle",ue="handle",H="live",fe="offset",ss="table",rs="where",ns="replica",is="params",as="experimental_live_sse",xt="live_sse",_t="force-disconnect-and-refresh",At="pause-stream",wt="log",pe="subset__where",De="subset__limit",He="subset__offset",me="subset__order_by",Ie="subset__params",Tt="subset__where_expr",Pt="subset__order_by_expr",it="cache-buster",Mt=[H,xt,ue,fe,nt,Le,wt,pe,De,He,me,Ie,Tt,Pt,it];var Ds=[429],ot={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function Hs(r){if(!r)return 0;let e=Number(r);if(Number.isFinite(e)&&e>0)return e*1e3;let t=Date.parse(r);if(!isNaN(t)){let s=t-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function os(r,e=ot){let{initialDelay:t,maxDelay:s,multiplier:i,debug:o=!1,onFailedAttempt:a,maxRetries:h=1/0}=e;return async(...d)=>{var b;let m=d[0],l=d[1],g=t,y=0;for(;;)try{let S=await r(...d);if(S.ok)return S;throw await A.fromResponse(S,m.toString())}catch(S){if(a==null||a(),(b=l==null?void 0:l.signal)!=null&&b.aborted)throw new D;if(S instanceof A&&!Ds.includes(S.status)&&S.status>=400&&S.status<500)throw S;{if(y++,y>h)throw o&&console.log(`Max retries reached (${y}/${h}), giving up`),S;let R=S instanceof A&&S.headers?Hs(S.headers["retry-after"]):0,x=Math.random()*g,L=Math.min(x,s),V=Math.max(R,L);if(o){let Ce=R>0?"server+client":"client";console.log(`Retry attempt #${y} after ${V}ms (${Ce}, serverMin=${R}ms, clientBackoff=${L}ms)`)}await new Promise(Ce=>setTimeout(Ce,V)),g=Math.min(g*i,s)}}}}var Is=[201,204,205];function cs(r){return async(...e)=>{var i,o;let t=e[0],s=await r(...e);try{if(s.status<200||Is.includes(s.status))return s;let a=await s.text();return new Response(a,s)}catch(a){throw(o=(i=e[1])==null?void 0:i.signal)!=null&&o.aborted?new D:new A(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),a instanceof Error?a.message:typeof a=="string"?a:"failed to read body")}}}var Bs={maxChunksToPrefetch:2};function hs(r,e=Bs){let{maxChunksToPrefetch:t}=e,s;return async(...o)=>{let a=o[0].toString(),h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort(),s=void 0;let d=await r(...o),m=Ct(a,d);return m&&(s=new vt({fetchClient:r,maxPrefetchedRequests:t,url:m,requestInit:o[1]})),d}}var Ns=["electric-offset","electric-handle"],Fs=["electric-cursor"],qs=["electric-schema"];function ls(r){return async(...e)=>{let t=await r(...e);if(t.ok){let s=t.headers,i=[],o=l=>i.push(...l.filter(g=>!s.has(g))),h=e[0].toString(),d=new URL(h);if([pe,Ie,De,He,me].some(l=>d.searchParams.has(l)))return t;if(o(Ns),d.searchParams.get(H)==="true"&&o(Fs),(!d.searchParams.has(H)||d.searchParams.get(H)==="false")&&o(qs),i.length>0)throw new ne(h,i)}return t}}var Be,Ne,C,ie,I,ge,at,vt=class{constructor(e){u(this,ge);u(this,Be);u(this,Ne);u(this,C,new Map);u(this,ie);u(this,I);var t;c(this,Be,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Ne,e.maxPrefetchedRequests),c(this,ie,e.url.toString()),c(this,I,n(this,ie)),p(this,ge,at).call(this,e.url,e.requestInit)}abort(){n(this,C).forEach(([e,t])=>t.abort()),n(this,C).clear()}consume(...e){let t=e[0].toString(),s=n(this,C).get(t);if(!s||t!==n(this,ie))return;let[i,o]=s;if(o.signal.aborted){n(this,C).delete(t);return}return n(this,C).delete(t),i.then(a=>{let h=Ct(t,a);c(this,ie,h),n(this,I)&&!n(this,C).has(n(this,I))&&p(this,ge,at).call(this,n(this,I),e[1])}).catch(()=>{}),i}};Be=new WeakMap,Ne=new WeakMap,C=new WeakMap,ie=new WeakMap,I=new WeakMap,ge=new WeakSet,at=function(...e){var i,o;let t=e[0].toString();if(n(this,C).size>=n(this,Ne))return;let s=new AbortController;try{let{signal:a,cleanup:h}=$s(s,(i=e[1])==null?void 0:i.signal),d=n(this,Be).call(this,t,re(E({},(o=e[1])!=null?o:{}),{signal:a}));n(this,C).set(t,[d,s]),d.then(m=>{if(!m.ok||s.signal.aborted)return;let l=Ct(t,m);if(!l||l===t){c(this,I,void 0);return}return c(this,I,l),p(this,ge,at).call(this,l,e[1])}).catch(()=>{}).finally(h)}catch(a){}};function Ct(r,e){let t=e.headers.get(de),s=e.headers.get(rt),i=e.headers.has(ts);if(!t||!s||i)return;let o=new URL(r);if(o.searchParams.has(H))return;let a=o.searchParams.get(Le);if(a&&t===a){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 "${t}" 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(ue,t),o.searchParams.set(fe,s),o.searchParams.sort(),o.toString()}function $s(r,e){let t=js;if(e)if(e.aborted)r.abort();else{let s=()=>r.abort();e.addEventListener("abort",s,{once:!0,signal:r.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:r.signal,cleanup:t}}function js(){}function Fe(r,e){switch(r.type){case"ref":{let t=e?e(r.column):r.column;return Oe(t)}case"val":return`$${r.paramIndex}`;case"func":return Ys(r,e);default:{let t=r;throw new Error(`Unknown expression type: ${JSON.stringify(t)}`)}}}function Ys(r,e){let t=r.args.map(s=>Fe(s,e));switch(r.name){case"eq":return`${t[0]} = ${t[1]}`;case"gt":return`${t[0]} > ${t[1]}`;case"gte":return`${t[0]} >= ${t[1]}`;case"lt":return`${t[0]} < ${t[1]}`;case"lte":return`${t[0]} <= ${t[1]}`;case"and":return t.map(s=>`(${s})`).join(" AND ");case"or":return t.map(s=>`(${s})`).join(" OR ");case"not":return`NOT (${t[0]})`;case"in":return`${t[0]} = ANY(${t[1]})`;case"like":return`${t[0]} LIKE ${t[1]}`;case"ilike":return`${t[0]} ILIKE ${t[1]}`;case"isNull":case"isUndefined":return`${t[0]} IS NULL`;case"upper":return`UPPER(${t[0]})`;case"lower":return`LOWER(${t[0]})`;case"length":return`LENGTH(${t[0]})`;case"concat":return`CONCAT(${t.join(", ")})`;case"coalesce":return`COALESCE(${t.join(", ")})`;default:throw new Error(`Unknown function: ${r.name}`)}}function ct(r,e){return r.map(t=>{let s=e?e(t.column):t.column,i=Oe(s);return t.direction==="desc"&&(i+=" DESC"),t.nulls==="first"&&(i+=" NULLS FIRST"),t.nulls==="last"&&(i+=" NULLS LAST"),i}).join(", ")}import{fetchEventSource as Vs}from"@microsoft/fetch-event-source";var kt=class{constructor(){this.data={};this.max=250;this.storageKey="electric_expired_shapes";this.load()}getExpiredHandle(e){let t=this.data[e];return t?(t.lastUsed=Date.now(),this.save(),t.expiredHandle):null}markExpired(e,t){this.data[e]={expiredHandle:t,lastUsed:Date.now()};let s=Object.keys(this.data);if(s.length>this.max){let i=s.reduce((o,a)=>this.data[a].lastUsed<this.data[o].lastUsed?a:o);delete this.data[i]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.save()}},qe=new kt;var Ut=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(e,t){this.data[e]={timestamp:Date.now(),cursor:t};let s=Object.keys(this.data);if(s.length>this.maxEntries){let i=s.reduce((o,a)=>this.data[a].timestamp<this.data[o].timestamp?a:o);delete this.data[i]}this.scheduleSave()}scheduleSave(){let e=Date.now(),t=e-this.lastWriteTime;if(t>=this.writeThrottleMs)this.lastWriteTime=e,this.save();else if(!this.pendingSaveTimer){let s=this.writeThrottleMs-t;this.pendingSaveTimer=setTimeout(()=>{this.lastWriteTime=Date.now(),this.pendingSaveTimer=void 0,this.save()},s)}}shouldEnterReplayMode(e){let t=this.data[e];return!t||Date.now()-t.timestamp>=this.cacheTTL?null:t.cursor}cleanup(){let e=Date.now(),t=Object.keys(this.data),s=!1;for(let i of t)e-this.data[i].timestamp>this.cacheTTL&&(delete this.data[i],s=!0);s&&this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.pendingSaveTimer&&(clearTimeout(this.pendingSaveTimer),this.pendingSaveTimer=void 0),this.save()}},Ot=new Ut;var ht=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,a,h,d;this.activeSnapshots.set(e.snapshot_mark,{xmin:BigInt(e.xmin),xmax:BigInt(e.xmax),xip_list:e.xip_list.map(BigInt),keys:t});let s=(a=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?a:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let i=(d=(h=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:h.add(e.snapshot_mark))!=null?d:new Set([e.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(e.database_lsn),i)}removeSnapshot(e){this.activeSnapshots.delete(e)}shouldRejectMessage(e){let t=e.headers.txids||[];if(t.length===0)return!1;let s=Math.max(...t);for(let[i,o]of this.xmaxSnapshots.entries())if(s>=i)for(let a of o)this.removeSnapshot(a);return[...this.activeSnapshots.values()].some(i=>i.keys.has(e.key)&&St(s,i))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let i of s)this.removeSnapshot(i)}};var Ws=new Set([nt,ue,H,fe,it]);async function qt(r){return typeof r=="function"?r():r}async function Ks(r){let e=Object.entries(r),t=await Promise.all(e.map(async([s,i])=>{if(i===void 0)return[s,void 0];let o=await qt(i);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(t.filter(([s,i])=>i!==void 0))}async function Qs(r){if(!r)return{};let e=Object.entries(r),t=await Promise.all(e.map(async([s,i])=>[s,await qt(i)]));return Object.fromEntries(t)}function Ee(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Mt.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var Se,Re,be,ae,W,O,w,B,N,K,v,oe,k,T,Q,F,xe,U,ce,q,_e,G,Ae,je,z,$,we,J,j,Ye,Ve,X,ut,Te,ft,pt,We,Y,Z,Pe,f,Dt,$e,ye,lt,us,Ht,dt,fs,ps,ms,It,Bt,gs,Es,Nt,Ft,ys,Ss,Rs,Lt=class{constructor(e){u(this,f);u(this,Se,null);u(this,Re);u(this,be);u(this,ae);u(this,W,new Map);u(this,O,!1);u(this,w,"active");u(this,B);u(this,N);u(this,K);u(this,v,!1);u(this,oe,!0);u(this,k,!1);u(this,T);u(this,Q);u(this,F);u(this,xe);u(this,U);u(this,ce,!1);u(this,q);u(this,_e);u(this,G);u(this,Ae,Promise.resolve([]));u(this,je,new ht);u(this,z,0);u(this,$);u(this,we);u(this,J);u(this,j);u(this,Ye);u(this,Ve,1e3);u(this,X,0);u(this,ut,3);u(this,Te,!1);u(this,ft,100);u(this,pt,5e3);u(this,We);u(this,Y);u(this,Z,0);u(this,Pe,3);var a,h,d,m;this.options=E({subscribe:!0},e),Gs(this.options),c(this,B,(a=this.options.offset)!=null?a:"-1"),c(this,N,""),c(this,T,this.options.handle);let t;if(e.columnMapper){let l=g=>{let y={};for(let[b,S]of Object.entries(g)){let R=e.columnMapper.decode(b);y[R]=S}return y};t=e.transformer?g=>e.transformer(l(g)):l}else t=e.transformer;c(this,ae,new tt(e.parser,t)),c(this,xe,this.options.onError),c(this,Q,(h=this.options.log)!=null?h:"full");let s=(d=e.fetchClient)!=null?d:(...l)=>fetch(...l),i=re(E({},(m=e.backoffOptions)!=null?m:ot),{onFailedAttempt:()=>{var l,g;c(this,k,!1),(g=(l=e.backoffOptions)==null?void 0:l.onFailedAttempt)==null||g.call(l)}}),o=os(s,i);c(this,be,ls(hs(o))),c(this,Re,cs(n(this,be))),p(this,f,ys).call(this)}get shapeHandle(){return n(this,T)}get error(){return n(this,Se)}get isUpToDate(){return n(this,v)}get lastOffset(){return n(this,B)}get mode(){return n(this,Q)}subscribe(e,t=()=>{}){let s={};return n(this,W).set(s,[e,t]),n(this,O)||p(this,f,$e).call(this),()=>{n(this,W).delete(s)}}unsubscribeAll(){var e;n(this,W).clear(),(e=n(this,We))==null||e.call(this)}lastSyncedAt(){return n(this,K)}lastSynced(){return n(this,K)===void 0?1/0:Date.now()-n(this,K)}isConnected(){return n(this,k)}isLoading(){return!n(this,v)}hasStarted(){return n(this,O)}isPaused(){return n(this,w)==="paused"}async forceDisconnectAndRefresh(){var e,t;c(this,ce,!0),n(this,v)&&!((e=n(this,U))!=null&&e.signal.aborted)&&((t=n(this,U))==null||t.abort(_t)),await p(this,f,gs).call(this),c(this,ce,!1)}async requestSnapshot(e){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,O)||await p(this,f,$e).call(this),await p(this,f,Es).call(this),ke(this,z)._++;try{n(this,z)===1&&p(this,f,It).call(this);let{metadata:t,data:s}=await this.fetchSnapshot(e),i=s.concat([{headers:E({control:"snapshot-end"},t)},{headers:E({control:"subset-end"},e)}]);return n(this,je).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,f,dt).call(this,i,!1),{metadata:t,data:s}}finally{ke(this,z)._--,n(this,z)===0&&p(this,f,Bt).call(this)}}async fetchSnapshot(e){var y,b,S;let s=((b=(y=e.method)!=null?y:this.options.subsetMethod)!=null?b:"GET")==="POST",i,o;if(s){let R=await p(this,f,lt).call(this,this.options.url,!0);i=R.fetchUrl,o={method:"POST",headers:re(E({},R.requestHeaders),{"Content-Type":"application/json"}),body:JSON.stringify(p(this,f,Rs).call(this,e))}}else{let R=await p(this,f,lt).call(this,this.options.url,!0,e);i=R.fetchUrl,o={headers:R.requestHeaders}}let a=n(this,T),h;try{h=await n(this,Re).call(this,i.toString(),o)}catch(R){if(R instanceof A&&R.status===409){if(a){let x=Ee(i);qe.markExpired(x,a)}return c(this,T,R.headers[de]||`${a!=null?a:"handle"}-next`),this.fetchSnapshot(e)}throw R}if(!h.ok)throw await A.fromResponse(h,i.toString());let d=(S=n(this,F))!=null?S:ds(h.headers,{required:!0,url:i.toString()}),{metadata:m,data:l}=await h.json(),g=n(this,ae).parseSnapshotData(l,d);return{metadata:m,data:g}}};Se=new WeakMap,Re=new WeakMap,be=new WeakMap,ae=new WeakMap,W=new WeakMap,O=new WeakMap,w=new WeakMap,B=new WeakMap,N=new WeakMap,K=new WeakMap,v=new WeakMap,oe=new WeakMap,k=new WeakMap,T=new WeakMap,Q=new WeakMap,F=new WeakMap,xe=new WeakMap,U=new WeakMap,ce=new WeakMap,q=new WeakMap,_e=new WeakMap,G=new WeakMap,Ae=new WeakMap,je=new WeakMap,z=new WeakMap,$=new WeakMap,we=new WeakMap,J=new WeakMap,j=new WeakMap,Ye=new WeakMap,Ve=new WeakMap,X=new WeakMap,ut=new WeakMap,Te=new WeakMap,ft=new WeakMap,pt=new WeakMap,We=new WeakMap,Y=new WeakMap,Z=new WeakMap,Pe=new WeakMap,f=new WeakSet,Dt=function(){return n(this,J)!==void 0},$e=async function(){var e,t,s,i,o;c(this,O,!0);try{await p(this,f,ye).call(this)}catch(a){if(c(this,Se,a),n(this,xe)){let h=await n(this,xe).call(this,a),d=!(a instanceof ne);if(h&&typeof h=="object"&&d){h.params&&(this.options.params=E(E({},(e=this.options.params)!=null?e:{}),h.params)),h.headers&&(this.options.headers=E(E({},(t=this.options.headers)!=null?t:{}),h.headers)),c(this,Se,null),c(this,O,!1),await p(this,f,$e).call(this);return}a instanceof Error&&p(this,f,Ft).call(this,a),c(this,k,!1),(s=n(this,G))==null||s.call(this);return}throw a instanceof Error&&p(this,f,Ft).call(this,a),c(this,k,!1),(i=n(this,G))==null||i.call(this),a}c(this,k,!1),(o=n(this,G))==null||o.call(this)},ye=async function(){var d,m;if(n(this,w)==="pause-requested"){c(this,w,"paused");return}if(!this.options.subscribe&&((d=this.options.signal)!=null&&d.aborted||n(this,v)))return;let e=n(this,w)==="paused";c(this,w,"active");let{url:t,signal:s}=this.options,{fetchUrl:i,requestHeaders:o}=await p(this,f,lt).call(this,t,e),a=await p(this,f,us).call(this,s),h=n(this,U);try{await p(this,f,fs).call(this,{fetchUrl:i,requestAbortController:h,headers:o,resumingFromPause:e})}catch(l){if((l instanceof A||l instanceof D)&&h.signal.aborted&&h.signal.reason===_t)return p(this,f,ye).call(this);if(l instanceof D){let g=n(this,w);h.signal.aborted&&h.signal.reason===At&&g==="pause-requested"&&c(this,w,"paused");return}if(l instanceof Ue)return p(this,f,ye).call(this);if(!(l instanceof A))throw l;if(l.status==409){if(n(this,T)){let y=Ee(i);qe.markExpired(y,n(this,T))}let g=l.headers[de]||`${n(this,T)}-next`;return p(this,f,Ss).call(this,g),await p(this,f,Nt).call(this,Array.isArray(l.json)?l.json:[l.json]),p(this,f,ye).call(this)}else throw l}finally{a&&s&&s.removeEventListener("abort",a),c(this,U,void 0)}return(m=n(this,_e))==null||m.call(this),p(this,f,ye).call(this)},lt=async function(e,t,s){var l,g,y,b,S,R;let[i,o]=await Promise.all([Qs(this.options.headers),this.options.params?Ks(zs(this.options.params)):void 0]);o&&bs(o);let a=new URL(e);if(o){if(o.table&&P(a,ss,o.table),o.where&&typeof o.where=="string"){let L=he(o.where,(l=this.options.columnMapper)==null?void 0:l.encode);P(a,rs,L)}if(o.columns){let L=await qt((g=this.options.params)==null?void 0:g.columns);if(Array.isArray(L)){let V=L.map(String);this.options.columnMapper&&(V=V.map(this.options.columnMapper.encode));let Ce=V.map(Oe).join(",");P(a,bt,Ce)}else P(a,bt,o.columns)}o.replica&&P(a,ns,o.replica),o.params&&P(a,is,o.params);let x=E({},o);delete x.table,delete x.where,delete x.columns,delete x.replica,delete x.params;for(let[L,V]of Object.entries(x))P(a,L,V)}if(s){if(s.whereExpr){let x=Fe(s.whereExpr,(y=this.options.columnMapper)==null?void 0:y.encode);P(a,pe,x),a.searchParams.set(Tt,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let x=he(s.where,(b=this.options.columnMapper)==null?void 0:b.encode);P(a,pe,x)}if(s.params&&a.searchParams.set(Ie,JSON.stringify(s.params)),s.limit&&P(a,De,s.limit),s.offset&&P(a,He,s.offset),s.orderByExpr){let x=ct(s.orderByExpr,(S=this.options.columnMapper)==null?void 0:S.encode);P(a,me,x),a.searchParams.set(Pt,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let x=he(s.orderBy,(R=this.options.columnMapper)==null?void 0:R.encode);P(a,me,x)}}a.searchParams.set(fe,n(this,B)),a.searchParams.set(wt,n(this,Q));let h=s!==void 0;n(this,v)&&!h&&(!n(this,ce)&&!t&&a.searchParams.set(H,"true"),a.searchParams.set(nt,n(this,N))),n(this,T)&&a.searchParams.set(ue,n(this,T));let d=Ee(a),m=qe.getExpiredHandle(d);return m&&a.searchParams.set(Le,m),n(this,Y)&&a.searchParams.set(it,n(this,Y)),a.searchParams.sort(),{fetchUrl:a,requestHeaders:i}},us=async function(e){var t;if(c(this,U,new AbortController),e){let s=()=>{var i;(i=n(this,U))==null||i.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,U))==null||t.abort(e.reason)),s}},Ht=async function(e){var h,d,m,l;let{headers:t,status:s}=e,i=t.get(de);if(i){let g=n(this,j)?Ee(n(this,j)):null,y=g?qe.getExpiredHandle(g):null;if(i!==y)c(this,T,i),n(this,Y)&&(c(this,Y,void 0),c(this,Z,0));else{if(n(this,T)===void 0)throw ke(this,Z)._++,await((h=e.body)==null?void 0:h.cancel()),n(this,Z)>n(this,Pe)?new A(502,void 0,void 0,{},(m=(d=n(this,j))==null?void 0:d.toString())!=null?m:"",`CDN continues serving stale cached responses after ${n(this,Pe)} 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 "${i}" 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,Z)}/${n(this,Pe)}).`),c(this,Y,`${Date.now()}-${Math.random().toString(36).substring(2,9)}`),new Ue(`Received stale cached response with expired handle "${i}". This indicates a proxy/CDN caching misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key.`));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 "${i}" 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,T)}".`);return}}let o=t.get(rt);o&&c(this,B,o);let a=t.get(es);a&&c(this,N,a),c(this,F,(l=n(this,F))!=null?l:ds(t)),s===204&&c(this,K,Date.now())},dt=async function(e,t=!1){var s;if(e.length>0){c(this,oe,!0);let i=e[e.length-1];if(yt(i)){if(t){let a=Zt(i);a&&c(this,B,a)}if(c(this,K,Date.now()),c(this,v,!0),c(this,oe,!1),(s=n(this,we))==null||s.call(this),n(this,f,Dt)&&!t&&n(this,N)===n(this,J)){c(this,J,void 0);return}if(c(this,J,void 0),n(this,j)){let a=Ee(n(this,j));Ot.recordUpToDate(a,n(this,N))}}let o=e.filter(a=>le(a)?!n(this,je).shouldRejectMessage(a):!0);await p(this,f,Nt).call(this,o)}},fs=async function(e){var s;if(c(this,j,e.fetchUrl),!n(this,v)&&!n(this,f,Dt)){let i=Ee(e.fetchUrl),o=Ot.shouldEnterReplayMode(i);o&&c(this,J,o)}let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,v)&&t&&!n(this,ce)&&!e.resumingFromPause&&!n(this,Te)?(e.fetchUrl.searchParams.set(as,"true"),e.fetchUrl.searchParams.set(xt,"true"),p(this,f,ms).call(this,e)):p(this,f,ps).call(this,e)},ps=async function(e){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=await n(this,Re).call(this,t.toString(),{signal:s.signal,headers:i});c(this,k,!0),await p(this,f,Ht).call(this,o);let a=n(this,F),d=await o.text()||"[]",m=n(this,ae).parse(d,a);await p(this,f,dt).call(this,m)},ms=async function(e){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=n(this,be);c(this,Ye,Date.now());let a=re(E({},i),{Accept:"text/event-stream"});try{let h=[];await Vs(t.toString(),{headers:a,fetch:o,onopen:async d=>{c(this,k,!0),await p(this,f,Ht).call(this,d)},onmessage:d=>{if(d.data){let m=n(this,F),l=n(this,ae).parse(d.data,m);h.push(l),yt(l)&&(p(this,f,dt).call(this,h,!0),h=[])}},onerror:d=>{throw d},signal:s.signal})}catch(h){throw s.signal.aborted?new D:h}finally{let h=Date.now()-n(this,Ye),d=s.signal.aborted;if(h<n(this,Ve)&&!d)if(ke(this,X)._++,n(this,X)>=n(this,ut))c(this,Te,!0),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{let m=Math.min(n(this,pt),n(this,ft)*Math.pow(2,n(this,X))),l=Math.floor(Math.random()*m);await new Promise(g=>setTimeout(g,l))}else h>=n(this,Ve)&&c(this,X,0)}},It=function(){var e;n(this,O)&&n(this,w)==="active"&&(c(this,w,"pause-requested"),(e=n(this,U))==null||e.abort(At))},Bt=function(){var e;if(n(this,O)&&(n(this,w)==="paused"||n(this,w)==="pause-requested")){if((e=this.options.signal)!=null&&e.aborted)return;n(this,w)==="pause-requested"&&c(this,w,"active"),p(this,f,$e).call(this)}},gs=async function(){return n(this,q)?n(this,q):(c(this,q,new Promise((e,t)=>{c(this,_e,e),c(this,G,t)})),n(this,q).finally(()=>{c(this,q,void 0),c(this,_e,void 0),c(this,G,void 0)}),n(this,q))},Es=async function(){if(n(this,oe))return n(this,$)?n(this,$):(c(this,$,new Promise(e=>{c(this,we,e)})),n(this,$).finally(()=>{c(this,$,void 0),c(this,we,void 0)}),n(this,$))},Nt=async function(e){return c(this,Ae,n(this,Ae).then(()=>Promise.all(Array.from(n(this,W).values()).map(async([t,s])=>{try{await t(e)}catch(i){queueMicrotask(()=>{throw i})}})))),n(this,Ae)},Ft=function(e){n(this,W).forEach(([t,s])=>{s==null||s(e)})},ys=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?p(this,f,It).call(this):p(this,f,Bt).call(this)};document.addEventListener("visibilitychange",e),c(this,We,()=>{document.removeEventListener("visibilitychange",e)})}},Ss=function(e){c(this,B,"-1"),c(this,N,""),c(this,T,e),c(this,v,!1),c(this,oe,!0),c(this,k,!1),c(this,F,void 0),c(this,z,0),c(this,X,0),c(this,Te,!1),c(this,Y,void 0),c(this,Z,0)},Rs=function(e){var s,i,o,a;let t={};return e.whereExpr?(t.where=Fe(e.whereExpr,(s=this.options.columnMapper)==null?void 0:s.encode),t.where_expr=e.whereExpr):e.where&&typeof e.where=="string"&&(t.where=he(e.where,(i=this.options.columnMapper)==null?void 0:i.encode)),e.params&&(t.params=e.params),e.limit!==void 0&&(t.limit=e.limit),e.offset!==void 0&&(t.offset=e.offset),e.orderByExpr?(t.order_by=ct(e.orderByExpr,(o=this.options.columnMapper)==null?void 0:o.encode),t.order_by_expr=e.orderByExpr):e.orderBy&&typeof e.orderBy=="string"&&(t.order_by=he(e.orderBy,(a=this.options.columnMapper)==null?void 0:a.encode)),t},Lt.Replica={FULL:"full",DEFAULT:"default"};function ds(r,e){let t=r.get(Rt);if(!t){if(e!=null&&e.required&&(e!=null&&e.url))throw new ne(e.url,[Rt]);return{}}return JSON.parse(t)}function bs(r){if(!r)return;let e=Object.keys(r).filter(t=>Ws.has(t));if(e.length>0)throw new Xe(e)}function Gs(r){if(!r.url)throw new Ge;if(r.signal&&!(r.signal instanceof AbortSignal))throw new ze;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Je;bs(r.params)}function P(r,e,t){if(!(t===void 0||t==null))if(typeof t=="string")r.searchParams.set(e,t);else if(typeof t=="object")for(let[s,i]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,i);else r.searchParams.set(e,t.toString())}function zs(r){return Array.isArray(r.params)?re(E({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var M,ee,te,Ke,Me,ve,se,_,_s,As,$t,mt,ws,jt,xs=class{constructor(e){u(this,_);u(this,M,new Map);u(this,ee,new Map);u(this,te,new Set);u(this,Ke,new Set);u(this,Me,!1);u(this,ve,"syncing");u(this,se,!1);this.stream=e,this.stream.subscribe(p(this,_,_s).bind(this),p(this,_,ws).bind(this))}get isUpToDate(){return n(this,ve)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(e=>Array.from(e.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((e,t)=>{if(this.stream.isUpToDate)e(this.currentValue);else{let s=this.subscribe(({value:i})=>{s(),n(this,se)&&t(n(this,se)),e(i)})}})}get currentValue(){return n(this,M)}get error(){return n(this,se)}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(e){let t=JSON.stringify(e);n(this,Ke).add(t),await p(this,_,$t).call(this),await this.stream.requestSnapshot(e)}subscribe(e){let t={};return n(this,ee).set(t,e),()=>{n(this,ee).delete(t)}}unsubscribeAll(){n(this,ee).clear()}get numSubscribers(){return n(this,ee).size}};M=new WeakMap,ee=new WeakMap,te=new WeakMap,Ke=new WeakMap,Me=new WeakMap,ve=new WeakMap,se=new WeakMap,_=new WeakSet,_s=function(e){let t=!1;e.forEach(s=>{if(le(s))if(t=p(this,_,mt).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,M).set(s.key,s.value);break;case"update":n(this,M).set(s.key,E(E({},n(this,M).get(s.key)),s.value));break;case"delete":n(this,M).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,te).add(s.key),n(this,M).set(s.key,s.value);break;case"update":n(this,te).has(s.key)&&n(this,M).set(s.key,E(E({},n(this,M).get(s.key)),s.value));break;case"delete":n(this,te).has(s.key)&&(n(this,M).delete(s.key),n(this,te).delete(s.key));break}if(st(s))switch(s.headers.control){case"up-to-date":t=p(this,_,mt).call(this,"up-to-date"),n(this,Me)&&(c(this,Me,!1),p(this,_,As).call(this));break;case"must-refetch":n(this,M).clear(),n(this,te).clear(),c(this,se,!1),t=p(this,_,mt).call(this,"syncing"),c(this,Me,!0);break}}),t&&p(this,_,jt).call(this)},As=async function(){await p(this,_,$t).call(this),await Promise.all(Array.from(n(this,Ke)).map(async e=>{try{let t=JSON.parse(e);await this.stream.requestSnapshot(t)}catch(t){}}))},$t=async function(){this.stream.isUpToDate||await new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),i(),e())},s=setInterval(t,10),i=this.stream.subscribe(()=>t(),()=>t());t()})},mt=function(e){let t=n(this,ve)!==e;return c(this,ve,e),t&&e==="up-to-date"},ws=function(e){e instanceof A&&(c(this,se,e),p(this,_,jt).call(this))},jt=function(){n(this,ee).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{ot as BackoffDefaults,Mt as ELECTRIC_PROTOCOL_QUERY_PARAMS,A as FetchError,xs as Shape,Lt as ShapeStream,Jt as camelToSnake,Fe as compileExpression,ct as compileOrderBy,Xt as createColumnMapper,le as isChangeMessage,st as isControlMessage,St as isVisibleInSnapshot,qt as resolveValue,Ls as snakeCamelMapper,Et as snakeToCamel};
5
+ For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}},Oe=class extends Error{constructor(e){super(e),this.name="StaleCacheError"}};var tt=r=>Number(r),Os=r=>r==="true"||r==="t",Ls=r=>BigInt(r),Xt=r=>JSON.parse(r),Ds=r=>r,Hs={int2:tt,int4:tt,int8:Ls,bool:Os,float4:tt,float8:tt,json:Xt,jsonb:Xt};function Is(r,e){let t=0,s=null,i="",o=!1,a=0,h;function u(l,g,S){let R=l.slice(g,S);return R=R==="NULL"?null:R,e?e(R):R}function m(l){let g=[];for(;t<l.length;t++){if(s=l[t],o)s==="\\"?i+=l[++t]:s==='"'?(g.push(e?e(i):i),i="",o=l[t+1]==='"',a=t+2):i+=s;else if(s==='"')o=!0;else if(s==="{")a=++t,g.push(m(l));else if(s==="}"){o=!1,a<t&&g.push(u(l,a,t)),a=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(g.push(u(l,a,t)),a=t+1);h=s}return a<t&&g.push(g.push(u(l,a,t+1))),g}return m(r)[0]}var st=class{constructor(e,t){this.parser=y(y({},Hs),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,i)=>(s==="value"||s==="old_value")&&typeof i=="object"&&i!==null?this.transformMessageValue(i,t):i)}parseSnapshotData(e,t){return e.map(s=>{let i=s;return i.value&&typeof i.value=="object"&&i.value!==null&&(i.value=this.transformMessageValue(i.value,t)),i.old_value&&typeof i.old_value=="object"&&i.old_value!==null&&(i.old_value=this.transformMessageValue(i.old_value,t)),i})}transformMessageValue(e,t){let s=e;return Object.keys(s).forEach(i=>{s[i]=this.parseRow(i,s[i],t)}),this.transformer?this.transformer(s):s}parseRow(e,t,s){var g;let i=s[e];if(!i)return t;let l=i,{type:o,dims:a}=l,h=Jt(l,["type","dims"]),u=(g=this.parser[o])!=null?g:Ds,m=Zt(u,i,e);return a&&a>0?Zt((R,E)=>Is(R,m),i,e)(t):m(t,h)}};function Zt(r,e,t){var i;let s=!((i=e.not_null)!=null&&i);return o=>{if(o===null){if(!s)throw new et(t!=null?t:"unknown");return null}return r(o,e)}}function Le(r){return`"${r.replace(/"/g,'""')}"`}function yt(r){var h,u,m,l;let e=(u=(h=r.match(/^_+/))==null?void 0:h[0])!=null?u:"",t=r.slice(e.length),s=(l=(m=t.match(/_+$/))==null?void 0:m[0])!=null?l:"",a=(s?t.slice(0,t.length-s.length):t).toLowerCase().replace(/_+([a-z])/g,(g,S)=>S.toUpperCase());return e+a+s}function es(r){return r.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function ts(r){let e={};for(let[t,s]of Object.entries(r))e[s]=t;return{decode:t=>{var s;return(s=r[t])!=null?s:t},encode:t=>{var s;return(s=e[t])!=null?s:t}}}function le(r,e){if(!r||!e)return r!=null?r:"";let t=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=[],i=0;for(;i<r.length;){let h=r[i];if(h==="'"||h==='"'){let u=i,m=h;for(i++;i<r.length;)if(r[i]===m)if(r[i+1]===m)i+=2;else{i++;break}else i++;s.push({start:u,end:i})}else i++}let o=h=>s.some(u=>h>=u.start&&h<u.end),a=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(a,(h,u,m)=>o(m)||t.has(h.toUpperCase())||h.startsWith("$")?h:e(h))}function Bs(r){if(r){let e={};for(let t of Object.keys(r))e[t]=yt(t);return ts(e)}return{decode:e=>yt(e),encode:e=>es(e)}}function ue(r){return"key"in r}function rt(r){return!ue(r)}function St(r){return rt(r)&&r.headers.control==="up-to-date"}function ss(r){if(r.headers.control!="up-to-date")return;let e=r.headers.global_last_seen_lsn;return e?`${e}_0`:void 0}function Rt(r,e){let t=BigInt(r),s=BigInt(e.xmin),i=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<i&&!o.includes(t)}var rs="electric-cursor",de="electric-handle",nt="electric-offset",bt="electric-schema",ns="electric-up-to-date",_t="columns",it="cursor",De="expired_handle",fe="handle",H="live",pe="offset",is="table",as="where",os="replica",cs="params",hs="experimental_live_sse",xt="live_sse",At="force-disconnect-and-refresh",wt="pause-stream",Tt="system-wake",Pt="log",me="subset__where",He="subset__limit",Ie="subset__offset",ge="subset__order_by",Be="subset__params",Mt="subset__where_expr",vt="subset__order_by_expr",at="cache-buster",Ct=[H,xt,fe,pe,it,De,Pt,me,He,Ie,ge,Be,Mt,vt,at];var Ns=[429],ct={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function Fs(r){if(!r)return 0;let e=Number(r);if(Number.isFinite(e)&&e>0)return e*1e3;let t=Date.parse(r);if(!isNaN(t)){let s=t-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function ls(r,e=ct){let{initialDelay:t,maxDelay:s,multiplier:i,debug:o=!1,onFailedAttempt:a,maxRetries:h=1/0}=e;return async(...u)=>{var R;let m=u[0],l=u[1],g=t,S=0;for(;;)try{let E=await r(...u);if(E.ok)return E;throw await w.fromResponse(E,m.toString())}catch(E){if(a==null||a(),(R=l==null?void 0:l.signal)!=null&&R.aborted)throw new D;if(E instanceof w&&!Ns.includes(E.status)&&E.status>=400&&E.status<500)throw E;{if(S++,S>h)throw o&&console.log(`Max retries reached (${S}/${h}), giving up`),E;let b=E instanceof w&&E.headers?Fs(E.headers["retry-after"]):0,_=Math.random()*g,L=Math.min(_,s),W=Math.max(b,L);if(o){let ke=b>0?"server+client":"client";console.log(`Retry attempt #${S} after ${W}ms (${ke}, serverMin=${b}ms, clientBackoff=${L}ms)`)}await new Promise(ke=>setTimeout(ke,W)),g=Math.min(g*i,s)}}}}var qs=[201,204,205];function us(r){return async(...e)=>{var i,o;let t=e[0],s=await r(...e);try{if(s.status<200||qs.includes(s.status))return s;let a=await s.text();return new Response(a,s)}catch(a){throw(o=(i=e[1])==null?void 0:i.signal)!=null&&o.aborted?new D:new w(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),a instanceof Error?a.message:typeof a=="string"?a:"failed to read body")}}}var $s={maxChunksToPrefetch:2};function ds(r,e=$s){let{maxChunksToPrefetch:t}=e,s;return async(...o)=>{let a=o[0].toString(),h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort(),s=void 0;let u=await r(...o),m=Ut(a,u);return m&&(s=new kt({fetchClient:r,maxPrefetchedRequests:t,url:m,requestInit:o[1]})),u}}var js=["electric-offset","electric-handle"],Ys=["electric-cursor"],Vs=["electric-schema"];function fs(r){return async(...e)=>{let t=await r(...e);if(t.ok){let s=t.headers,i=[],o=l=>i.push(...l.filter(g=>!s.has(g))),h=e[0].toString(),u=new URL(h);if([me,Be,He,Ie,ge].some(l=>u.searchParams.has(l)))return t;if(o(js),u.searchParams.get(H)==="true"&&o(Ys),(!u.searchParams.has(H)||u.searchParams.get(H)==="false")&&o(Vs),i.length>0)throw new ae(h,i)}return t}}var Ne,Fe,k,oe,I,Ee,ot,kt=class{constructor(e){f(this,Ee);f(this,Ne);f(this,Fe);f(this,k,new Map);f(this,oe);f(this,I);var t;c(this,Ne,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Fe,e.maxPrefetchedRequests),c(this,oe,e.url.toString()),c(this,I,n(this,oe)),p(this,Ee,ot).call(this,e.url,e.requestInit)}abort(){n(this,k).forEach(([e,t])=>t.abort()),n(this,k).clear()}consume(...e){let t=e[0].toString(),s=n(this,k).get(t);if(!s||t!==n(this,oe))return;let[i,o]=s;if(o.signal.aborted){n(this,k).delete(t);return}return n(this,k).delete(t),i.then(a=>{let h=Ut(t,a);c(this,oe,h),n(this,I)&&!n(this,k).has(n(this,I))&&p(this,Ee,ot).call(this,n(this,I),e[1])}).catch(()=>{}),i}};Ne=new WeakMap,Fe=new WeakMap,k=new WeakMap,oe=new WeakMap,I=new WeakMap,Ee=new WeakSet,ot=function(...e){var i,o;let t=e[0].toString();if(n(this,k).size>=n(this,Fe))return;let s=new AbortController;try{let{signal:a,cleanup:h}=Ws(s,(i=e[1])==null?void 0:i.signal),u=n(this,Ne).call(this,t,ie(y({},(o=e[1])!=null?o:{}),{signal:a}));n(this,k).set(t,[u,s]),u.then(m=>{if(!m.ok||s.signal.aborted)return;let l=Ut(t,m);if(!l||l===t){c(this,I,void 0);return}return c(this,I,l),p(this,Ee,ot).call(this,l,e[1])}).catch(()=>{}).finally(h)}catch(a){}};function Ut(r,e){let t=e.headers.get(de),s=e.headers.get(nt),i=e.headers.has(ns);if(!t||!s||i)return;let o=new URL(r);if(o.searchParams.has(H))return;let a=o.searchParams.get(De);if(a&&t===a){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 "${t}" 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(fe,t),o.searchParams.set(pe,s),o.searchParams.sort(),o.toString()}function Ws(r,e){let t=Ks;if(e)if(e.aborted)r.abort();else{let s=()=>r.abort();e.addEventListener("abort",s,{once:!0,signal:r.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:r.signal,cleanup:t}}function Ks(){}function qe(r,e){switch(r.type){case"ref":{let t=e?e(r.column):r.column;return Le(t)}case"val":return`$${r.paramIndex}`;case"func":return Qs(r,e);default:{let t=r;throw new Error(`Unknown expression type: ${JSON.stringify(t)}`)}}}function Qs(r,e){let t=r.args.map(s=>qe(s,e));switch(r.name){case"eq":return`${t[0]} = ${t[1]}`;case"gt":return`${t[0]} > ${t[1]}`;case"gte":return`${t[0]} >= ${t[1]}`;case"lt":return`${t[0]} < ${t[1]}`;case"lte":return`${t[0]} <= ${t[1]}`;case"and":return t.map(s=>`(${s})`).join(" AND ");case"or":return t.map(s=>`(${s})`).join(" OR ");case"not":return`NOT (${t[0]})`;case"in":return`${t[0]} = ANY(${t[1]})`;case"like":return`${t[0]} LIKE ${t[1]}`;case"ilike":return`${t[0]} ILIKE ${t[1]}`;case"isNull":case"isUndefined":return`${t[0]} IS NULL`;case"upper":return`UPPER(${t[0]})`;case"lower":return`LOWER(${t[0]})`;case"length":return`LENGTH(${t[0]})`;case"concat":return`CONCAT(${t.join(", ")})`;case"coalesce":return`COALESCE(${t.join(", ")})`;default:throw new Error(`Unknown function: ${r.name}`)}}function ht(r,e){return r.map(t=>{let s=e?e(t.column):t.column,i=Le(s);return t.direction==="desc"&&(i+=" DESC"),t.nulls==="first"&&(i+=" NULLS FIRST"),t.nulls==="last"&&(i+=" NULLS LAST"),i}).join(", ")}import{fetchEventSource as Gs}from"@microsoft/fetch-event-source";var Ot=class{constructor(){this.data={};this.max=250;this.storageKey="electric_expired_shapes";this.load()}getExpiredHandle(e){let t=this.data[e];return t?(t.lastUsed=Date.now(),this.save(),t.expiredHandle):null}markExpired(e,t){this.data[e]={expiredHandle:t,lastUsed:Date.now()};let s=Object.keys(this.data);if(s.length>this.max){let i=s.reduce((o,a)=>this.data[a].lastUsed<this.data[o].lastUsed?a:o);delete this.data[i]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.save()}},$e=new Ot;var Lt=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(e,t){this.data[e]={timestamp:Date.now(),cursor:t};let s=Object.keys(this.data);if(s.length>this.maxEntries){let i=s.reduce((o,a)=>this.data[a].timestamp<this.data[o].timestamp?a:o);delete this.data[i]}this.scheduleSave()}scheduleSave(){let e=Date.now(),t=e-this.lastWriteTime;if(t>=this.writeThrottleMs)this.lastWriteTime=e,this.save();else if(!this.pendingSaveTimer){let s=this.writeThrottleMs-t;this.pendingSaveTimer=setTimeout(()=>{this.lastWriteTime=Date.now(),this.pendingSaveTimer=void 0,this.save()},s)}}shouldEnterReplayMode(e){let t=this.data[e];return!t||Date.now()-t.timestamp>=this.cacheTTL?null:t.cursor}cleanup(){let e=Date.now(),t=Object.keys(this.data),s=!1;for(let i of t)e-this.data[i].timestamp>this.cacheTTL&&(delete this.data[i],s=!0);s&&this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.pendingSaveTimer&&(clearTimeout(this.pendingSaveTimer),this.pendingSaveTimer=void 0),this.save()}},Dt=new Lt;var lt=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,a,h,u;this.activeSnapshots.set(e.snapshot_mark,{xmin:BigInt(e.xmin),xmax:BigInt(e.xmax),xip_list:e.xip_list.map(BigInt),keys:t});let s=(a=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?a:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let i=(u=(h=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:h.add(e.snapshot_mark))!=null?u:new Set([e.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(e.database_lsn),i)}removeSnapshot(e){this.activeSnapshots.delete(e)}shouldRejectMessage(e){let t=e.headers.txids||[];if(t.length===0)return!1;let s=Math.max(...t);for(let[i,o]of this.xmaxSnapshots.entries())if(s>=i)for(let a of o)this.removeSnapshot(a);return[...this.activeSnapshots.values()].some(i=>i.keys.has(e.key)&&Rt(s,i))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let i of s)this.removeSnapshot(i)}};var zs=new Set([it,fe,H,pe,at]);async function Yt(r){return typeof r=="function"?r():r}async function Js(r){let e=Object.entries(r),t=await Promise.all(e.map(async([s,i])=>{if(i===void 0)return[s,void 0];let o=await Yt(i);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(t.filter(([s,i])=>i!==void 0))}async function Xs(r){if(!r)return{};let e=Object.entries(r),t=await Promise.all(e.map(async([s,i])=>[s,await Yt(i)]));return Object.fromEntries(t)}function ye(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Ct.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var Re,be,_e,ce,K,O,A,B,N,Q,C,he,U,T,G,F,xe,M,q,$,Ae,z,we,Ye,J,j,Te,X,Y,Ve,We,Z,ft,Pe,pt,mt,Ke,ee,V,te,Me,d,It,je,Se,ut,ms,Bt,dt,gs,Es,ys,Nt,Ft,Ss,Rs,qt,$t,jt,bs,_s,xs,As,Ht=class{constructor(e){f(this,d);f(this,Re,null);f(this,be);f(this,_e);f(this,ce);f(this,K,new Map);f(this,O,!1);f(this,A,"active");f(this,B);f(this,N);f(this,Q);f(this,C,!1);f(this,he,!0);f(this,U,!1);f(this,T);f(this,G);f(this,F);f(this,xe);f(this,M);f(this,q,!1);f(this,$);f(this,Ae);f(this,z);f(this,we,Promise.resolve([]));f(this,Ye,new lt);f(this,J,0);f(this,j);f(this,Te);f(this,X);f(this,Y);f(this,Ve);f(this,We,1e3);f(this,Z,0);f(this,ft,3);f(this,Pe,!1);f(this,pt,100);f(this,mt,5e3);f(this,Ke);f(this,ee);f(this,V);f(this,te,0);f(this,Me,3);var a,h,u,m;this.options=y({subscribe:!0},e),Zs(this.options),c(this,B,(a=this.options.offset)!=null?a:"-1"),c(this,N,""),c(this,T,this.options.handle);let t;if(e.columnMapper){let l=g=>{let S={};for(let[R,E]of Object.entries(g)){let b=e.columnMapper.decode(R);S[b]=E}return S};t=e.transformer?g=>e.transformer(l(g)):l}else t=e.transformer;c(this,ce,new st(e.parser,t)),c(this,xe,this.options.onError),c(this,G,(h=this.options.log)!=null?h:"full");let s=(u=e.fetchClient)!=null?u:(...l)=>fetch(...l),i=ie(y({},(m=e.backoffOptions)!=null?m:ct),{onFailedAttempt:()=>{var l,g;c(this,U,!1),(g=(l=e.backoffOptions)==null?void 0:l.onFailedAttempt)==null||g.call(l)}}),o=ls(s,i);c(this,_e,fs(ds(o))),c(this,be,us(n(this,_e))),p(this,d,bs).call(this),p(this,d,_s).call(this)}get shapeHandle(){return n(this,T)}get error(){return n(this,Re)}get isUpToDate(){return n(this,C)}get lastOffset(){return n(this,B)}get mode(){return n(this,G)}subscribe(e,t=()=>{}){let s={};return n(this,K).set(s,[e,t]),n(this,O)||p(this,d,je).call(this),()=>{n(this,K).delete(s)}}unsubscribeAll(){var e,t;n(this,K).clear(),(e=n(this,Ke))==null||e.call(this),(t=n(this,ee))==null||t.call(this)}lastSyncedAt(){return n(this,Q)}lastSynced(){return n(this,Q)===void 0?1/0:Date.now()-n(this,Q)}isConnected(){return n(this,U)}isLoading(){return!n(this,C)}hasStarted(){return n(this,O)}isPaused(){return n(this,A)==="paused"}async forceDisconnectAndRefresh(){var e,t;c(this,q,!0),n(this,C)&&!((e=n(this,M))!=null&&e.signal.aborted)&&((t=n(this,M))==null||t.abort(At)),await p(this,d,Ss).call(this),c(this,q,!1)}async requestSnapshot(e){if(n(this,G)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,G)} mode, as the consumer is guaranteed to observe all data`);n(this,O)||await p(this,d,je).call(this),await p(this,d,Rs).call(this),Ue(this,J)._++;try{n(this,J)===1&&p(this,d,Nt).call(this);let{metadata:t,data:s}=await this.fetchSnapshot(e),i=s.concat([{headers:y({control:"snapshot-end"},t)},{headers:y({control:"subset-end"},e)}]);return n(this,Ye).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,d,dt).call(this,i,!1),{metadata:t,data:s}}finally{Ue(this,J)._--,n(this,J)===0&&p(this,d,Ft).call(this)}}async fetchSnapshot(e){var S,R,E;let s=((R=(S=e.method)!=null?S:this.options.subsetMethod)!=null?R:"GET")==="POST",i,o;if(s){let b=await p(this,d,ut).call(this,this.options.url,!0);i=b.fetchUrl,o={method:"POST",headers:ie(y({},b.requestHeaders),{"Content-Type":"application/json"}),body:JSON.stringify(p(this,d,As).call(this,e))}}else{let b=await p(this,d,ut).call(this,this.options.url,!0,e);i=b.fetchUrl,o={headers:b.requestHeaders}}let a=n(this,T),h;try{h=await n(this,be).call(this,i.toString(),o)}catch(b){if(b instanceof w&&b.status===409){if(a){let _=ye(i);$e.markExpired(_,a)}return c(this,T,b.headers[de]||`${a!=null?a:"handle"}-next`),this.fetchSnapshot(e)}throw b}if(!h.ok)throw await w.fromResponse(h,i.toString());let u=(E=n(this,F))!=null?E:ps(h.headers,{required:!0,url:i.toString()}),{metadata:m,data:l}=await h.json(),g=n(this,ce).parseSnapshotData(l,u);return{metadata:m,data:g}}};Re=new WeakMap,be=new WeakMap,_e=new WeakMap,ce=new WeakMap,K=new WeakMap,O=new WeakMap,A=new WeakMap,B=new WeakMap,N=new WeakMap,Q=new WeakMap,C=new WeakMap,he=new WeakMap,U=new WeakMap,T=new WeakMap,G=new WeakMap,F=new WeakMap,xe=new WeakMap,M=new WeakMap,q=new WeakMap,$=new WeakMap,Ae=new WeakMap,z=new WeakMap,we=new WeakMap,Ye=new WeakMap,J=new WeakMap,j=new WeakMap,Te=new WeakMap,X=new WeakMap,Y=new WeakMap,Ve=new WeakMap,We=new WeakMap,Z=new WeakMap,ft=new WeakMap,Pe=new WeakMap,pt=new WeakMap,mt=new WeakMap,Ke=new WeakMap,ee=new WeakMap,V=new WeakMap,te=new WeakMap,Me=new WeakMap,d=new WeakSet,It=function(){return n(this,X)!==void 0},je=async function(){var e,t,s,i,o,a,h,u;c(this,O,!0);try{await p(this,d,Se).call(this)}catch(m){if(c(this,Re,m),n(this,xe)){let l=await n(this,xe).call(this,m),g=!(m instanceof ae);if(l&&typeof l=="object"&&g){l.params&&(this.options.params=y(y({},(e=this.options.params)!=null?e:{}),l.params)),l.headers&&(this.options.headers=y(y({},(t=this.options.headers)!=null?t:{}),l.headers)),c(this,Re,null),c(this,O,!1),await p(this,d,je).call(this);return}m instanceof Error&&p(this,d,$t).call(this,m),c(this,U,!1),(s=n(this,z))==null||s.call(this),(i=n(this,ee))==null||i.call(this);return}throw m instanceof Error&&p(this,d,$t).call(this,m),c(this,U,!1),(o=n(this,z))==null||o.call(this),(a=n(this,ee))==null||a.call(this),m}c(this,U,!1),(h=n(this,z))==null||h.call(this),(u=n(this,ee))==null||u.call(this)},Se=async function(){var u,m;if(n(this,A)==="pause-requested"){c(this,A,"paused");return}if(!this.options.subscribe&&((u=this.options.signal)!=null&&u.aborted||n(this,C)))return;let e=n(this,A)==="paused";c(this,A,"active");let{url:t,signal:s}=this.options,{fetchUrl:i,requestHeaders:o}=await p(this,d,ut).call(this,t,e),a=await p(this,d,ms).call(this,s),h=n(this,M);try{await p(this,d,gs).call(this,{fetchUrl:i,requestAbortController:h,headers:o,resumingFromPause:e})}catch(l){let g=h.signal.reason,S=h.signal.aborted&&(g===At||g===Tt);if((l instanceof w||l instanceof D)&&S)return p(this,d,Se).call(this);if(l instanceof D){let R=n(this,A);h.signal.aborted&&h.signal.reason===wt&&R==="pause-requested"&&c(this,A,"paused");return}if(l instanceof Oe)return p(this,d,Se).call(this);if(!(l instanceof w))throw l;if(l.status==409){if(n(this,T)){let E=ye(i);$e.markExpired(E,n(this,T))}let R=l.headers[de]||`${n(this,T)}-next`;return p(this,d,xs).call(this,R),await p(this,d,qt).call(this,Array.isArray(l.json)?l.json:[l.json]),p(this,d,Se).call(this)}else throw l}finally{a&&s&&s.removeEventListener("abort",a),c(this,M,void 0)}return(m=n(this,Ae))==null||m.call(this),p(this,d,Se).call(this)},ut=async function(e,t,s){var l,g,S,R,E,b;let[i,o]=await Promise.all([Xs(this.options.headers),this.options.params?Js(er(this.options.params)):void 0]);o&&ws(o);let a=new URL(e);if(o){if(o.table&&P(a,is,o.table),o.where&&typeof o.where=="string"){let L=le(o.where,(l=this.options.columnMapper)==null?void 0:l.encode);P(a,as,L)}if(o.columns){let L=await Yt((g=this.options.params)==null?void 0:g.columns);if(Array.isArray(L)){let W=L.map(String);this.options.columnMapper&&(W=W.map(this.options.columnMapper.encode));let ke=W.map(Le).join(",");P(a,_t,ke)}else P(a,_t,o.columns)}o.replica&&P(a,os,o.replica),o.params&&P(a,cs,o.params);let _=y({},o);delete _.table,delete _.where,delete _.columns,delete _.replica,delete _.params;for(let[L,W]of Object.entries(_))P(a,L,W)}if(s){if(s.whereExpr){let _=qe(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);P(a,me,_),a.searchParams.set(Mt,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let _=le(s.where,(R=this.options.columnMapper)==null?void 0:R.encode);P(a,me,_)}if(s.params&&a.searchParams.set(Be,JSON.stringify(s.params)),s.limit&&P(a,He,s.limit),s.offset&&P(a,Ie,s.offset),s.orderByExpr){let _=ht(s.orderByExpr,(E=this.options.columnMapper)==null?void 0:E.encode);P(a,ge,_),a.searchParams.set(vt,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let _=le(s.orderBy,(b=this.options.columnMapper)==null?void 0:b.encode);P(a,ge,_)}}a.searchParams.set(pe,n(this,B)),a.searchParams.set(Pt,n(this,G));let h=s!==void 0;n(this,C)&&!h&&(!n(this,q)&&!t&&a.searchParams.set(H,"true"),a.searchParams.set(it,n(this,N))),n(this,T)&&a.searchParams.set(fe,n(this,T));let u=ye(a),m=$e.getExpiredHandle(u);return m&&a.searchParams.set(De,m),n(this,V)&&a.searchParams.set(at,n(this,V)),a.searchParams.sort(),{fetchUrl:a,requestHeaders:i}},ms=async function(e){var t;if(c(this,M,new AbortController),e){let s=()=>{var i;(i=n(this,M))==null||i.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,M))==null||t.abort(e.reason)),s}},Bt=async function(e){var h,u,m,l;let{headers:t,status:s}=e,i=t.get(de);if(i){let g=n(this,Y)?ye(n(this,Y)):null,S=g?$e.getExpiredHandle(g):null;if(i!==S)c(this,T,i),n(this,V)&&(c(this,V,void 0),c(this,te,0));else{if(n(this,T)===void 0)throw Ue(this,te)._++,await((h=e.body)==null?void 0:h.cancel()),n(this,te)>n(this,Me)?new w(502,void 0,void 0,{},(m=(u=n(this,Y))==null?void 0:u.toString())!=null?m:"",`CDN continues serving stale cached responses after ${n(this,Me)} 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 "${i}" 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,te)}/${n(this,Me)}).`),c(this,V,`${Date.now()}-${Math.random().toString(36).substring(2,9)}`),new Oe(`Received stale cached response with expired handle "${i}". This indicates a proxy/CDN caching misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key.`));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 "${i}" 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,T)}".`);return}}let o=t.get(nt);o&&c(this,B,o);let a=t.get(rs);a&&c(this,N,a),c(this,F,(l=n(this,F))!=null?l:ps(t)),s===204&&c(this,Q,Date.now())},dt=async function(e,t=!1){var s;if(e.length>0){c(this,he,!0);let i=e[e.length-1];if(St(i)){if(t){let a=ss(i);a&&c(this,B,a)}if(c(this,Q,Date.now()),c(this,C,!0),c(this,he,!1),(s=n(this,Te))==null||s.call(this),n(this,d,It)&&!t&&n(this,N)===n(this,X)){c(this,X,void 0);return}if(c(this,X,void 0),n(this,Y)){let a=ye(n(this,Y));Dt.recordUpToDate(a,n(this,N))}}let o=e.filter(a=>ue(a)?!n(this,Ye).shouldRejectMessage(a):!0);await p(this,d,qt).call(this,o)}},gs=async function(e){var s;if(c(this,Y,e.fetchUrl),!n(this,C)&&!n(this,d,It)){let i=ye(e.fetchUrl),o=Dt.shouldEnterReplayMode(i);o&&c(this,X,o)}let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,C)&&t&&!n(this,q)&&!e.resumingFromPause&&!n(this,Pe)?(e.fetchUrl.searchParams.set(hs,"true"),e.fetchUrl.searchParams.set(xt,"true"),p(this,d,ys).call(this,e)):p(this,d,Es).call(this,e)},Es=async function(e){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=await n(this,be).call(this,t.toString(),{signal:s.signal,headers:i});c(this,U,!0),await p(this,d,Bt).call(this,o);let a=n(this,F),u=await o.text()||"[]",m=n(this,ce).parse(u,a);await p(this,d,dt).call(this,m)},ys=async function(e){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=n(this,_e);c(this,Ve,Date.now());let a=ie(y({},i),{Accept:"text/event-stream"});try{let h=[];await Gs(t.toString(),{headers:a,fetch:o,onopen:async u=>{c(this,U,!0),await p(this,d,Bt).call(this,u)},onmessage:u=>{if(u.data){let m=n(this,F),l=n(this,ce).parse(u.data,m);h.push(l),St(l)&&(p(this,d,dt).call(this,h,!0),h=[])}},onerror:u=>{throw u},signal:s.signal})}catch(h){throw s.signal.aborted?new D:h}finally{let h=Date.now()-n(this,Ve),u=s.signal.aborted;if(h<n(this,We)&&!u)if(Ue(this,Z)._++,n(this,Z)>=n(this,ft))c(this,Pe,!0),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{let m=Math.min(n(this,mt),n(this,pt)*Math.pow(2,n(this,Z))),l=Math.floor(Math.random()*m);await new Promise(g=>setTimeout(g,l))}else h>=n(this,We)&&c(this,Z,0)}},Nt=function(){var e;n(this,O)&&n(this,A)==="active"&&(c(this,A,"pause-requested"),(e=n(this,M))==null||e.abort(wt))},Ft=function(){var e;if(n(this,O)&&(n(this,A)==="paused"||n(this,A)==="pause-requested")){if((e=this.options.signal)!=null&&e.aborted)return;n(this,A)==="pause-requested"&&c(this,A,"active"),p(this,d,je).call(this)}},Ss=async function(){return n(this,$)?n(this,$):(c(this,$,new Promise((e,t)=>{c(this,Ae,e),c(this,z,t)})),n(this,$).finally(()=>{c(this,$,void 0),c(this,Ae,void 0),c(this,z,void 0)}),n(this,$))},Rs=async function(){if(n(this,he))return n(this,j)?n(this,j):(c(this,j,new Promise(e=>{c(this,Te,e)})),n(this,j).finally(()=>{c(this,j,void 0),c(this,Te,void 0)}),n(this,j))},qt=async function(e){return c(this,we,n(this,we).then(()=>Promise.all(Array.from(n(this,K).values()).map(async([t,s])=>{try{await t(e)}catch(i){queueMicrotask(()=>{throw i})}})))),n(this,we)},$t=function(e){n(this,K).forEach(([t,s])=>{s==null||s(e)})},jt=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},bs=function(){if(p(this,d,jt).call(this)){let e=()=>{document.hidden?p(this,d,Nt).call(this):p(this,d,Ft).call(this)};document.addEventListener("visibilitychange",e),c(this,Ke,()=>{document.removeEventListener("visibilitychange",e)})}},_s=function(){if(p(this,d,jt).call(this))return;let e=2e3,t=4e3,s=Date.now(),i=setInterval(()=>{let o=Date.now(),a=o-s;s=o,a>e+t&&n(this,A)==="active"&&n(this,M)&&(c(this,q,!0),n(this,M).abort(Tt),queueMicrotask(()=>{c(this,q,!1)}))},e);typeof i=="object"&&"unref"in i&&i.unref(),c(this,ee,()=>{clearInterval(i)})},xs=function(e){c(this,B,"-1"),c(this,N,""),c(this,T,e),c(this,C,!1),c(this,he,!0),c(this,U,!1),c(this,F,void 0),c(this,J,0),c(this,Z,0),c(this,Pe,!1),c(this,V,void 0),c(this,te,0)},As=function(e){var s,i,o,a;let t={};return e.whereExpr?(t.where=qe(e.whereExpr,(s=this.options.columnMapper)==null?void 0:s.encode),t.where_expr=e.whereExpr):e.where&&typeof e.where=="string"&&(t.where=le(e.where,(i=this.options.columnMapper)==null?void 0:i.encode)),e.params&&(t.params=e.params),e.limit!==void 0&&(t.limit=e.limit),e.offset!==void 0&&(t.offset=e.offset),e.orderByExpr?(t.order_by=ht(e.orderByExpr,(o=this.options.columnMapper)==null?void 0:o.encode),t.order_by_expr=e.orderByExpr):e.orderBy&&typeof e.orderBy=="string"&&(t.order_by=le(e.orderBy,(a=this.options.columnMapper)==null?void 0:a.encode)),t},Ht.Replica={FULL:"full",DEFAULT:"default"};function ps(r,e){let t=r.get(bt);if(!t){if(e!=null&&e.required&&(e!=null&&e.url))throw new ae(e.url,[bt]);return{}}return JSON.parse(t)}function ws(r){if(!r)return;let e=Object.keys(r).filter(t=>zs.has(t));if(e.length>0)throw new Ze(e)}function Zs(r){if(!r.url)throw new ze;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Je;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Xe;ws(r.params)}function P(r,e,t){if(!(t===void 0||t==null))if(typeof t=="string")r.searchParams.set(e,t);else if(typeof t=="object")for(let[s,i]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,i);else r.searchParams.set(e,t.toString())}function er(r){return Array.isArray(r.params)?ie(y({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var v,se,re,Qe,ve,Ce,ne,x,Ps,Ms,Vt,gt,vs,Wt,Ts=class{constructor(e){f(this,x);f(this,v,new Map);f(this,se,new Map);f(this,re,new Set);f(this,Qe,new Set);f(this,ve,!1);f(this,Ce,"syncing");f(this,ne,!1);this.stream=e,this.stream.subscribe(p(this,x,Ps).bind(this),p(this,x,vs).bind(this))}get isUpToDate(){return n(this,Ce)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(e=>Array.from(e.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((e,t)=>{if(this.stream.isUpToDate)e(this.currentValue);else{let s=this.subscribe(({value:i})=>{s(),n(this,ne)&&t(n(this,ne)),e(i)})}})}get currentValue(){return n(this,v)}get error(){return n(this,ne)}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(e){let t=JSON.stringify(e);n(this,Qe).add(t),await p(this,x,Vt).call(this),await this.stream.requestSnapshot(e)}subscribe(e){let t={};return n(this,se).set(t,e),()=>{n(this,se).delete(t)}}unsubscribeAll(){n(this,se).clear()}get numSubscribers(){return n(this,se).size}};v=new WeakMap,se=new WeakMap,re=new WeakMap,Qe=new WeakMap,ve=new WeakMap,Ce=new WeakMap,ne=new WeakMap,x=new WeakSet,Ps=function(e){let t=!1;e.forEach(s=>{if(ue(s))if(t=p(this,x,gt).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,v).set(s.key,s.value);break;case"update":n(this,v).set(s.key,y(y({},n(this,v).get(s.key)),s.value));break;case"delete":n(this,v).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,re).add(s.key),n(this,v).set(s.key,s.value);break;case"update":n(this,re).has(s.key)&&n(this,v).set(s.key,y(y({},n(this,v).get(s.key)),s.value));break;case"delete":n(this,re).has(s.key)&&(n(this,v).delete(s.key),n(this,re).delete(s.key));break}if(rt(s))switch(s.headers.control){case"up-to-date":t=p(this,x,gt).call(this,"up-to-date"),n(this,ve)&&(c(this,ve,!1),p(this,x,Ms).call(this));break;case"must-refetch":n(this,v).clear(),n(this,re).clear(),c(this,ne,!1),t=p(this,x,gt).call(this,"syncing"),c(this,ve,!0);break}}),t&&p(this,x,Wt).call(this)},Ms=async function(){await p(this,x,Vt).call(this),await Promise.all(Array.from(n(this,Qe)).map(async e=>{try{let t=JSON.parse(e);await this.stream.requestSnapshot(t)}catch(t){}}))},Vt=async function(){this.stream.isUpToDate||await new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),i(),e())},s=setInterval(t,10),i=this.stream.subscribe(()=>t(),()=>t());t()})},gt=function(e){let t=n(this,Ce)!==e;return c(this,Ce,e),t&&e==="up-to-date"},vs=function(e){e instanceof w&&(c(this,ne,e),p(this,x,Wt).call(this))},Wt=function(){n(this,se).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{ct as BackoffDefaults,Ct as ELECTRIC_PROTOCOL_QUERY_PARAMS,w as FetchError,Ts as Shape,Ht as ShapeStream,es as camelToSnake,qe as compileExpression,ht as compileOrderBy,ts as createColumnMapper,ue as isChangeMessage,rt as isControlMessage,Rt as isVisibleInSnapshot,Yt as resolveValue,Bs as snakeCamelMapper,yt as snakeToCamel};
6
6
  //# sourceMappingURL=index.browser.mjs.map