@electric-sql/client 1.2.1 → 1.3.0
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.
- package/dist/cjs/index.cjs +524 -564
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +10 -8
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.d.ts +10 -8
- package/dist/index.legacy-esm.js +39 -13
- package/dist/index.legacy-esm.js.map +1 -1
- package/dist/index.mjs +524 -564
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +35 -12
- package/src/column-mapper.ts +25 -0
- package/src/fetch.ts +14 -3
- package/src/helpers.ts +2 -4
- package/src/types.ts +9 -0
package/dist/cjs/index.d.cts
CHANGED
|
@@ -45,13 +45,22 @@ type MoveOutPattern = {
|
|
|
45
45
|
pos: number;
|
|
46
46
|
value: string;
|
|
47
47
|
};
|
|
48
|
+
type SubsetParams = {
|
|
49
|
+
where?: string;
|
|
50
|
+
params?: Record<string, string>;
|
|
51
|
+
limit?: number;
|
|
52
|
+
offset?: number;
|
|
53
|
+
orderBy?: string;
|
|
54
|
+
};
|
|
48
55
|
type ControlMessage = {
|
|
49
56
|
headers: (Header & {
|
|
50
57
|
control: `up-to-date` | `must-refetch`;
|
|
51
58
|
global_last_seen_lsn?: string;
|
|
52
59
|
}) | (Header & {
|
|
53
60
|
control: `snapshot-end`;
|
|
54
|
-
} & PostgresSnapshot)
|
|
61
|
+
} & PostgresSnapshot) | (Header & {
|
|
62
|
+
control: `subset-end`;
|
|
63
|
+
} & SubsetParams);
|
|
55
64
|
};
|
|
56
65
|
type EventMessage = {
|
|
57
66
|
headers: Header & {
|
|
@@ -377,13 +386,6 @@ type ExternalParamsRecord<T extends Row<unknown> = Row> = {
|
|
|
377
386
|
} & Partial<PostgresParams<T>> & {
|
|
378
387
|
[K in ReservedParamKeys]?: never;
|
|
379
388
|
};
|
|
380
|
-
type SubsetParams = {
|
|
381
|
-
where?: string;
|
|
382
|
-
params?: Record<string, string>;
|
|
383
|
-
limit?: number;
|
|
384
|
-
offset?: number;
|
|
385
|
-
orderBy?: string;
|
|
386
|
-
};
|
|
387
389
|
type ReservedParamKeys = typeof LIVE_CACHE_BUSTER_QUERY_PARAM | typeof SHAPE_HANDLE_QUERY_PARAM | typeof LIVE_QUERY_PARAM | typeof OFFSET_QUERY_PARAM | `subset__${string}`;
|
|
388
390
|
/**
|
|
389
391
|
* External headers type - what users provide.
|
package/dist/index.browser.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var gs=Object.defineProperty,Es=Object.defineProperties;var Ss=Object.getOwnPropertyDescriptors;var
|
|
1
|
+
var gs=Object.defineProperty,Es=Object.defineProperties;var Ss=Object.getOwnPropertyDescriptors;var De=Object.getOwnPropertySymbols;var Dt=Object.prototype.hasOwnProperty,Ht=Object.prototype.propertyIsEnumerable;var It=r=>{throw TypeError(r)};var Lt=(r,e,t)=>e in r?gs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,S=(r,e)=>{for(var t in e||(e={}))Dt.call(e,t)&&Lt(r,t,e[t]);if(De)for(var t of De(e))Ht.call(e,t)&&Lt(r,t,e[t]);return r},se=(r,e)=>Es(r,Ss(e));var Nt=(r,e)=>{var t={};for(var s in r)Dt.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&De)for(var s of De(r))e.indexOf(s)<0&&Ht.call(r,s)&&(t[s]=r[s]);return t};var nt=(r,e,t)=>e.has(r)||It("Cannot "+t);var n=(r,e,t)=>(nt(r,e,"read from private field"),t?t.call(r):e.get(r)),d=(r,e,t)=>e.has(r)?It("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),c=(r,e,t,s)=>(nt(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),p=(r,e,t)=>(nt(r,e,"access private method"),t);var He=(r,e,t,s)=>({set _(a){c(r,e,a,t)},get _(){return n(r,e,s)}});var _=class r extends Error{constructor(t,s,a,o,i,h){super(h||`HTTP Error ${t} at ${i}: ${s!=null?s:JSON.stringify(a)}`);this.url=i;this.name="FetchError",this.status=t,this.text=s,this.json=a,this.headers=o}static async fromResponse(t,s){let a=t.status,o=Object.fromEntries([...t.headers.entries()]),i,h,u=t.headers.get("content-type");return t.bodyUsed||(u&&u.includes("application/json")?h=await t.json():i=await t.text()),new r(a,i,h,o,s)}},O=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var Ie=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Ne=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Fe=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Be=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},qe=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var re=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(a=>{s+=`- ${a}
|
|
3
3
|
`}),s+=`
|
|
4
4
|
This is often due to a proxy not setting CORS correctly so that all Electric headers can be read by the client.`,s+=`
|
|
5
|
-
For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var qe=r=>Number(r),ys=r=>r==="true"||r==="t",Rs=r=>BigInt(r),It=r=>JSON.parse(r),bs=r=>r,As={int2:qe,int4:qe,int8:Rs,bool:ys,float4:qe,float8:qe,json:It,jsonb:It};function _s(r,e){let t=0,s=null,a="",o=!1,i=0,h;function l(u,g,A){let S=u.slice(g,A);return S=S==="NULL"?null:S,e?e(S):S}function m(u){let g=[];for(;t<u.length;t++){if(s=u[t],o)s==="\\"?a+=u[++t]:s==='"'?(g.push(e?e(a):a),a="",o=u[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,g.push(m(u));else if(s==="}"){o=!1,i<t&&g.push(l(u,i,t)),i=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(g.push(l(u,i,t)),i=t+1);h=s}return i<t&&g.push(g.push(l(u,i,t+1))),g}return m(r)[0]}var je=class{constructor(e,t){this.parser=y(y({},As),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,a)=>(s==="value"||s==="old_value")&&typeof a=="object"&&a!==null?this.transformMessageValue(a,t):a)}parseSnapshotData(e,t){return e.map(s=>{let a=s;return a.value&&typeof a.value=="object"&&a.value!==null&&(a.value=this.transformMessageValue(a.value,t)),a.old_value&&typeof a.old_value=="object"&&a.old_value!==null&&(a.old_value=this.transformMessageValue(a.old_value,t)),a})}transformMessageValue(e,t){let s=e;return Object.keys(s).forEach(a=>{s[a]=this.parseRow(a,s[a],t)}),this.transformer?this.transformer(s):s}parseRow(e,t,s){var g;let a=s[e];if(!a)return t;let u=a,{type:o,dims:i}=u,h=Ht(u,["type","dims"]),l=(g=this.parser[o])!=null?g:bs,m=Nt(l,a,e);return i&&i>0?Nt((S,R)=>_s(S,m),a,e)(t):m(t,h)}};function Nt(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new Fe(t!=null?t:"unknown");return null}return r(o,e)}}function nt(r){var h,l,m,u;let e=(l=(h=r.match(/^_+/))==null?void 0:h[0])!=null?l:"",t=r.slice(e.length),s=(u=(m=t.match(/_+$/))==null?void 0:m[0])!=null?u:"",i=(s?t.slice(0,t.length-s.length):t).toLowerCase().replace(/_+([a-z])/g,(g,A)=>A.toUpperCase());return e+i+s}function Bt(r){return r.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ft(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 Ve(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=[],a=0;for(;a<r.length;){let h=r[a];if(h==="'"||h==='"'){let l=a,m=h;for(a++;a<r.length;)if(r[a]===m)if(r[a+1]===m)a+=2;else{a++;break}else a++;s.push({start:l,end:a})}else a++}let o=h=>s.some(l=>h>=l.start&&h<l.end),i=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(i,(h,l,m)=>o(m)||t.has(h.toUpperCase())||h.startsWith("$")?h:e(h))}function xs(r){if(r){let e={};for(let t of Object.keys(r))e[t]=nt(t);return Ft(e)}return{decode:e=>nt(e),encode:e=>Bt(e)}}function ne(r){return"key"in r}function Ye(r){return!ne(r)}function at(r){return Ye(r)&&r.headers.control==="up-to-date"}function qt(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function it(r,e){let t=BigInt(r),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var jt="electric-cursor",ye="electric-handle",We="electric-offset",ot="electric-schema",Vt="electric-up-to-date",Yt="columns",Ke="cursor",ct="expired_handle",ae="handle",O="live",ie="offset",Wt="table",Kt="where",Qt="replica",$t="params",Gt="experimental_live_sse",ht="live_sse",lt="force-disconnect-and-refresh",ut="pause-stream",dt="log",Re="subset__where",be="subset__limit",Ae="subset__offset",_e="subset__order_by",xe="subset__params",ft=[O,ht,ae,ie,Ke,ct,dt,Re,be,Ae,_e,xe];var Ps=[429],$e={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function Ts(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 zt(r,e=$e){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:h=1/0}=e;return(...l)=>E(this,null,function*(){var S;let m=l[0],u=l[1],g=t,A=0;for(;;)try{let R=yield r(...l);if(R.ok)return R;throw yield x.fromResponse(R,m.toString())}catch(R){if(i==null||i(),(S=u==null?void 0:u.signal)!=null&&S.aborted)throw new U;if(R instanceof x&&!Ps.includes(R.status)&&R.status>=400&&R.status<500)throw R;{if(A++,A>h)throw o&&console.log(`Max retries reached (${A}/${h}), giving up`),R;let q=R instanceof x&&R.headers?Ts(R.headers["retry-after"]):0,ms=Math.random()*g,Ct=Math.min(ms,s),kt=Math.max(q,Ct);if(o){let st=q>0?"server+client":"client";console.log(`Retry attempt #${A} after ${kt}ms (${st}, serverMin=${q}ms, clientBackoff=${Ct}ms)`)}yield new Promise(st=>setTimeout(st,kt)),g=Math.min(g*a,s)}}})}var ws=[201,204,205];function Jt(r){return(...e)=>E(this,null,function*(){var a,o;let t=e[0],s=yield r(...e);try{if(s.status<200||ws.includes(s.status))return s;let i=yield s.text();return new Response(i,s)}catch(i){throw(o=(a=e[1])==null?void 0:a.signal)!=null&&o.aborted?new U:new x(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}})}var Ms={maxChunksToPrefetch:2};function Zt(r,e=Ms){let{maxChunksToPrefetch:t}=e,s;return(...o)=>E(this,null,function*(){let i=o[0].toString(),h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort();let l=yield r(...o),m=mt(i,l);return m&&(s=new pt({fetchClient:r,maxPrefetchedRequests:t,url:m,requestInit:o[1]})),l})}var vs=["electric-offset","electric-handle"],Cs=["electric-cursor"],ks=["electric-schema"];function Xt(r){return(...e)=>E(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,a=[],o=u=>a.push(...u.filter(g=>!s.has(g))),h=e[0].toString(),l=new URL(h);if([Re,xe,be,Ae,_e].some(u=>l.searchParams.has(u)))return t;if(o(vs),l.searchParams.get(O)==="true"&&o(Cs),(!l.searchParams.has(O)||l.searchParams.get(O)==="false")&&o(ks),a.length>0)throw new re(h,a)}return t})}var Pe,Te,L,J,D,oe,Qe,pt=class{constructor(e){d(this,oe);d(this,Pe);d(this,Te);d(this,L,new Map);d(this,J);d(this,D);var t;c(this,Pe,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Te,e.maxPrefetchedRequests),c(this,J,e.url.toString()),c(this,D,n(this,J)),p(this,oe,Qe).call(this,e.url,e.requestInit)}abort(){n(this,L).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=n(this,L).get(t))==null?void 0:a[0];if(!(!s||t!==n(this,J)))return n(this,L).delete(t),s.then(o=>{let i=mt(t,o);c(this,J,i),n(this,D)&&!n(this,L).has(n(this,D))&&p(this,oe,Qe).call(this,n(this,D),e[1])}).catch(()=>{}),s}};Pe=new WeakMap,Te=new WeakMap,L=new WeakMap,J=new WeakMap,D=new WeakMap,oe=new WeakSet,Qe=function(...e){var a,o;let t=e[0].toString();if(n(this,L).size>=n(this,Te))return;let s=new AbortController;try{let{signal:i,cleanup:h}=Us(s,(a=e[1])==null?void 0:a.signal),l=n(this,Pe).call(this,t,se(y({},(o=e[1])!=null?o:{}),{signal:i}));n(this,L).set(t,[l,s]),l.then(m=>{if(!m.ok||s.signal.aborted)return;let u=mt(t,m);if(!u||u===t){c(this,D,void 0);return}return c(this,D,u),p(this,oe,Qe).call(this,u,e[1])}).catch(()=>{}).finally(h)}catch(i){}};function mt(r,e){let t=e.headers.get(ye),s=e.headers.get(We),a=e.headers.has(Vt);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(O))return o.searchParams.set(ae,t),o.searchParams.set(ie,s),o.searchParams.sort(),o.toString()}function Us(r,e){let t=Os;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 Os(){}import{fetchEventSource as Ls}from"@microsoft/fetch-event-source";var gt=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 a=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[a]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(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()}},Et=new gt;var St=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 a=s.reduce((o,i)=>this.data[i].timestamp<this.data[o].timestamp?i:o);delete this.data[a]}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 a of t)e-this.data[a].timestamp>this.cacheTTL&&(delete this.data[a],s=!0);s&&this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(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()}},yt=new St;var Ge=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,h,l;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=(i=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?i:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let a=(l=(h=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:h.add(e.snapshot_mark))!=null?l:new Set([e.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(e.database_lsn),a)}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[a,o]of this.xmaxSnapshots.entries())if(s>=a)for(let i of o)this.removeSnapshot(i);return[...this.activeSnapshots.values()].some(a=>a.keys.has(e.key)&&it(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var Ds=new Set([Ke,ae,O,ie]);function ts(r){return E(this,null,function*(){return typeof r=="function"?r():r})}function Hs(r){return E(this,null,function*(){let e=Object.entries(r),t=yield Promise.all(e.map(o=>E(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield ts(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function Is(r){return E(this,null,function*(){if(!r)return{};let e=Object.entries(r),t=yield Promise.all(e.map(o=>E(this,[o],function*([s,a]){return[s,yield ts(a)]})));return Object.fromEntries(t)})}function ze(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)ft.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ce,he,le,Z,j,k,_,H,I,V,T,X,M,w,Y,N,ue,v,ee,B,de,W,fe,ve,K,F,pe,te,me,Ce,ke,Q,Ze,ge,Xe,et,Ue,f,bt,we,Me,At,ss,_t,Je,rs,ns,as,xt,Pt,is,os,Tt,wt,cs,hs,Rt=class{constructor(e){d(this,f);d(this,ce,null);d(this,he);d(this,le);d(this,Z);d(this,j,new Map);d(this,k,!1);d(this,_,"active");d(this,H);d(this,I);d(this,V);d(this,T,!1);d(this,X,!0);d(this,M,!1);d(this,w);d(this,Y);d(this,N);d(this,ue);d(this,v);d(this,ee,!1);d(this,B);d(this,de);d(this,W);d(this,fe,Promise.resolve([]));d(this,ve,new Ge);d(this,K,0);d(this,F);d(this,pe);d(this,te);d(this,me);d(this,Ce);d(this,ke,1e3);d(this,Q,0);d(this,Ze,3);d(this,ge,!1);d(this,Xe,100);d(this,et,5e3);d(this,Ue);var i,h,l,m;this.options=y({subscribe:!0},e),Ns(this.options),c(this,H,(i=this.options.offset)!=null?i:"-1"),c(this,I,""),c(this,w,this.options.handle);let t;if(e.columnMapper){let u=g=>{let A={};for(let[S,R]of Object.entries(g)){let q=e.columnMapper.decode(S);A[q]=R}return A};t=e.transformer?g=>e.transformer(u(g)):u}else t=e.transformer;c(this,Z,new je(e.parser,t)),c(this,ue,this.options.onError),c(this,Y,(h=this.options.log)!=null?h:"full");let s=(l=e.fetchClient)!=null?l:(...u)=>fetch(...u),a=se(y({},(m=e.backoffOptions)!=null?m:$e),{onFailedAttempt:()=>{var u,g;c(this,M,!1),(g=(u=e.backoffOptions)==null?void 0:u.onFailedAttempt)==null||g.call(u)}}),o=zt(s,a);c(this,le,Xt(Zt(o))),c(this,he,Jt(n(this,le))),p(this,f,cs).call(this)}get shapeHandle(){return n(this,w)}get error(){return n(this,ce)}get isUpToDate(){return n(this,T)}get lastOffset(){return n(this,H)}get mode(){return n(this,Y)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,j).set(s,[e,t]),n(this,k)||p(this,f,we).call(this),()=>{n(this,j).delete(s)}}unsubscribeAll(){var e;n(this,j).clear(),(e=n(this,Ue))==null||e.call(this)}lastSyncedAt(){return n(this,V)}lastSynced(){return n(this,V)===void 0?1/0:Date.now()-n(this,V)}isConnected(){return n(this,M)}isLoading(){return!n(this,T)}hasStarted(){return n(this,k)}isPaused(){return n(this,_)==="paused"}forceDisconnectAndRefresh(){return E(this,null,function*(){var e,t;c(this,ee,!0),n(this,T)&&!((e=n(this,v))!=null&&e.signal.aborted)&&((t=n(this,v))==null||t.abort(lt)),yield p(this,f,is).call(this),c(this,ee,!1)})}requestSnapshot(e){return E(this,null,function*(){if(n(this,Y)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,Y)} mode, as the consumer is guaranteed to observe all data`);n(this,k)||(yield p(this,f,we).call(this)),yield p(this,f,os).call(this),De(this,K)._++;try{n(this,K)===1&&p(this,f,xt).call(this);let{metadata:t,data:s}=yield this.fetchSnapshot(e),a=s.concat([{headers:y({control:"snapshot-end"},t)}]);return n(this,ve).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,f,Je).call(this,a,!1),{metadata:t,data:s}}finally{De(this,K)._--,n(this,K)===0&&p(this,f,Pt).call(this)}})}fetchSnapshot(e){return E(this,null,function*(){var m;let{fetchUrl:t,requestHeaders:s}=yield p(this,f,At).call(this,this.options.url,!0,e),a=yield n(this,he).call(this,t.toString(),{headers:s});if(!a.ok)throw new x(a.status,void 0,void 0,Object.fromEntries([...a.headers.entries()]),t.toString());let o=(m=n(this,N))!=null?m:es(a.headers,{required:!0,url:t.toString()}),{metadata:i,data:h}=yield a.json(),l=n(this,Z).parseSnapshotData(h,o);return{metadata:i,data:l}})}};ce=new WeakMap,he=new WeakMap,le=new WeakMap,Z=new WeakMap,j=new WeakMap,k=new WeakMap,_=new WeakMap,H=new WeakMap,I=new WeakMap,V=new WeakMap,T=new WeakMap,X=new WeakMap,M=new WeakMap,w=new WeakMap,Y=new WeakMap,N=new WeakMap,ue=new WeakMap,v=new WeakMap,ee=new WeakMap,B=new WeakMap,de=new WeakMap,W=new WeakMap,fe=new WeakMap,ve=new WeakMap,K=new WeakMap,F=new WeakMap,pe=new WeakMap,te=new WeakMap,me=new WeakMap,Ce=new WeakMap,ke=new WeakMap,Q=new WeakMap,Ze=new WeakMap,ge=new WeakMap,Xe=new WeakMap,et=new WeakMap,Ue=new WeakMap,f=new WeakSet,bt=function(){return n(this,te)!==void 0},we=function(){return E(this,null,function*(){var e,t,s,a,o;c(this,k,!0);try{yield p(this,f,Me).call(this)}catch(i){if(c(this,ce,i),n(this,ue)){let h=yield n(this,ue).call(this,i);if(h&&typeof h=="object"){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,ce,null),c(this,k,!1),yield p(this,f,we).call(this);return}i instanceof Error&&p(this,f,wt).call(this,i),c(this,M,!1),(s=n(this,W))==null||s.call(this);return}throw i instanceof Error&&p(this,f,wt).call(this,i),c(this,M,!1),(a=n(this,W))==null||a.call(this),i}c(this,M,!1),(o=n(this,W))==null||o.call(this)})},Me=function(){return E(this,null,function*(){var l,m;if(n(this,_)==="pause-requested"){c(this,_,"paused");return}if(!this.options.subscribe&&((l=this.options.signal)!=null&&l.aborted||n(this,T)))return;let e=n(this,_)==="paused";c(this,_,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield p(this,f,At).call(this,t,e),i=yield p(this,f,ss).call(this,s),h=n(this,v);try{yield p(this,f,rs).call(this,{fetchUrl:a,requestAbortController:h,headers:o,resumingFromPause:e})}catch(u){if((u instanceof x||u instanceof U)&&h.signal.aborted&&h.signal.reason===lt)return p(this,f,Me).call(this);if(u instanceof U){let g=n(this,_);h.signal.aborted&&h.signal.reason===ut&&g==="pause-requested"&&c(this,_,"paused");return}if(!(u instanceof x))throw u;if(u.status==409){if(n(this,w)){let A=ze(a);Et.markExpired(A,n(this,w))}let g=u.headers[ye]||`${n(this,w)}-next`;return p(this,f,hs).call(this,g),yield p(this,f,Tt).call(this,Array.isArray(u.json)?u.json:[u.json]),p(this,f,Me).call(this)}else throw u}finally{i&&s&&s.removeEventListener("abort",i),c(this,v,void 0)}return(m=n(this,de))==null||m.call(this),p(this,f,Me).call(this)})},At=function(e,t,s){return E(this,null,function*(){var u,g,A;let[a,o]=yield Promise.all([Is(this.options.headers),this.options.params?Hs(Bs(this.options.params)):void 0]);o&&ls(o);let i=new URL(e);if(o){if(o.table&&C(i,Wt,o.table),o.where&&typeof o.where=="string"){let R=Ve(o.where,(u=this.options.columnMapper)==null?void 0:u.encode);C(i,Kt,R)}o.columns&&C(i,Yt,o.columns),o.replica&&C(i,Qt,o.replica),o.params&&C(i,$t,o.params);let S=y({},o);delete S.table,delete S.where,delete S.columns,delete S.replica,delete S.params;for(let[R,q]of Object.entries(S))C(i,R,q)}if(s){if(s.where&&typeof s.where=="string"){let S=Ve(s.where,(g=this.options.columnMapper)==null?void 0:g.encode);C(i,Re,S)}if(s.params&&i.searchParams.set(xe,JSON.stringify(s.params)),s.limit&&C(i,be,s.limit),s.offset&&C(i,Ae,s.offset),s.orderBy&&typeof s.orderBy=="string"){let S=Ve(s.orderBy,(A=this.options.columnMapper)==null?void 0:A.encode);C(i,_e,S)}}i.searchParams.set(ie,n(this,H)),i.searchParams.set(dt,n(this,Y));let h=s!==void 0;n(this,T)&&!h&&(!n(this,ee)&&!t&&i.searchParams.set(O,"true"),i.searchParams.set(Ke,n(this,I))),n(this,w)&&i.searchParams.set(ae,n(this,w));let l=ze(i),m=Et.getExpiredHandle(l);return m&&i.searchParams.set(ct,m),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},ss=function(e){return E(this,null,function*(){var t;if(c(this,v,new AbortController),e){let s=()=>{var a;(a=n(this,v))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,v))==null||t.abort(e.reason)),s}})},_t=function(e){return E(this,null,function*(){var h;let{headers:t,status:s}=e,a=t.get(ye);a&&c(this,w,a);let o=t.get(We);o&&c(this,H,o);let i=t.get(jt);i&&c(this,I,i),c(this,N,(h=n(this,N))!=null?h:es(t)),s===204&&c(this,V,Date.now())})},Je=function(e,t=!1){return E(this,null,function*(){var s;if(e.length>0){c(this,X,!0);let a=e[e.length-1];if(at(a)){if(t){let i=qt(a);i&&c(this,H,i)}if(c(this,V,Date.now()),c(this,T,!0),c(this,X,!1),(s=n(this,pe))==null||s.call(this),n(this,f,bt)&&!t&&n(this,I)===n(this,te))return;if(c(this,te,void 0),n(this,me)){let i=ze(n(this,me));yt.recordUpToDate(i,n(this,I))}}let o=e.filter(i=>ne(i)?!n(this,ve).shouldRejectMessage(i):!0);yield p(this,f,Tt).call(this,o)}})},rs=function(e){return E(this,null,function*(){var s;if(c(this,me,e.fetchUrl),!n(this,T)&&!n(this,f,bt)){let a=ze(e.fetchUrl),o=yt.shouldEnterReplayMode(a);o&&c(this,te,o)}let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,T)&&t&&!n(this,ee)&&!e.resumingFromPause&&!n(this,ge)?(e.fetchUrl.searchParams.set(Gt,"true"),e.fetchUrl.searchParams.set(ht,"true"),p(this,f,as).call(this,e)):p(this,f,ns).call(this,e)})},ns=function(e){return E(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield n(this,he).call(this,t.toString(),{signal:s.signal,headers:a});c(this,M,!0),yield p(this,f,_t).call(this,o);let i=n(this,N),l=(yield o.text())||"[]",m=n(this,Z).parse(l,i);yield p(this,f,Je).call(this,m)})},as=function(e){return E(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,le);c(this,Ce,Date.now());let i=se(y({},a),{Accept:"text/event-stream"});try{let h=[];yield Ls(t.toString(),{headers:i,fetch:o,onopen:l=>E(this,null,function*(){c(this,M,!0),yield p(this,f,_t).call(this,l)}),onmessage:l=>{if(l.data){let m=n(this,N),u=n(this,Z).parse(l.data,m);h.push(u),at(u)&&(p(this,f,Je).call(this,h,!0),h=[])}},onerror:l=>{throw l},signal:s.signal})}catch(h){throw s.signal.aborted?new U:h}finally{let h=Date.now()-n(this,Ce),l=s.signal.aborted;if(h<n(this,ke)&&!l)if(De(this,Q)._++,n(this,Q)>=n(this,Ze))c(this,ge,!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,et),n(this,Xe)*Math.pow(2,n(this,Q))),u=Math.floor(Math.random()*m);yield new Promise(g=>setTimeout(g,u))}else h>=n(this,ke)&&c(this,Q,0)}})},xt=function(){var e;n(this,k)&&n(this,_)==="active"&&(c(this,_,"pause-requested"),(e=n(this,v))==null||e.abort(ut))},Pt=function(){n(this,k)&&(n(this,_)==="paused"||n(this,_)==="pause-requested")&&(n(this,_)==="pause-requested"&&c(this,_,"active"),p(this,f,we).call(this))},is=function(){return E(this,null,function*(){return n(this,B)?n(this,B):(c(this,B,new Promise((e,t)=>{c(this,de,e),c(this,W,t)})),n(this,B).finally(()=>{c(this,B,void 0),c(this,de,void 0),c(this,W,void 0)}),n(this,B))})},os=function(){return E(this,null,function*(){if(n(this,X))return n(this,F)?n(this,F):(c(this,F,new Promise(e=>{c(this,pe,e)})),n(this,F).finally(()=>{c(this,F,void 0),c(this,pe,void 0)}),n(this,F))})},Tt=function(e){return E(this,null,function*(){return c(this,fe,n(this,fe).then(()=>Promise.all(Array.from(n(this,j).values()).map(a=>E(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,fe)})},wt=function(e){n(this,j).forEach(([t,s])=>{s==null||s(e)})},cs=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?p(this,f,xt).call(this):p(this,f,Pt).call(this)};document.addEventListener("visibilitychange",e),c(this,Ue,()=>{document.removeEventListener("visibilitychange",e)})}},hs=function(e){c(this,H,"-1"),c(this,I,""),c(this,w,e),c(this,T,!1),c(this,X,!0),c(this,M,!1),c(this,N,void 0),c(this,K,0),c(this,Q,0),c(this,ge,!1)},Rt.Replica={FULL:"full",DEFAULT:"default"};function es(r,e){let t=r.get(ot);if(!t){if(e!=null&&e.required&&(e!=null&&e.url))throw new re(e.url,[ot]);return{}}return JSON.parse(t)}function ls(r){if(!r)return;let e=Object.keys(r).filter(t=>Ds.has(t));if(e.length>0)throw new Be(e)}function Ns(r){if(!r.url)throw new He;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Ie;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Ne;ls(r.params)}function C(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,a]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,a);else r.searchParams.set(e,t.toString())}function Bs(r){return Array.isArray(r.params)?se(y({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,$,G,Oe,Ee,Se,z,b,ds,fs,Mt,tt,ps,vt,us=class{constructor(e){d(this,b);d(this,P,new Map);d(this,$,new Map);d(this,G,new Set);d(this,Oe,new Set);d(this,Ee,!1);d(this,Se,"syncing");d(this,z,!1);this.stream=e,this.stream.subscribe(p(this,b,ds).bind(this),p(this,b,ps).bind(this))}get isUpToDate(){return n(this,Se)==="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:a})=>{s(),n(this,z)&&t(n(this,z)),e(a)})}})}get currentValue(){return n(this,P)}get error(){return n(this,z)}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}requestSnapshot(e){return E(this,null,function*(){let t=JSON.stringify(e);n(this,Oe).add(t),yield p(this,b,Mt).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,$).set(t,e),()=>{n(this,$).delete(t)}}unsubscribeAll(){n(this,$).clear()}get numSubscribers(){return n(this,$).size}};P=new WeakMap,$=new WeakMap,G=new WeakMap,Oe=new WeakMap,Ee=new WeakMap,Se=new WeakMap,z=new WeakMap,b=new WeakSet,ds=function(e){let t=!1;e.forEach(s=>{if(ne(s))if(t=p(this,b,tt).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,G).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,G).has(s.key)&&n(this,P).set(s.key,y(y({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,G).has(s.key)&&(n(this,P).delete(s.key),n(this,G).delete(s.key));break}if(Ye(s))switch(s.headers.control){case"up-to-date":t=p(this,b,tt).call(this,"up-to-date"),n(this,Ee)&&(c(this,Ee,!1),p(this,b,fs).call(this));break;case"must-refetch":n(this,P).clear(),n(this,G).clear(),c(this,z,!1),t=p(this,b,tt).call(this,"syncing"),c(this,Ee,!0);break}}),t&&p(this,b,vt).call(this)},fs=function(){return E(this,null,function*(){yield p(this,b,Mt).call(this),yield Promise.all(Array.from(n(this,Oe)).map(e=>E(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},Mt=function(){return E(this,null,function*(){this.stream.isUpToDate||(yield new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),e())},s=setInterval(t,10),a=this.stream.subscribe(()=>t(),()=>t());t()}))})},tt=function(e){let t=n(this,Se)!==e;return c(this,Se,e),t&&e==="up-to-date"},ps=function(e){e instanceof x&&(c(this,z,e),p(this,b,vt).call(this))},vt=function(){n(this,$).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{$e as BackoffDefaults,ft as ELECTRIC_PROTOCOL_QUERY_PARAMS,x as FetchError,us as Shape,Rt as ShapeStream,Bt as camelToSnake,Ft as createColumnMapper,ne as isChangeMessage,Ye as isControlMessage,it as isVisibleInSnapshot,ts as resolveValue,xs as snakeCamelMapper,nt as snakeToCamel};
|
|
5
|
+
For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var je=r=>Number(r),ys=r=>r==="true"||r==="t",Rs=r=>BigInt(r),Ft=r=>JSON.parse(r),bs=r=>r,As={int2:je,int4:je,int8:Rs,bool:ys,float4:je,float8:je,json:Ft,jsonb:Ft};function _s(r,e){let t=0,s=null,a="",o=!1,i=0,h;function u(l,g,R){let A=l.slice(g,R);return A=A==="NULL"?null:A,e?e(A):A}function m(l){let g=[];for(;t<l.length;t++){if(s=l[t],o)s==="\\"?a+=l[++t]:s==='"'?(g.push(e?e(a):a),a="",o=l[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,g.push(m(l));else if(s==="}"){o=!1,i<t&&g.push(u(l,i,t)),i=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(g.push(u(l,i,t)),i=t+1);h=s}return i<t&&g.push(g.push(u(l,i,t+1))),g}return m(r)[0]}var Ve=class{constructor(e,t){this.parser=S(S({},As),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,a)=>(s==="value"||s==="old_value")&&typeof a=="object"&&a!==null?this.transformMessageValue(a,t):a)}parseSnapshotData(e,t){return e.map(s=>{let a=s;return a.value&&typeof a.value=="object"&&a.value!==null&&(a.value=this.transformMessageValue(a.value,t)),a.old_value&&typeof a.old_value=="object"&&a.old_value!==null&&(a.old_value=this.transformMessageValue(a.old_value,t)),a})}transformMessageValue(e,t){let s=e;return Object.keys(s).forEach(a=>{s[a]=this.parseRow(a,s[a],t)}),this.transformer?this.transformer(s):s}parseRow(e,t,s){var g;let a=s[e];if(!a)return t;let l=a,{type:o,dims:i}=l,h=Nt(l,["type","dims"]),u=(g=this.parser[o])!=null?g:bs,m=Bt(u,a,e);return i&&i>0?Bt((A,E)=>_s(A,m),a,e)(t):m(t,h)}};function Bt(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new qe(t!=null?t:"unknown");return null}return r(o,e)}}function qt(r){return`"${r.replace(/"/g,'""')}"`}function at(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:"",i=(s?t.slice(0,t.length-s.length):t).toLowerCase().replace(/_+([a-z])/g,(g,R)=>R.toUpperCase());return e+i+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 Vt(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 Ye(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=[],a=0;for(;a<r.length;){let h=r[a];if(h==="'"||h==='"'){let u=a,m=h;for(a++;a<r.length;)if(r[a]===m)if(r[a+1]===m)a+=2;else{a++;break}else a++;s.push({start:u,end:a})}else a++}let o=h=>s.some(u=>h>=u.start&&h<u.end),i=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(i,(h,u,m)=>o(m)||t.has(h.toUpperCase())||h.startsWith("$")?h:e(h))}function xs(r){if(r){let e={};for(let t of Object.keys(r))e[t]=at(t);return Vt(e)}return{decode:e=>at(e),encode:e=>jt(e)}}function ne(r){return"key"in r}function We(r){return!ne(r)}function it(r){return We(r)&&r.headers.control==="up-to-date"}function Yt(r){if(r.headers.control!="up-to-date")return;let e=r.headers.global_last_seen_lsn;return e?`${e}_0`:void 0}function ot(r,e){let t=BigInt(r),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var Wt="electric-cursor",ye="electric-handle",Ke="electric-offset",ct="electric-schema",Kt="electric-up-to-date",ht="columns",Qe="cursor",lt="expired_handle",ae="handle",L="live",ie="offset",Qt="table",$t="where",Gt="replica",zt="params",Jt="experimental_live_sse",ut="live_sse",dt="force-disconnect-and-refresh",ft="pause-stream",pt="log",Re="subset__where",be="subset__limit",Ae="subset__offset",_e="subset__order_by",xe="subset__params",mt=[L,ut,ae,ie,Qe,lt,pt,Re,be,Ae,_e,xe];var Ps=[429],Ge={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function Ts(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 Zt(r,e=Ge){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:h=1/0}=e;return async(...u)=>{var A;let m=u[0],l=u[1],g=t,R=0;for(;;)try{let E=await r(...u);if(E.ok)return E;throw await _.fromResponse(E,m.toString())}catch(E){if(i==null||i(),(A=l==null?void 0:l.signal)!=null&&A.aborted)throw new O;if(E instanceof _&&!Ps.includes(E.status)&&E.status>=400&&E.status<500)throw E;{if(R++,R>h)throw o&&console.log(`Max retries reached (${R}/${h}), giving up`),E;let x=E instanceof _&&E.headers?Ts(E.headers["retry-after"]):0,z=Math.random()*g,Le=Math.min(z,s),Ot=Math.max(x,Le);if(o){let rt=x>0?"server+client":"client";console.log(`Retry attempt #${R} after ${Ot}ms (${rt}, serverMin=${x}ms, clientBackoff=${Le}ms)`)}await new Promise(rt=>setTimeout(rt,Ot)),g=Math.min(g*a,s)}}}}var ws=[201,204,205];function Xt(r){return async(...e)=>{var a,o;let t=e[0],s=await r(...e);try{if(s.status<200||ws.includes(s.status))return s;let i=await s.text();return new Response(i,s)}catch(i){throw(o=(a=e[1])==null?void 0:a.signal)!=null&&o.aborted?new O:new _(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}}}var Ms={maxChunksToPrefetch:2};function es(r,e=Ms){let{maxChunksToPrefetch:t}=e,s;return async(...o)=>{let i=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=Et(i,u);return m&&(s=new gt({fetchClient:r,maxPrefetchedRequests:t,url:m,requestInit:o[1]})),u}}var vs=["electric-offset","electric-handle"],Cs=["electric-cursor"],ks=["electric-schema"];function ts(r){return async(...e)=>{let t=await r(...e);if(t.ok){let s=t.headers,a=[],o=l=>a.push(...l.filter(g=>!s.has(g))),h=e[0].toString(),u=new URL(h);if([Re,xe,be,Ae,_e].some(l=>u.searchParams.has(l)))return t;if(o(vs),u.searchParams.get(L)==="true"&&o(Cs),(!u.searchParams.has(L)||u.searchParams.get(L)==="false")&&o(ks),a.length>0)throw new re(h,a)}return t}}var Pe,Te,M,J,D,oe,$e,gt=class{constructor(e){d(this,oe);d(this,Pe);d(this,Te);d(this,M,new Map);d(this,J);d(this,D);var t;c(this,Pe,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Te,e.maxPrefetchedRequests),c(this,J,e.url.toString()),c(this,D,n(this,J)),p(this,oe,$e).call(this,e.url,e.requestInit)}abort(){n(this,M).forEach(([e,t])=>t.abort()),n(this,M).clear()}consume(...e){let t=e[0].toString(),s=n(this,M).get(t);if(!s||t!==n(this,J))return;let[a,o]=s;if(o.signal.aborted){n(this,M).delete(t);return}return n(this,M).delete(t),a.then(i=>{let h=Et(t,i);c(this,J,h),n(this,D)&&!n(this,M).has(n(this,D))&&p(this,oe,$e).call(this,n(this,D),e[1])}).catch(()=>{}),a}};Pe=new WeakMap,Te=new WeakMap,M=new WeakMap,J=new WeakMap,D=new WeakMap,oe=new WeakSet,$e=function(...e){var a,o;let t=e[0].toString();if(n(this,M).size>=n(this,Te))return;let s=new AbortController;try{let{signal:i,cleanup:h}=Us(s,(a=e[1])==null?void 0:a.signal),u=n(this,Pe).call(this,t,se(S({},(o=e[1])!=null?o:{}),{signal:i}));n(this,M).set(t,[u,s]),u.then(m=>{if(!m.ok||s.signal.aborted)return;let l=Et(t,m);if(!l||l===t){c(this,D,void 0);return}return c(this,D,l),p(this,oe,$e).call(this,l,e[1])}).catch(()=>{}).finally(h)}catch(i){}};function Et(r,e){let t=e.headers.get(ye),s=e.headers.get(Ke),a=e.headers.has(Kt);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(L))return o.searchParams.set(ae,t),o.searchParams.set(ie,s),o.searchParams.sort(),o.toString()}function Us(r,e){let t=Os;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 Os(){}import{fetchEventSource as Ls}from"@microsoft/fetch-event-source";var St=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 a=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[a]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(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()}},yt=new St;var Rt=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 a=s.reduce((o,i)=>this.data[i].timestamp<this.data[o].timestamp?i:o);delete this.data[a]}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 a of t)e-this.data[a].timestamp>this.cacheTTL&&(delete this.data[a],s=!0);s&&this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(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()}},bt=new Rt;var ze=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,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=(i=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?i:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let a=(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),a)}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[a,o]of this.xmaxSnapshots.entries())if(s>=a)for(let i of o)this.removeSnapshot(i);return[...this.activeSnapshots.values()].some(a=>a.keys.has(e.key)&&ot(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var Ds=new Set([Qe,ae,L,ie]);async function Ct(r){return typeof r=="function"?r():r}async function Hs(r){let e=Object.entries(r),t=await Promise.all(e.map(async([s,a])=>{if(a===void 0)return[s,void 0];let o=await Ct(a);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))}async function Is(r){if(!r)return{};let e=Object.entries(r),t=await Promise.all(e.map(async([s,a])=>[s,await Ct(a)]));return Object.fromEntries(t)}function Je(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 ce,he,le,Z,q,U,b,H,I,j,T,X,C,w,V,N,ue,k,ee,F,de,Y,fe,ve,W,B,pe,te,me,Ce,ke,K,Xe,ge,et,tt,Ue,f,_t,we,Me,xt,rs,Pt,Ze,ns,as,is,Tt,wt,os,cs,Mt,vt,hs,ls,At=class{constructor(e){d(this,f);d(this,ce,null);d(this,he);d(this,le);d(this,Z);d(this,q,new Map);d(this,U,!1);d(this,b,"active");d(this,H);d(this,I);d(this,j);d(this,T,!1);d(this,X,!0);d(this,C,!1);d(this,w);d(this,V);d(this,N);d(this,ue);d(this,k);d(this,ee,!1);d(this,F);d(this,de);d(this,Y);d(this,fe,Promise.resolve([]));d(this,ve,new ze);d(this,W,0);d(this,B);d(this,pe);d(this,te);d(this,me);d(this,Ce);d(this,ke,1e3);d(this,K,0);d(this,Xe,3);d(this,ge,!1);d(this,et,100);d(this,tt,5e3);d(this,Ue);var i,h,u,m;this.options=S({subscribe:!0},e),Ns(this.options),c(this,H,(i=this.options.offset)!=null?i:"-1"),c(this,I,""),c(this,w,this.options.handle);let t;if(e.columnMapper){let l=g=>{let R={};for(let[A,E]of Object.entries(g)){let x=e.columnMapper.decode(A);R[x]=E}return R};t=e.transformer?g=>e.transformer(l(g)):l}else t=e.transformer;c(this,Z,new Ve(e.parser,t)),c(this,ue,this.options.onError),c(this,V,(h=this.options.log)!=null?h:"full");let s=(u=e.fetchClient)!=null?u:(...l)=>fetch(...l),a=se(S({},(m=e.backoffOptions)!=null?m:Ge),{onFailedAttempt:()=>{var l,g;c(this,C,!1),(g=(l=e.backoffOptions)==null?void 0:l.onFailedAttempt)==null||g.call(l)}}),o=Zt(s,a);c(this,le,ts(es(o))),c(this,he,Xt(n(this,le))),p(this,f,hs).call(this)}get shapeHandle(){return n(this,w)}get error(){return n(this,ce)}get isUpToDate(){return n(this,T)}get lastOffset(){return n(this,H)}get mode(){return n(this,V)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,q).set(s,[e,t]),n(this,U)||p(this,f,we).call(this),()=>{n(this,q).delete(s)}}unsubscribeAll(){var e;n(this,q).clear(),(e=n(this,Ue))==null||e.call(this)}lastSyncedAt(){return n(this,j)}lastSynced(){return n(this,j)===void 0?1/0:Date.now()-n(this,j)}isConnected(){return n(this,C)}isLoading(){return!n(this,T)}hasStarted(){return n(this,U)}isPaused(){return n(this,b)==="paused"}async forceDisconnectAndRefresh(){var e,t;c(this,ee,!0),n(this,T)&&!((e=n(this,k))!=null&&e.signal.aborted)&&((t=n(this,k))==null||t.abort(dt)),await p(this,f,os).call(this),c(this,ee,!1)}async requestSnapshot(e){if(n(this,V)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,V)} mode, as the consumer is guaranteed to observe all data`);n(this,U)||await p(this,f,we).call(this),await p(this,f,cs).call(this),He(this,W)._++;try{n(this,W)===1&&p(this,f,Tt).call(this);let{metadata:t,data:s}=await this.fetchSnapshot(e),a=s.concat([{headers:S({control:"snapshot-end"},t)},{headers:S({control:"subset-end"},e)}]);return n(this,ve).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,f,Ze).call(this,a,!1),{metadata:t,data:s}}finally{He(this,W)._--,n(this,W)===0&&p(this,f,wt).call(this)}}async fetchSnapshot(e){var m;let{fetchUrl:t,requestHeaders:s}=await p(this,f,xt).call(this,this.options.url,!0,e),a=await n(this,he).call(this,t.toString(),{headers:s});if(!a.ok)throw new _(a.status,void 0,void 0,Object.fromEntries([...a.headers.entries()]),t.toString());let o=(m=n(this,N))!=null?m:ss(a.headers,{required:!0,url:t.toString()}),{metadata:i,data:h}=await a.json(),u=n(this,Z).parseSnapshotData(h,o);return{metadata:i,data:u}}};ce=new WeakMap,he=new WeakMap,le=new WeakMap,Z=new WeakMap,q=new WeakMap,U=new WeakMap,b=new WeakMap,H=new WeakMap,I=new WeakMap,j=new WeakMap,T=new WeakMap,X=new WeakMap,C=new WeakMap,w=new WeakMap,V=new WeakMap,N=new WeakMap,ue=new WeakMap,k=new WeakMap,ee=new WeakMap,F=new WeakMap,de=new WeakMap,Y=new WeakMap,fe=new WeakMap,ve=new WeakMap,W=new WeakMap,B=new WeakMap,pe=new WeakMap,te=new WeakMap,me=new WeakMap,Ce=new WeakMap,ke=new WeakMap,K=new WeakMap,Xe=new WeakMap,ge=new WeakMap,et=new WeakMap,tt=new WeakMap,Ue=new WeakMap,f=new WeakSet,_t=function(){return n(this,te)!==void 0},we=async function(){var e,t,s,a,o;c(this,U,!0);try{await p(this,f,Me).call(this)}catch(i){if(c(this,ce,i),n(this,ue)){let h=await n(this,ue).call(this,i);if(h&&typeof h=="object"){h.params&&(this.options.params=S(S({},(e=this.options.params)!=null?e:{}),h.params)),h.headers&&(this.options.headers=S(S({},(t=this.options.headers)!=null?t:{}),h.headers)),c(this,ce,null),c(this,U,!1),await p(this,f,we).call(this);return}i instanceof Error&&p(this,f,vt).call(this,i),c(this,C,!1),(s=n(this,Y))==null||s.call(this);return}throw i instanceof Error&&p(this,f,vt).call(this,i),c(this,C,!1),(a=n(this,Y))==null||a.call(this),i}c(this,C,!1),(o=n(this,Y))==null||o.call(this)},Me=async function(){var u,m;if(n(this,b)==="pause-requested"){c(this,b,"paused");return}if(!this.options.subscribe&&((u=this.options.signal)!=null&&u.aborted||n(this,T)))return;let e=n(this,b)==="paused";c(this,b,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=await p(this,f,xt).call(this,t,e),i=await p(this,f,rs).call(this,s),h=n(this,k);try{await p(this,f,ns).call(this,{fetchUrl:a,requestAbortController:h,headers:o,resumingFromPause:e})}catch(l){if((l instanceof _||l instanceof O)&&h.signal.aborted&&h.signal.reason===dt)return p(this,f,Me).call(this);if(l instanceof O){let g=n(this,b);h.signal.aborted&&h.signal.reason===ft&&g==="pause-requested"&&c(this,b,"paused");return}if(!(l instanceof _))throw l;if(l.status==409){if(n(this,w)){let R=Je(a);yt.markExpired(R,n(this,w))}let g=l.headers[ye]||`${n(this,w)}-next`;return p(this,f,ls).call(this,g),await p(this,f,Mt).call(this,Array.isArray(l.json)?l.json:[l.json]),p(this,f,Me).call(this)}else throw l}finally{i&&s&&s.removeEventListener("abort",i),c(this,k,void 0)}return(m=n(this,de))==null||m.call(this),p(this,f,Me).call(this)},xt=async function(e,t,s){var l,g,R,A;let[a,o]=await Promise.all([Is(this.options.headers),this.options.params?Hs(Fs(this.options.params)):void 0]);o&&us(o);let i=new URL(e);if(o){if(o.table&&v(i,Qt,o.table),o.where&&typeof o.where=="string"){let x=Ye(o.where,(l=this.options.columnMapper)==null?void 0:l.encode);v(i,$t,x)}if(o.columns){let x=await Ct((g=this.options.params)==null?void 0:g.columns);if(Array.isArray(x)){let z=x.map(String);this.options.columnMapper&&(z=z.map(this.options.columnMapper.encode));let Le=z.map(qt).join(",");v(i,ht,Le)}else v(i,ht,o.columns)}o.replica&&v(i,Gt,o.replica),o.params&&v(i,zt,o.params);let E=S({},o);delete E.table,delete E.where,delete E.columns,delete E.replica,delete E.params;for(let[x,z]of Object.entries(E))v(i,x,z)}if(s){if(s.where&&typeof s.where=="string"){let E=Ye(s.where,(R=this.options.columnMapper)==null?void 0:R.encode);v(i,Re,E)}if(s.params&&i.searchParams.set(xe,JSON.stringify(s.params)),s.limit&&v(i,be,s.limit),s.offset&&v(i,Ae,s.offset),s.orderBy&&typeof s.orderBy=="string"){let E=Ye(s.orderBy,(A=this.options.columnMapper)==null?void 0:A.encode);v(i,_e,E)}}i.searchParams.set(ie,n(this,H)),i.searchParams.set(pt,n(this,V));let h=s!==void 0;n(this,T)&&!h&&(!n(this,ee)&&!t&&i.searchParams.set(L,"true"),i.searchParams.set(Qe,n(this,I))),n(this,w)&&i.searchParams.set(ae,n(this,w));let u=Je(i),m=yt.getExpiredHandle(u);return m&&i.searchParams.set(lt,m),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}},rs=async function(e){var t;if(c(this,k,new AbortController),e){let s=()=>{var a;(a=n(this,k))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,k))==null||t.abort(e.reason)),s}},Pt=async function(e){var h;let{headers:t,status:s}=e,a=t.get(ye);a&&c(this,w,a);let o=t.get(Ke);o&&c(this,H,o);let i=t.get(Wt);i&&c(this,I,i),c(this,N,(h=n(this,N))!=null?h:ss(t)),s===204&&c(this,j,Date.now())},Ze=async function(e,t=!1){var s;if(e.length>0){c(this,X,!0);let a=e[e.length-1];if(it(a)){if(t){let i=Yt(a);i&&c(this,H,i)}if(c(this,j,Date.now()),c(this,T,!0),c(this,X,!1),(s=n(this,pe))==null||s.call(this),n(this,f,_t)&&!t&&n(this,I)===n(this,te))return;if(c(this,te,void 0),n(this,me)){let i=Je(n(this,me));bt.recordUpToDate(i,n(this,I))}}let o=e.filter(i=>ne(i)?!n(this,ve).shouldRejectMessage(i):!0);await p(this,f,Mt).call(this,o)}},ns=async function(e){var s;if(c(this,me,e.fetchUrl),!n(this,T)&&!n(this,f,_t)){let a=Je(e.fetchUrl),o=bt.shouldEnterReplayMode(a);o&&c(this,te,o)}let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,T)&&t&&!n(this,ee)&&!e.resumingFromPause&&!n(this,ge)?(e.fetchUrl.searchParams.set(Jt,"true"),e.fetchUrl.searchParams.set(ut,"true"),p(this,f,is).call(this,e)):p(this,f,as).call(this,e)},as=async function(e){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=await n(this,he).call(this,t.toString(),{signal:s.signal,headers:a});c(this,C,!0),await p(this,f,Pt).call(this,o);let i=n(this,N),u=await o.text()||"[]",m=n(this,Z).parse(u,i);await p(this,f,Ze).call(this,m)},is=async function(e){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,le);c(this,Ce,Date.now());let i=se(S({},a),{Accept:"text/event-stream"});try{let h=[];await Ls(t.toString(),{headers:i,fetch:o,onopen:async u=>{c(this,C,!0),await p(this,f,Pt).call(this,u)},onmessage:u=>{if(u.data){let m=n(this,N),l=n(this,Z).parse(u.data,m);h.push(l),it(l)&&(p(this,f,Ze).call(this,h,!0),h=[])}},onerror:u=>{throw u},signal:s.signal})}catch(h){throw s.signal.aborted?new O:h}finally{let h=Date.now()-n(this,Ce),u=s.signal.aborted;if(h<n(this,ke)&&!u)if(He(this,K)._++,n(this,K)>=n(this,Xe))c(this,ge,!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,tt),n(this,et)*Math.pow(2,n(this,K))),l=Math.floor(Math.random()*m);await new Promise(g=>setTimeout(g,l))}else h>=n(this,ke)&&c(this,K,0)}},Tt=function(){var e;n(this,U)&&n(this,b)==="active"&&(c(this,b,"pause-requested"),(e=n(this,k))==null||e.abort(ft))},wt=function(){var e;if(n(this,U)&&(n(this,b)==="paused"||n(this,b)==="pause-requested")){if((e=this.options.signal)!=null&&e.aborted)return;n(this,b)==="pause-requested"&&c(this,b,"active"),p(this,f,we).call(this)}},os=async function(){return n(this,F)?n(this,F):(c(this,F,new Promise((e,t)=>{c(this,de,e),c(this,Y,t)})),n(this,F).finally(()=>{c(this,F,void 0),c(this,de,void 0),c(this,Y,void 0)}),n(this,F))},cs=async function(){if(n(this,X))return n(this,B)?n(this,B):(c(this,B,new Promise(e=>{c(this,pe,e)})),n(this,B).finally(()=>{c(this,B,void 0),c(this,pe,void 0)}),n(this,B))},Mt=async function(e){return c(this,fe,n(this,fe).then(()=>Promise.all(Array.from(n(this,q).values()).map(async([t,s])=>{try{await t(e)}catch(a){queueMicrotask(()=>{throw a})}})))),n(this,fe)},vt=function(e){n(this,q).forEach(([t,s])=>{s==null||s(e)})},hs=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?p(this,f,Tt).call(this):p(this,f,wt).call(this)};document.addEventListener("visibilitychange",e),c(this,Ue,()=>{document.removeEventListener("visibilitychange",e)})}},ls=function(e){c(this,H,"-1"),c(this,I,""),c(this,w,e),c(this,T,!1),c(this,X,!0),c(this,C,!1),c(this,N,void 0),c(this,W,0),c(this,K,0),c(this,ge,!1)},At.Replica={FULL:"full",DEFAULT:"default"};function ss(r,e){let t=r.get(ct);if(!t){if(e!=null&&e.required&&(e!=null&&e.url))throw new re(e.url,[ct]);return{}}return JSON.parse(t)}function us(r){if(!r)return;let e=Object.keys(r).filter(t=>Ds.has(t));if(e.length>0)throw new Be(e)}function Ns(r){if(!r.url)throw new Ie;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Ne;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Fe;us(r.params)}function v(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,a]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,a);else r.searchParams.set(e,t.toString())}function Fs(r){return Array.isArray(r.params)?se(S({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,Q,$,Oe,Ee,Se,G,y,fs,ps,kt,st,ms,Ut,ds=class{constructor(e){d(this,y);d(this,P,new Map);d(this,Q,new Map);d(this,$,new Set);d(this,Oe,new Set);d(this,Ee,!1);d(this,Se,"syncing");d(this,G,!1);this.stream=e,this.stream.subscribe(p(this,y,fs).bind(this),p(this,y,ms).bind(this))}get isUpToDate(){return n(this,Se)==="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:a})=>{s(),n(this,G)&&t(n(this,G)),e(a)})}})}get currentValue(){return n(this,P)}get error(){return n(this,G)}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,Oe).add(t),await p(this,y,kt).call(this),await this.stream.requestSnapshot(e)}subscribe(e){let t=Math.random();return n(this,Q).set(t,e),()=>{n(this,Q).delete(t)}}unsubscribeAll(){n(this,Q).clear()}get numSubscribers(){return n(this,Q).size}};P=new WeakMap,Q=new WeakMap,$=new WeakMap,Oe=new WeakMap,Ee=new WeakMap,Se=new WeakMap,G=new WeakMap,y=new WeakSet,fs=function(e){let t=!1;e.forEach(s=>{if(ne(s))if(t=p(this,y,st).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,S(S({},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,$).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,$).has(s.key)&&n(this,P).set(s.key,S(S({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,$).has(s.key)&&(n(this,P).delete(s.key),n(this,$).delete(s.key));break}if(We(s))switch(s.headers.control){case"up-to-date":t=p(this,y,st).call(this,"up-to-date"),n(this,Ee)&&(c(this,Ee,!1),p(this,y,ps).call(this));break;case"must-refetch":n(this,P).clear(),n(this,$).clear(),c(this,G,!1),t=p(this,y,st).call(this,"syncing"),c(this,Ee,!0);break}}),t&&p(this,y,Ut).call(this)},ps=async function(){await p(this,y,kt).call(this),await Promise.all(Array.from(n(this,Oe)).map(async e=>{try{let t=JSON.parse(e);await this.stream.requestSnapshot(t)}catch(t){}}))},kt=async function(){this.stream.isUpToDate||await new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),e())},s=setInterval(t,10),a=this.stream.subscribe(()=>t(),()=>t());t()})},st=function(e){let t=n(this,Se)!==e;return c(this,Se,e),t&&e==="up-to-date"},ms=function(e){e instanceof _&&(c(this,G,e),p(this,y,Ut).call(this))},Ut=function(){n(this,Q).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Ge as BackoffDefaults,mt as ELECTRIC_PROTOCOL_QUERY_PARAMS,_ as FetchError,ds as Shape,At as ShapeStream,jt as camelToSnake,Vt as createColumnMapper,ne as isChangeMessage,We as isControlMessage,ot as isVisibleInSnapshot,Ct as resolveValue,xs as snakeCamelMapper,at as snakeToCamel};
|
|
6
6
|
//# sourceMappingURL=index.browser.mjs.map
|