@electric-sql/client 1.5.0 → 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 Qt=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,y=(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 Kt=(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)||Qt("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)?Qt("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 ve=(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 Ke=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Ge=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},ze=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Je=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},Xe=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)}},Ce=class extends Error{constructor(e){super(e),this.name="StaleCacheError"}};var Ze=r=>Number(r),vs=r=>r==="true"||r==="t",Cs=r=>BigInt(r),Gt=r=>JSON.parse(r),ks=r=>r,Us={int2:Ze,int4:Ze,int8:Cs,bool:vs,float4:Ze,float8:Ze,json:Gt,jsonb:Gt};function Os(r,e){let t=0,s=null,i="",o=!1,a=0,h;function d(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(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 et=class{constructor(e,t){this.parser=y(y({},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=Kt(l,["type","dims"]),d=(g=this.parser[o])!=null?g:ks,m=zt(d,i,e);return a&&a>0?zt((R,E)=>Os(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 Xe(t!=null?t:"unknown");return null}return r(o,e)}}function ke(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,S)=>S.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 tt(r){return!le(r)}function yt(r){return tt(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",Ue="electric-handle",st="electric-offset",Rt="electric-schema",ts="electric-up-to-date",bt="columns",rt="cursor",Oe="expired_handle",de="handle",H="live",ue="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",fe="subset__where",Le="subset__limit",De="subset__offset",pe="subset__order_by",He="subset__params",Tt="subset__where_expr",Pt="subset__order_by_expr",nt="cache-buster",Mt=[H,xt,de,ue,rt,Oe,wt,fe,Le,De,pe,He,Tt,Pt,nt];var Ds=[429],at={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=at){let{initialDelay:t,maxDelay:s,multiplier:i,debug:o=!1,onFailedAttempt:a,maxRetries:h=1/0}=e;return async(...d)=>{var R;let m=d[0],l=d[1],g=t,S=0;for(;;)try{let E=await r(...d);if(E.ok)return E;throw await A.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 A&&!Ds.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 O=E instanceof A&&E.headers?Hs(E.headers["retry-after"]):0,x=Math.random()*g,L=Math.min(x,s),V=Math.max(O,L);if(o){let Me=O>0?"server+client":"client";console.log(`Retry attempt #${S} after ${V}ms (${Me}, serverMin=${O}ms, clientBackoff=${L}ms)`)}await new Promise(Me=>setTimeout(Me,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([fe,He,Le,De,pe].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 Ie,Be,v,ie,I,me,it,vt=class{constructor(e){u(this,me);u(this,Ie);u(this,Be);u(this,v,new Map);u(this,ie);u(this,I);var t;c(this,Ie,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Be,e.maxPrefetchedRequests),c(this,ie,e.url.toString()),c(this,I,n(this,ie)),p(this,me,it).call(this,e.url,e.requestInit)}abort(){n(this,v).forEach(([e,t])=>t.abort()),n(this,v).clear()}consume(...e){let t=e[0].toString(),s=n(this,v).get(t);if(!s||t!==n(this,ie))return;let[i,o]=s;if(o.signal.aborted){n(this,v).delete(t);return}return n(this,v).delete(t),i.then(a=>{let h=Ct(t,a);c(this,ie,h),n(this,I)&&!n(this,v).has(n(this,I))&&p(this,me,it).call(this,n(this,I),e[1])}).catch(()=>{}),i}};Ie=new WeakMap,Be=new WeakMap,v=new WeakMap,ie=new WeakMap,I=new WeakMap,me=new WeakSet,it=function(...e){var i,o;let t=e[0].toString();if(n(this,v).size>=n(this,Be))return;let s=new AbortController;try{let{signal:a,cleanup:h}=$s(s,(i=e[1])==null?void 0:i.signal),d=n(this,Ie).call(this,t,re(y({},(o=e[1])!=null?o:{}),{signal:a}));n(this,v).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,me,it).call(this,l,e[1])}).catch(()=>{}).finally(h)}catch(a){}};function Ct(r,e){let t=e.headers.get(Ue),s=e.headers.get(st),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(Oe);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(de,t),o.searchParams.set(ue,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 Ne(r,e){switch(r.type){case"ref":{let t=e?e(r.column):r.column;return ke(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=>Ne(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 ot(r,e){return r.map(t=>{let s=e?e(t.column):t.column,i=ke(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()}},ct=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([rt,de,H,ue,nt]);async function qt(r){return typeof r=="function"?r():r}async function Qs(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 Ks(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 Fe(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 Ee,ye,Se,ae,W,U,_,B,N,Q,M,oe,C,w,K,F,Re,k,ce,q,be,G,xe,$e,z,$,_e,J,j,je,Ye,X,ut,Ae,ft,pt,Ve,Y,Z,we,f,Dt,qe,ge,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,Ee,null);u(this,ye);u(this,Se);u(this,ae);u(this,W,new Map);u(this,U,!1);u(this,_,"active");u(this,B);u(this,N);u(this,Q);u(this,M,!1);u(this,oe,!0);u(this,C,!1);u(this,w);u(this,K);u(this,F);u(this,Re);u(this,k);u(this,ce,!1);u(this,q);u(this,be);u(this,G);u(this,xe,Promise.resolve([]));u(this,$e,new ht);u(this,z,0);u(this,$);u(this,_e);u(this,J);u(this,j);u(this,je);u(this,Ye,1e3);u(this,X,0);u(this,ut,3);u(this,Ae,!1);u(this,ft,100);u(this,pt,5e3);u(this,Ve);u(this,Y);u(this,Z,0);u(this,we,3);var a,h,d,m;this.options=y({subscribe:!0},e),Gs(this.options),c(this,B,(a=this.options.offset)!=null?a:"-1"),c(this,N,""),c(this,w,this.options.handle);let t;if(e.columnMapper){let l=g=>{let S={};for(let[R,E]of Object.entries(g)){let O=e.columnMapper.decode(R);S[O]=E}return S};t=e.transformer?g=>e.transformer(l(g)):l}else t=e.transformer;c(this,ae,new et(e.parser,t)),c(this,Re,this.options.onError),c(this,K,(h=this.options.log)!=null?h:"full");let s=(d=e.fetchClient)!=null?d:(...l)=>fetch(...l),i=re(y({},(m=e.backoffOptions)!=null?m:at),{onFailedAttempt:()=>{var l,g;c(this,C,!1),(g=(l=e.backoffOptions)==null?void 0:l.onFailedAttempt)==null||g.call(l)}}),o=os(s,i);c(this,Se,ls(hs(o))),c(this,ye,cs(n(this,Se))),p(this,f,ys).call(this)}get shapeHandle(){return n(this,w)}get error(){return n(this,Ee)}get isUpToDate(){return n(this,M)}get lastOffset(){return n(this,B)}get mode(){return n(this,K)}subscribe(e,t=()=>{}){let s={};return n(this,W).set(s,[e,t]),n(this,U)||p(this,f,qe).call(this),()=>{n(this,W).delete(s)}}unsubscribeAll(){var e;n(this,W).clear(),(e=n(this,Ve))==null||e.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,C)}isLoading(){return!n(this,M)}hasStarted(){return n(this,U)}isPaused(){return n(this,_)==="paused"}async forceDisconnectAndRefresh(){var e,t;c(this,ce,!0),n(this,M)&&!((e=n(this,k))!=null&&e.signal.aborted)&&((t=n(this,k))==null||t.abort(_t)),await p(this,f,gs).call(this),c(this,ce,!1)}async requestSnapshot(e){if(n(this,K)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,K)} mode, as the consumer is guaranteed to observe all data`);n(this,U)||await p(this,f,qe).call(this),await p(this,f,Es).call(this),ve(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:y({control:"snapshot-end"},t)},{headers:y({control:"subset-end"},e)}]);return n(this,$e).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,f,dt).call(this,i,!1),{metadata:t,data:s}}finally{ve(this,z)._--,n(this,z)===0&&p(this,f,Bt).call(this)}}async fetchSnapshot(e){var g,S,R;let s=((S=(g=e.method)!=null?g:this.options.subsetMethod)!=null?S:"GET")==="POST",i,o;if(s){let E=await p(this,f,lt).call(this,this.options.url,!0);i=E.fetchUrl,o={method:"POST",headers:re(y({},E.requestHeaders),{"Content-Type":"application/json"}),body:JSON.stringify(p(this,f,Rs).call(this,e))}}else{let E=await p(this,f,lt).call(this,this.options.url,!0,e);i=E.fetchUrl,o={headers:E.requestHeaders}}let a=await n(this,ye).call(this,i.toString(),o);if(!a.ok)throw await A.fromResponse(a,i.toString());let h=(R=n(this,F))!=null?R:ds(a.headers,{required:!0,url:i.toString()}),{metadata:d,data:m}=await a.json(),l=n(this,ae).parseSnapshotData(m,h);return{metadata:d,data:l}}};Ee=new WeakMap,ye=new WeakMap,Se=new WeakMap,ae=new WeakMap,W=new WeakMap,U=new WeakMap,_=new WeakMap,B=new WeakMap,N=new WeakMap,Q=new WeakMap,M=new WeakMap,oe=new WeakMap,C=new WeakMap,w=new WeakMap,K=new WeakMap,F=new WeakMap,Re=new WeakMap,k=new WeakMap,ce=new WeakMap,q=new WeakMap,be=new WeakMap,G=new WeakMap,xe=new WeakMap,$e=new WeakMap,z=new WeakMap,$=new WeakMap,_e=new WeakMap,J=new WeakMap,j=new WeakMap,je=new WeakMap,Ye=new WeakMap,X=new WeakMap,ut=new WeakMap,Ae=new WeakMap,ft=new WeakMap,pt=new WeakMap,Ve=new WeakMap,Y=new WeakMap,Z=new WeakMap,we=new WeakMap,f=new WeakSet,Dt=function(){return n(this,J)!==void 0},qe=async function(){var e,t,s,i,o;c(this,U,!0);try{await p(this,f,ge).call(this)}catch(a){if(c(this,Ee,a),n(this,Re)){let h=await n(this,Re).call(this,a),d=!(a instanceof ne);if(h&&typeof h=="object"&&d){h.params&&(this.options.params=y(y({},(e=this.options.params)!=null?e:{}),h.params)),h.headers&&(this.options.headers=y(y({},(t=this.options.headers)!=null?t:{}),h.headers)),c(this,Ee,null),c(this,U,!1),await p(this,f,qe).call(this);return}a instanceof Error&&p(this,f,Ft).call(this,a),c(this,C,!1),(s=n(this,G))==null||s.call(this);return}throw a instanceof Error&&p(this,f,Ft).call(this,a),c(this,C,!1),(i=n(this,G))==null||i.call(this),a}c(this,C,!1),(o=n(this,G))==null||o.call(this)},ge=async function(){var d,m;if(n(this,_)==="pause-requested"){c(this,_,"paused");return}if(!this.options.subscribe&&((d=this.options.signal)!=null&&d.aborted||n(this,M)))return;let e=n(this,_)==="paused";c(this,_,"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,k);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,ge).call(this);if(l instanceof D){let g=n(this,_);h.signal.aborted&&h.signal.reason===At&&g==="pause-requested"&&c(this,_,"paused");return}if(l instanceof Ce)return p(this,f,ge).call(this);if(!(l instanceof A))throw l;if(l.status==409){if(n(this,w)){let S=Fe(i);ct.markExpired(S,n(this,w))}let g=l.headers[Ue]||`${n(this,w)}-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,ge).call(this)}else throw l}finally{a&&s&&s.removeEventListener("abort",a),c(this,k,void 0)}return(m=n(this,be))==null||m.call(this),p(this,f,ge).call(this)},lt=async function(e,t,s){var l,g,S,R,E,O;let[i,o]=await Promise.all([Ks(this.options.headers),this.options.params?Qs(zs(this.options.params)):void 0]);o&&bs(o);let a=new URL(e);if(o){if(o.table&&T(a,ss,o.table),o.where&&typeof o.where=="string"){let L=he(o.where,(l=this.options.columnMapper)==null?void 0:l.encode);T(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 Me=V.map(ke).join(",");T(a,bt,Me)}else T(a,bt,o.columns)}o.replica&&T(a,ns,o.replica),o.params&&T(a,is,o.params);let x=y({},o);delete x.table,delete x.where,delete x.columns,delete x.replica,delete x.params;for(let[L,V]of Object.entries(x))T(a,L,V)}if(s){if(s.whereExpr){let x=Ne(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);T(a,fe,x),a.searchParams.set(Tt,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let x=he(s.where,(R=this.options.columnMapper)==null?void 0:R.encode);T(a,fe,x)}if(s.params&&a.searchParams.set(He,JSON.stringify(s.params)),s.limit&&T(a,Le,s.limit),s.offset&&T(a,De,s.offset),s.orderByExpr){let x=ot(s.orderByExpr,(E=this.options.columnMapper)==null?void 0:E.encode);T(a,pe,x),a.searchParams.set(Pt,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let x=he(s.orderBy,(O=this.options.columnMapper)==null?void 0:O.encode);T(a,pe,x)}}a.searchParams.set(ue,n(this,B)),a.searchParams.set(wt,n(this,K));let h=s!==void 0;n(this,M)&&!h&&(!n(this,ce)&&!t&&a.searchParams.set(H,"true"),a.searchParams.set(rt,n(this,N))),n(this,w)&&a.searchParams.set(de,n(this,w));let d=Fe(a),m=ct.getExpiredHandle(d);return m&&a.searchParams.set(Oe,m),n(this,Y)&&a.searchParams.set(nt,n(this,Y)),a.searchParams.sort(),{fetchUrl:a,requestHeaders:i}},us=async function(e){var t;if(c(this,k,new AbortController),e){let s=()=>{var i;(i=n(this,k))==null||i.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,k))==null||t.abort(e.reason)),s}},Ht=async function(e){var h,d,m,l;let{headers:t,status:s}=e,i=t.get(Ue);if(i){let g=n(this,j)?Fe(n(this,j)):null,S=g?ct.getExpiredHandle(g):null;if(i!==S)c(this,w,i),n(this,Y)&&(c(this,Y,void 0),c(this,Z,0));else{if(n(this,w)===void 0)throw ve(this,Z)._++,await((h=e.body)==null?void 0:h.cancel()),n(this,Z)>n(this,we)?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,we)} 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,we)}).`),c(this,Y,`${Date.now()}-${Math.random().toString(36).substring(2,9)}`),new Ce(`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 handle and continuing with handle "${n(this,w)}".`)}}let o=t.get(st);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,Q,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,Q,Date.now()),c(this,M,!0),c(this,oe,!1),(s=n(this,_e))==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=Fe(n(this,j));Ot.recordUpToDate(a,n(this,N))}}let o=e.filter(a=>le(a)?!n(this,$e).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,M)&&!n(this,f,Dt)){let i=Fe(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,M)&&t&&!n(this,ce)&&!e.resumingFromPause&&!n(this,Ae)?(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,ye).call(this,t.toString(),{signal:s.signal,headers:i});c(this,C,!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,Se);c(this,je,Date.now());let a=re(y({},i),{Accept:"text/event-stream"});try{let h=[];await Vs(t.toString(),{headers:a,fetch:o,onopen:async d=>{c(this,C,!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,je),d=s.signal.aborted;if(h<n(this,Ye)&&!d)if(ve(this,X)._++,n(this,X)>=n(this,ut))c(this,Ae,!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,Ye)&&c(this,X,0)}},It=function(){var e;n(this,U)&&n(this,_)==="active"&&(c(this,_,"pause-requested"),(e=n(this,k))==null||e.abort(At))},Bt=function(){var e;if(n(this,U)&&(n(this,_)==="paused"||n(this,_)==="pause-requested")){if((e=this.options.signal)!=null&&e.aborted)return;n(this,_)==="pause-requested"&&c(this,_,"active"),p(this,f,qe).call(this)}},gs=async function(){return n(this,q)?n(this,q):(c(this,q,new Promise((e,t)=>{c(this,be,e),c(this,G,t)})),n(this,q).finally(()=>{c(this,q,void 0),c(this,be,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,_e,e)})),n(this,$).finally(()=>{c(this,$,void 0),c(this,_e,void 0)}),n(this,$))},Nt=async function(e){return c(this,xe,n(this,xe).then(()=>Promise.all(Array.from(n(this,W).values()).map(async([t,s])=>{try{await t(e)}catch(i){queueMicrotask(()=>{throw i})}})))),n(this,xe)},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,Ve,()=>{document.removeEventListener("visibilitychange",e)})}},Ss=function(e){c(this,B,"-1"),c(this,N,""),c(this,w,e),c(this,M,!1),c(this,oe,!0),c(this,C,!1),c(this,F,void 0),c(this,z,0),c(this,X,0),c(this,Ae,!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=Ne(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=ot(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 Je(e)}function Gs(r){if(!r.url)throw new Ke;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Ge;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new ze;bs(r.params)}function T(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(y({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,ee,te,We,Te,Pe,se,b,_s,As,$t,mt,ws,jt,xs=class{constructor(e){u(this,b);u(this,P,new Map);u(this,ee,new Map);u(this,te,new Set);u(this,We,new Set);u(this,Te,!1);u(this,Pe,"syncing");u(this,se,!1);this.stream=e,this.stream.subscribe(p(this,b,_s).bind(this),p(this,b,ws).bind(this))}get isUpToDate(){return n(this,Pe)==="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,P)}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,We).add(t),await p(this,b,$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}};P=new WeakMap,ee=new WeakMap,te=new WeakMap,We=new WeakMap,Te=new WeakMap,Pe=new WeakMap,se=new WeakMap,b=new WeakSet,_s=function(e){let t=!1;e.forEach(s=>{if(le(s))if(t=p(this,b,mt).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,P).set(s.key,s.value);break;case"update":n(this,P).set(s.key,y(y({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,P).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,te).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,te).has(s.key)&&n(this,P).set(s.key,y(y({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,te).has(s.key)&&(n(this,P).delete(s.key),n(this,te).delete(s.key));break}if(tt(s))switch(s.headers.control){case"up-to-date":t=p(this,b,mt).call(this,"up-to-date"),n(this,Te)&&(c(this,Te,!1),p(this,b,As).call(this));break;case"must-refetch":n(this,P).clear(),n(this,te).clear(),c(this,se,!1),t=p(this,b,mt).call(this,"syncing"),c(this,Te,!0);break}}),t&&p(this,b,jt).call(this)},As=async function(){await p(this,b,$t).call(this),await Promise.all(Array.from(n(this,We)).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,Pe)!==e;return c(this,Pe,e),t&&e==="up-to-date"},ws=function(e){e instanceof A&&(c(this,se,e),p(this,b,jt).call(this))},jt=function(){n(this,ee).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{at as BackoffDefaults,Mt as ELECTRIC_PROTOCOL_QUERY_PARAMS,A as FetchError,xs as Shape,Lt as ShapeStream,Jt as camelToSnake,Ne as compileExpression,ot as compileOrderBy,Xt as createColumnMapper,le as isChangeMessage,tt 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