@electric-sql/client 1.1.3 → 1.1.5
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 +95 -41
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +17 -8
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.d.ts +17 -8
- package/dist/index.legacy-esm.js +93 -39
- package/dist/index.legacy-esm.js.map +1 -1
- package/dist/index.mjs +95 -41
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +96 -34
- package/src/parser.ts +45 -7
package/dist/cjs/index.d.cts
CHANGED
|
@@ -368,16 +368,14 @@ interface ShapeStreamInterface<T extends Row<unknown> = Row> {
|
|
|
368
368
|
error?: unknown;
|
|
369
369
|
mode: LogMode;
|
|
370
370
|
forceDisconnectAndRefresh(): Promise<void>;
|
|
371
|
-
requestSnapshot(params: {
|
|
372
|
-
where?: string;
|
|
373
|
-
params?: Record<string, string>;
|
|
374
|
-
limit: number;
|
|
375
|
-
offset?: number;
|
|
376
|
-
orderBy: string;
|
|
377
|
-
}): Promise<{
|
|
371
|
+
requestSnapshot(params: SubsetParams): Promise<{
|
|
378
372
|
metadata: SnapshotMetadata;
|
|
379
373
|
data: Array<Message<T>>;
|
|
380
374
|
}>;
|
|
375
|
+
fetchSnapshot(opts: SubsetParams): Promise<{
|
|
376
|
+
metadata: SnapshotMetadata;
|
|
377
|
+
data: Array<ChangeMessage<T>>;
|
|
378
|
+
}>;
|
|
381
379
|
}
|
|
382
380
|
/**
|
|
383
381
|
* Reads updates to a shape from Electric using HTTP requests and long polling or
|
|
@@ -451,7 +449,7 @@ declare class ShapeStream<T extends Row<unknown> = Row> implements ShapeStreamIn
|
|
|
451
449
|
*/
|
|
452
450
|
forceDisconnectAndRefresh(): Promise<void>;
|
|
453
451
|
/**
|
|
454
|
-
* Request a snapshot for subset of data.
|
|
452
|
+
* Request a snapshot for subset of data and inject it into the subscribed data stream.
|
|
455
453
|
*
|
|
456
454
|
* Only available when mode is `changes_only`.
|
|
457
455
|
* Returns the insertion point & the data, but more importantly injects the data
|
|
@@ -468,6 +466,17 @@ declare class ShapeStream<T extends Row<unknown> = Row> implements ShapeStreamIn
|
|
|
468
466
|
metadata: SnapshotMetadata;
|
|
469
467
|
data: Array<ChangeMessage<T>>;
|
|
470
468
|
}>;
|
|
469
|
+
/**
|
|
470
|
+
* Fetch a snapshot for subset of data.
|
|
471
|
+
* Returns the metadata and the data, but does not inject it into the subscribed data stream.
|
|
472
|
+
*
|
|
473
|
+
* @param opts - The options for the snapshot request.
|
|
474
|
+
* @returns The metadata and the data for the snapshot.
|
|
475
|
+
*/
|
|
476
|
+
fetchSnapshot(opts: SubsetParams): Promise<{
|
|
477
|
+
metadata: SnapshotMetadata;
|
|
478
|
+
data: Array<ChangeMessage<T>>;
|
|
479
|
+
}>;
|
|
471
480
|
}
|
|
472
481
|
|
|
473
482
|
type ShapeData<T extends Row<unknown> = Row> = Map<string, T>;
|
package/dist/index.browser.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
1
|
+
var os=Object.defineProperty,hs=Object.defineProperties;var cs=Object.getOwnPropertyDescriptors;var Ue=Object.getOwnPropertySymbols;var xt=Object.prototype.hasOwnProperty,wt=Object.prototype.propertyIsEnumerable;var Mt=n=>{throw TypeError(n)};var _t=(n,e,t)=>e in n?os(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,S=(n,e)=>{for(var t in e||(e={}))xt.call(e,t)&&_t(n,t,e[t]);if(Ue)for(var t of Ue(e))wt.call(e,t)&&_t(n,t,e[t]);return n},me=(n,e)=>hs(n,cs(e));var Tt=(n,e)=>{var t={};for(var s in n)xt.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&Ue)for(var s of Ue(n))e.indexOf(s)<0&&wt.call(n,s)&&(t[s]=n[s]);return t};var Ze=(n,e,t)=>e.has(n)||Mt("Cannot "+t);var r=(n,e,t)=>(Ze(n,e,"read from private field"),t?t.call(n):e.get(n)),l=(n,e,t)=>e.has(n)?Mt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),h=(n,e,t,s)=>(Ze(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),p=(n,e,t)=>(Ze(n,e,"access private method"),t);var Oe=(n,e,t,s)=>({set _(a){h(n,e,a,t)},get _(){return r(n,e,s)}});var g=(n,e,t)=>new Promise((s,a)=>{var o=u=>{try{c(t.next(u))}catch(m){a(m)}},i=u=>{try{c(t.throw(u))}catch(m){a(m)}},c=u=>u.done?s(u.value):Promise.resolve(u.value).then(o,i);c((t=t.apply(n,e)).next())});var A=class n extends Error{constructor(t,s,a,o,i,c){super(c||`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 fromResponse(t,s){return g(this,null,function*(){let a=t.status,o=Object.fromEntries([...t.headers.entries()]),i,c,u=t.headers.get("content-type");return t.bodyUsed||(u&&u.includes("application/json")?c=yield t.json():i=yield t.text()),new n(a,i,c,o,s)})}},U=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var He=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Le=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},De=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Ie=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},Be=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var ee=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 Be=r=>Number(r),hs=r=>r==="true"||r==="t",ls=r=>BigInt(r),Tt=r=>JSON.parse(r),fs=r=>r,us={int2:Be,int4:Be,int8:ls,bool:hs,float4:Be,float8:Be,json:Tt,jsonb:Tt};function ds(r,e){let t=0,s=null,a="",o=!1,i=0,h;function l(m,E,k){let v=m.slice(E,k);return v=v==="NULL"?null:v,e?e(v):v}function p(m){let E=[];for(;t<m.length;t++){if(s=m[t],o)s==="\\"?a+=m[++t]:s==='"'?(E.push(e?e(a):a),a="",o=m[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,E.push(p(m));else if(s==="}"){o=!1,i<t&&E.push(l(m,i,t)),i=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(E.push(l(m,i,t)),i=t+1);h=s}return i<t&&E.push(E.push(l(m,i,t+1))),E}return p(r)[0]}var Fe=class{constructor(e,t){this.parser=S(S({},us),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,a)=>{if((s==="value"||s==="old_value")&&typeof a=="object"&&a!==null){let o=a;Object.keys(o).forEach(i=>{o[i]=this.parseRow(i,o[i],t)}),this.transformer&&(a=this.transformer(a))}return a})}parseRow(e,t,s){var E;let a=s[e];if(!a)return t;let m=a,{type:o,dims:i}=m,h=wt(m,["type","dims"]),l=(E=this.parser[o])!=null?E:fs,p=Mt(l,a,e);return i&&i>0?Mt((v,b)=>ds(v,p),a,e)(t):p(t,h)}};function Mt(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new De(t!=null?t:"unknown");return null}return r(o,e)}}function ee(r){return"key"in r}function Ne(r){return!ee(r)}function Ze(r){return Ne(r)&&r.headers.control==="up-to-date"}function vt(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function et(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 Ct="electric-cursor",me="electric-handle",qe="electric-offset",kt="electric-schema",Ut="electric-up-to-date",Ot="columns",Ve="cursor",tt="expired_handle",te="handle",O="live",se="offset",Ht="table",Lt="where",Dt="replica",It="params",Bt="experimental_live_sse",st="live_sse",rt="force-disconnect-and-refresh",nt="pause-stream",it="log",ge="subset__where",Ee="subset__limit",Se="subset__offset",Re="subset__order_by",be="subset__params",at=[O,st,te,se,Ve,tt,it,ge,Ee,Se,Re,be];var ps=[429],Ye={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function ms(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 Ft(r,e=Ye){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:h=1/0}=e;return(...l)=>g(this,null,function*(){var v;let p=l[0],m=l[1],E=t,k=0;for(;;)try{let b=yield r(...l);if(b.ok)return b;throw yield y.fromResponse(b,p.toString())}catch(b){if(i==null||i(),(v=m==null?void 0:m.signal)!=null&&v.aborted)throw new U;if(b instanceof y&&!ps.includes(b.status)&&b.status>=400&&b.status<500)throw b;{if(k++,k>h)throw o&&console.log(`Max retries reached (${k}/${h}), giving up`),b;let ve=b instanceof y&&b.headers?ms(b.headers["retry-after"]):0,is=Math.random()*E,bt=Math.min(is,s),yt=Math.max(ve,bt);if(o){let ze=ve>0?"server+client":"client";console.log(`Retry attempt #${k} after ${yt}ms (${ze}, serverMin=${ve}ms, clientBackoff=${bt}ms)`)}yield new Promise(ze=>setTimeout(ze,yt)),E=Math.min(E*a,s)}}})}var gs=[201,204,205];function Nt(r){return(...e)=>g(this,null,function*(){var a,o;let t=e[0],s=yield r(...e);try{if(s.status<200||gs.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 y(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 Es={maxChunksToPrefetch:2};function qt(r,e=Es){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(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),p=ct(i,l);return p&&(s=new ot({fetchClient:r,maxPrefetchedRequests:t,url:p,requestInit:o[1]})),l})}var Ss=["electric-offset","electric-handle"],Rs=["electric-cursor"],bs=["electric-schema"];function Vt(r){return(...e)=>g(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,a=[],o=m=>a.push(...m.filter(E=>!s.has(E))),h=e[0].toString(),l=new URL(h);if([ge,be,Ee,Se,Re].some(m=>l.searchParams.has(m)))return t;if(o(Ss),l.searchParams.get(O)==="true"&&o(Rs),(!l.searchParams.has(O)||l.searchParams.get(O)==="false")&&o(bs),a.length>0)throw new Ie(h,a)}return t})}var ye,Ae,H,G,L,re,je,ot=class{constructor(e){f(this,re);f(this,ye);f(this,Ae);f(this,H,new Map);f(this,G);f(this,L);var t;c(this,ye,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Ae,e.maxPrefetchedRequests),c(this,G,e.url.toString()),c(this,L,n(this,G)),d(this,re,je).call(this,e.url,e.requestInit)}abort(){n(this,H).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=n(this,H).get(t))==null?void 0:a[0];if(!(!s||t!==n(this,G)))return n(this,H).delete(t),s.then(o=>{let i=ct(t,o);c(this,G,i),n(this,L)&&!n(this,H).has(n(this,L))&&d(this,re,je).call(this,n(this,L),e[1])}).catch(()=>{}),s}};ye=new WeakMap,Ae=new WeakMap,H=new WeakMap,G=new WeakMap,L=new WeakMap,re=new WeakSet,je=function(...e){var a,o;let t=e[0].toString();if(n(this,H).size>=n(this,Ae))return;let s=new AbortController;try{let{signal:i,cleanup:h}=ys(s,(a=e[1])==null?void 0:a.signal),l=n(this,ye).call(this,t,pe(S({},(o=e[1])!=null?o:{}),{signal:i}));n(this,H).set(t,[l,s]),l.then(p=>{if(!p.ok||s.signal.aborted)return;let m=ct(t,p);if(!m||m===t){c(this,L,void 0);return}return c(this,L,m),d(this,re,je).call(this,m,e[1])}).catch(()=>{}).finally(h)}catch(i){}};function ct(r,e){let t=e.headers.get(me),s=e.headers.get(qe),a=e.headers.has(Ut);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(O))return o.searchParams.set(te,t),o.searchParams.set(se,s),o.searchParams.sort(),o.toString()}function ys(r,e){let t=As;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 As(){}import{fetchEventSource as Ps}from"@microsoft/fetch-event-source";var ht=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()}},lt=new ht;var Qe=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)&&et(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var _s=new Set([Ve,te,O,se]);function Yt(r){return g(this,null,function*(){return typeof r=="function"?r():r})}function xs(r){return g(this,null,function*(){let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield Yt(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function ws(r){return g(this,null,function*(){if(!r)return{};let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){return[s,yield Yt(a)]})));return Object.fromEntries(t)})}function jt(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)at.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ne,ie,ae,J,N,C,P,D,z,q,w,X,T,_,V,I,oe,M,Z,B,ce,j,he,xe,Y,F,le,we,Te,Q,$e,fe,We,Ge,u,Pe,_e,ut,Qt,dt,Ke,Kt,$t,Wt,pt,mt,Gt,Jt,gt,Et,zt,Xt,Zt,ft=class{constructor(e){f(this,u);f(this,ne,null);f(this,ie);f(this,ae);f(this,J);f(this,N,new Map);f(this,C,!1);f(this,P,"active");f(this,D);f(this,z);f(this,q);f(this,w,!1);f(this,X,!0);f(this,T,!1);f(this,_);f(this,V);f(this,I);f(this,oe);f(this,M);f(this,Z,!1);f(this,B);f(this,ce);f(this,j);f(this,he,Promise.resolve([]));f(this,xe,new Qe);f(this,Y,0);f(this,F);f(this,le);f(this,we);f(this,Te,1e3);f(this,Q,0);f(this,$e,3);f(this,fe,!1);f(this,We,100);f(this,Ge,5e3);var o,i,h,l;this.options=S({subscribe:!0},e),Ts(this.options),c(this,D,(o=this.options.offset)!=null?o:"-1"),c(this,z,""),c(this,_,this.options.handle),c(this,J,new Fe(e.parser,e.transformer)),c(this,oe,this.options.onError),c(this,V,(i=this.options.log)!=null?i:"full");let t=(h=e.fetchClient)!=null?h:(...p)=>fetch(...p),s=pe(S({},(l=e.backoffOptions)!=null?l:Ye),{onFailedAttempt:()=>{var p,m;c(this,T,!1),(m=(p=e.backoffOptions)==null?void 0:p.onFailedAttempt)==null||m.call(p)}}),a=Ft(t,s);c(this,ae,Vt(qt(a))),c(this,ie,Nt(n(this,ae))),d(this,u,zt).call(this)}get shapeHandle(){return n(this,_)}get error(){return n(this,ne)}get isUpToDate(){return n(this,w)}get lastOffset(){return n(this,D)}get mode(){return n(this,V)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,N).set(s,[e,t]),n(this,C)||d(this,u,Pe).call(this),()=>{n(this,N).delete(s)}}unsubscribeAll(){n(this,N).clear()}lastSyncedAt(){return n(this,q)}lastSynced(){return n(this,q)===void 0?1/0:Date.now()-n(this,q)}isConnected(){return n(this,T)}isLoading(){return!n(this,w)}hasStarted(){return n(this,C)}isPaused(){return n(this,P)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;c(this,Z,!0),n(this,w)&&!((e=n(this,M))!=null&&e.signal.aborted)&&((t=n(this,M))==null||t.abort(rt)),yield d(this,u,Gt).call(this),c(this,Z,!1)})}requestSnapshot(e){return g(this,null,function*(){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,C)||(yield d(this,u,Pe).call(this)),yield d(this,u,Jt).call(this),ke(this,Y)._++;try{n(this,Y)===1&&d(this,u,pt).call(this);let{fetchUrl:t,requestHeaders:s}=yield d(this,u,ut).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield d(this,u,Zt).call(this,t,s),i=o.concat([{headers:S({control:"snapshot-end"},a)}]);return n(this,xe).addSnapshot(a,new Set(o.map(h=>h.key))),d(this,u,Ke).call(this,i,!1),{metadata:a,data:o}}finally{ke(this,Y)._--,n(this,Y)===0&&d(this,u,mt).call(this)}})}};ne=new WeakMap,ie=new WeakMap,ae=new WeakMap,J=new WeakMap,N=new WeakMap,C=new WeakMap,P=new WeakMap,D=new WeakMap,z=new WeakMap,q=new WeakMap,w=new WeakMap,X=new WeakMap,T=new WeakMap,_=new WeakMap,V=new WeakMap,I=new WeakMap,oe=new WeakMap,M=new WeakMap,Z=new WeakMap,B=new WeakMap,ce=new WeakMap,j=new WeakMap,he=new WeakMap,xe=new WeakMap,Y=new WeakMap,F=new WeakMap,le=new WeakMap,we=new WeakMap,Te=new WeakMap,Q=new WeakMap,$e=new WeakMap,fe=new WeakMap,We=new WeakMap,Ge=new WeakMap,u=new WeakSet,Pe=function(){return g(this,null,function*(){var e,t,s,a,o;c(this,C,!0);try{yield d(this,u,_e).call(this)}catch(i){if(c(this,ne,i),n(this,oe)){let h=yield n(this,oe).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,ne,null),c(this,C,!1),yield d(this,u,Pe).call(this);return}i instanceof Error&&d(this,u,Et).call(this,i),c(this,T,!1),(s=n(this,j))==null||s.call(this);return}throw i instanceof Error&&d(this,u,Et).call(this,i),c(this,T,!1),(a=n(this,j))==null||a.call(this),i}c(this,T,!1),(o=n(this,j))==null||o.call(this)})},_e=function(){return g(this,null,function*(){var l,p;if(n(this,P)==="pause-requested"){c(this,P,"paused");return}if(!this.options.subscribe&&((l=this.options.signal)!=null&&l.aborted||n(this,w)))return;let e=n(this,P)==="paused";c(this,P,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield d(this,u,ut).call(this,t,e),i=yield d(this,u,Qt).call(this,s),h=n(this,M);try{yield d(this,u,Kt).call(this,{fetchUrl:a,requestAbortController:h,headers:o,resumingFromPause:e})}catch(m){if((m instanceof y||m instanceof U)&&h.signal.aborted&&h.signal.reason===rt)return d(this,u,_e).call(this);if(m instanceof U){h.signal.aborted&&h.signal.reason===nt&&c(this,P,"paused");return}if(!(m instanceof y))throw m;if(m.status==409){if(n(this,_)){let k=jt(a);lt.markExpired(k,n(this,_))}let E=m.headers[me]||`${n(this,_)}-next`;return d(this,u,Xt).call(this,E),yield d(this,u,gt).call(this,Array.isArray(m.json)?m.json:[m.json]),d(this,u,_e).call(this)}else throw m}finally{i&&s&&s.removeEventListener("abort",i),c(this,M,void 0)}return(p=n(this,ce))==null||p.call(this),d(this,u,_e).call(this)})},ut=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([ws(this.options.headers),this.options.params?xs(Ms(this.options.params)):void 0]);o&&es(o);let i=new URL(e);if(o){o.table&&x(i,Ht,o.table),o.where&&x(i,Lt,o.where),o.columns&&x(i,Ot,o.columns),o.replica&&x(i,Dt,o.replica),o.params&&x(i,It,o.params);let p=S({},o);delete p.table,delete p.where,delete p.columns,delete p.replica,delete p.params;for(let[m,E]of Object.entries(p))x(i,m,E)}s&&(s.where&&x(i,ge,s.where),s.params&&x(i,be,s.params),s.limit&&x(i,Ee,s.limit),s.offset&&x(i,Se,s.offset),s.orderBy&&x(i,Re,s.orderBy)),i.searchParams.set(se,n(this,D)),i.searchParams.set(it,n(this,V)),n(this,w)&&(!n(this,Z)&&!t&&i.searchParams.set(O,"true"),i.searchParams.set(Ve,n(this,z))),n(this,_)&&i.searchParams.set(te,n(this,_));let h=jt(i),l=lt.getExpiredHandle(h);return l&&i.searchParams.set(tt,l),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Qt=function(e){return g(this,null,function*(){var t;if(c(this,M,new AbortController),e){let s=()=>{var a;(a=n(this,M))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,M))==null||t.abort(e.reason)),s}})},dt=function(e){return g(this,null,function*(){var l;let{headers:t,status:s}=e,a=t.get(me);a&&c(this,_,a);let o=t.get(qe);o&&c(this,D,o);let i=t.get(Ct);i&&c(this,z,i);let h=()=>{let p=t.get(kt);return p?JSON.parse(p):{}};c(this,I,(l=n(this,I))!=null?l:h()),s===204&&c(this,q,Date.now())})},Ke=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){c(this,X,!0);let a=e[e.length-1];if(Ze(a)){if(t){let i=vt(a);i&&c(this,D,i)}c(this,q,Date.now()),c(this,w,!0),c(this,X,!1),(s=n(this,le))==null||s.call(this)}let o=e.filter(i=>ee(i)?!n(this,xe).shouldRejectMessage(i):!0);yield d(this,u,gt).call(this,o)}})},Kt=function(e){return g(this,null,function*(){var s;let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,w)&&t&&!n(this,Z)&&!e.resumingFromPause&&!n(this,fe)?(e.fetchUrl.searchParams.set(Bt,"true"),e.fetchUrl.searchParams.set(st,"true"),d(this,u,Wt).call(this,e)):d(this,u,$t).call(this,e)})},$t=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield n(this,ie).call(this,t.toString(),{signal:s.signal,headers:a});c(this,T,!0),yield d(this,u,dt).call(this,o);let i=n(this,I),l=(yield o.text())||"[]",p=n(this,J).parse(l,i);yield d(this,u,Ke).call(this,p)})},Wt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,ae);c(this,we,Date.now());try{let i=[];yield Ps(t.toString(),{headers:a,fetch:o,onopen:h=>g(this,null,function*(){c(this,T,!0),yield d(this,u,dt).call(this,h)}),onmessage:h=>{if(h.data){let l=n(this,I),p=n(this,J).parse(h.data,l);i.push(p),Ze(p)&&(d(this,u,Ke).call(this,i,!0),i=[])}},onerror:h=>{throw h},signal:s.signal})}catch(i){throw s.signal.aborted?new U:i}finally{let i=Date.now()-n(this,we),h=s.signal.aborted;if(i<n(this,Te)&&!h)if(ke(this,Q)._++,n(this,Q)>=n(this,$e))c(this,fe,!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 l=Math.min(n(this,Ge),n(this,We)*Math.pow(2,n(this,Q))),p=Math.floor(Math.random()*l);yield new Promise(m=>setTimeout(m,p))}else i>=n(this,Te)&&c(this,Q,0)}})},pt=function(){var e;n(this,C)&&n(this,P)==="active"&&(c(this,P,"pause-requested"),(e=n(this,M))==null||e.abort(nt))},mt=function(){n(this,C)&&n(this,P)==="paused"&&d(this,u,Pe).call(this)},Gt=function(){return g(this,null,function*(){return n(this,B)?n(this,B):(c(this,B,new Promise((e,t)=>{c(this,ce,e),c(this,j,t)})),n(this,B).finally(()=>{c(this,B,void 0),c(this,ce,void 0),c(this,j,void 0)}),n(this,B))})},Jt=function(){return g(this,null,function*(){if(n(this,X))return n(this,F)?n(this,F):(c(this,F,new Promise(e=>{c(this,le,e)})),n(this,F).finally(()=>{c(this,F,void 0),c(this,le,void 0)}),n(this,F))})},gt=function(e){return g(this,null,function*(){return c(this,he,n(this,he).then(()=>Promise.all(Array.from(n(this,N).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,he)})},Et=function(e){n(this,N).forEach(([t,s])=>{s==null||s(e)})},zt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?d(this,u,pt).call(this):d(this,u,mt).call(this)};document.addEventListener("visibilitychange",e)}},Xt=function(e){c(this,D,"-1"),c(this,z,""),c(this,_,e),c(this,w,!1),c(this,X,!0),c(this,T,!1),c(this,I,void 0),c(this,Y,0),c(this,Q,0),c(this,fe,!1)},Zt=function(e,t){return g(this,null,function*(){let s=yield n(this,ie).call(this,e.toString(),{headers:t});if(!s.ok)throw new y(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString());let{metadata:a,data:o}=yield s.json(),i=n(this,J).parse(JSON.stringify(o),n(this,I));return{metadata:a,data:i}})},ft.Replica={FULL:"full",DEFAULT:"default"};function es(r){if(!r)return;let e=Object.keys(r).filter(t=>_s.has(t));if(e.length>0)throw new Le(e)}function Ts(r){if(!r.url)throw new Ue;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Oe;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new He;es(r.params)}function x(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 Ms(r){return Array.isArray(r.params)?pe(S({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var A,K,$,Me,ue,de,W,R,ss,rs,St,Je,ns,Rt,ts=class{constructor(e){f(this,R);f(this,A,new Map);f(this,K,new Map);f(this,$,new Set);f(this,Me,new Set);f(this,ue,!1);f(this,de,"syncing");f(this,W,!1);this.stream=e,this.stream.subscribe(d(this,R,ss).bind(this),d(this,R,ns).bind(this))}get isUpToDate(){return n(this,de)==="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,W)&&t(n(this,W)),e(a)})}})}get currentValue(){return n(this,A)}get error(){return n(this,W)}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 g(this,null,function*(){let t=JSON.stringify(e);n(this,Me).add(t),yield d(this,R,St).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,K).set(t,e),()=>{n(this,K).delete(t)}}unsubscribeAll(){n(this,K).clear()}get numSubscribers(){return n(this,K).size}};A=new WeakMap,K=new WeakMap,$=new WeakMap,Me=new WeakMap,ue=new WeakMap,de=new WeakMap,W=new WeakMap,R=new WeakSet,ss=function(e){let t=!1;e.forEach(s=>{if(ee(s))if(t=d(this,R,Je).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,A).set(s.key,s.value);break;case"update":n(this,A).set(s.key,S(S({},n(this,A).get(s.key)),s.value));break;case"delete":n(this,A).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,$).add(s.key),n(this,A).set(s.key,s.value);break;case"update":n(this,$).has(s.key)&&n(this,A).set(s.key,S(S({},n(this,A).get(s.key)),s.value));break;case"delete":n(this,$).has(s.key)&&(n(this,A).delete(s.key),n(this,$).delete(s.key));break}if(Ne(s))switch(s.headers.control){case"up-to-date":t=d(this,R,Je).call(this,"up-to-date"),n(this,ue)&&(c(this,ue,!1),d(this,R,rs).call(this));break;case"must-refetch":n(this,A).clear(),n(this,$).clear(),c(this,W,!1),t=d(this,R,Je).call(this,"syncing"),c(this,ue,!0);break}}),t&&d(this,R,Rt).call(this)},rs=function(){return g(this,null,function*(){yield d(this,R,St).call(this),yield Promise.all(Array.from(n(this,Me)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},St=function(){return g(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()}))})},Je=function(e){let t=n(this,de)!==e;return c(this,de,e),t&&e==="up-to-date"},ns=function(e){e instanceof y&&(c(this,W,e),d(this,R,Rt).call(this))},Rt=function(){n(this,K).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Ye as BackoffDefaults,at as ELECTRIC_PROTOCOL_QUERY_PARAMS,y as FetchError,ts as Shape,ft as ShapeStream,ee as isChangeMessage,Ne as isControlMessage,et as isVisibleInSnapshot,Yt as resolveValue};
|
|
5
|
+
For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var Fe=n=>Number(n),ls=n=>n==="true"||n==="t",us=n=>BigInt(n),vt=n=>JSON.parse(n),fs=n=>n,ds={int2:Fe,int4:Fe,int8:us,bool:ls,float4:Fe,float8:Fe,json:vt,jsonb:vt};function ps(n,e){let t=0,s=null,a="",o=!1,i=0,c;function u(f,E,x){let C=f.slice(E,x);return C=C==="NULL"?null:C,e?e(C):C}function m(f){let E=[];for(;t<f.length;t++){if(s=f[t],o)s==="\\"?a+=f[++t]:s==='"'?(E.push(e?e(a):a),a="",o=f[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,E.push(m(f));else if(s==="}"){o=!1,i<t&&E.push(u(f,i,t)),i=t+1;break}else s===","&&c!=="}"&&c!=='"'&&(E.push(u(f,i,t)),i=t+1);c=s}return i<t&&E.push(E.push(u(f,i,t+1))),E}return m(n)[0]}var qe=class{constructor(e,t){this.parser=S(S({},ds),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 E;let a=s[e];if(!a)return t;let f=a,{type:o,dims:i}=f,c=Tt(f,["type","dims"]),u=(E=this.parser[o])!=null?E:fs,m=Ct(u,a,e);return i&&i>0?Ct((C,y)=>ps(C,m),a,e)(t):m(t,c)}};function Ct(n,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new Be(t!=null?t:"unknown");return null}return n(o,e)}}function te(n){return"key"in n}function Ne(n){return!te(n)}function et(n){return Ne(n)&&n.headers.control==="up-to-date"}function kt(n){let e=n.headers.global_last_seen_lsn;if(e)return`${e}_0`}function tt(n,e){let t=BigInt(n),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var Ut="electric-cursor",ge="electric-handle",Ve="electric-offset",st="electric-schema",Ot="electric-up-to-date",Ht="columns",je="cursor",rt="expired_handle",se="handle",O="live",re="offset",Lt="table",Dt="where",It="replica",Bt="params",Ft="experimental_live_sse",nt="live_sse",at="force-disconnect-and-refresh",it="pause-stream",ot="log",Ee="subset__where",Se="subset__limit",Re="subset__offset",be="subset__order_by",ye="subset__params",ht=[O,nt,se,re,je,rt,ot,Ee,Se,Re,be,ye];var ms=[429],Qe={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function gs(n){if(!n)return 0;let e=Number(n);if(Number.isFinite(e)&&e>0)return e*1e3;let t=Date.parse(n);if(!isNaN(t)){let s=t-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function qt(n,e=Qe){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:c=1/0}=e;return(...u)=>g(this,null,function*(){var C;let m=u[0],f=u[1],E=t,x=0;for(;;)try{let y=yield n(...u);if(y.ok)return y;throw yield A.fromResponse(y,m.toString())}catch(y){if(i==null||i(),(C=f==null?void 0:f.signal)!=null&&C.aborted)throw new U;if(y instanceof A&&!ms.includes(y.status)&&y.status>=400&&y.status<500)throw y;{if(x++,x>c)throw o&&console.log(`Max retries reached (${x}/${c}), giving up`),y;let ke=y instanceof A&&y.headers?gs(y.headers["retry-after"]):0,is=Math.random()*E,At=Math.min(is,s),Pt=Math.max(ke,At);if(o){let Xe=ke>0?"server+client":"client";console.log(`Retry attempt #${x} after ${Pt}ms (${Xe}, serverMin=${ke}ms, clientBackoff=${At}ms)`)}yield new Promise(Xe=>setTimeout(Xe,Pt)),E=Math.min(E*a,s)}}})}var Es=[201,204,205];function Nt(n){return(...e)=>g(this,null,function*(){var a,o;let t=e[0],s=yield n(...e);try{if(s.status<200||Es.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 A(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 Ss={maxChunksToPrefetch:2};function Vt(n,e=Ss){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(this,null,function*(){let i=o[0].toString(),c=s==null?void 0:s.consume(...o);if(c)return c;s==null||s.abort();let u=yield n(...o),m=lt(i,u);return m&&(s=new ct({fetchClient:n,maxPrefetchedRequests:t,url:m,requestInit:o[1]})),u})}var Rs=["electric-offset","electric-handle"],bs=["electric-cursor"],ys=["electric-schema"];function jt(n){return(...e)=>g(this,null,function*(){let t=yield n(...e);if(t.ok){let s=t.headers,a=[],o=f=>a.push(...f.filter(E=>!s.has(E))),c=e[0].toString(),u=new URL(c);if([Ee,ye,Se,Re,be].some(f=>u.searchParams.has(f)))return t;if(o(Rs),u.searchParams.get(O)==="true"&&o(bs),(!u.searchParams.has(O)||u.searchParams.get(O)==="false")&&o(ys),a.length>0)throw new ee(c,a)}return t})}var Ae,Pe,H,G,L,ne,Ye,ct=class{constructor(e){l(this,ne);l(this,Ae);l(this,Pe);l(this,H,new Map);l(this,G);l(this,L);var t;h(this,Ae,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),h(this,Pe,e.maxPrefetchedRequests),h(this,G,e.url.toString()),h(this,L,r(this,G)),p(this,ne,Ye).call(this,e.url,e.requestInit)}abort(){r(this,H).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=r(this,H).get(t))==null?void 0:a[0];if(!(!s||t!==r(this,G)))return r(this,H).delete(t),s.then(o=>{let i=lt(t,o);h(this,G,i),r(this,L)&&!r(this,H).has(r(this,L))&&p(this,ne,Ye).call(this,r(this,L),e[1])}).catch(()=>{}),s}};Ae=new WeakMap,Pe=new WeakMap,H=new WeakMap,G=new WeakMap,L=new WeakMap,ne=new WeakSet,Ye=function(...e){var a,o;let t=e[0].toString();if(r(this,H).size>=r(this,Pe))return;let s=new AbortController;try{let{signal:i,cleanup:c}=As(s,(a=e[1])==null?void 0:a.signal),u=r(this,Ae).call(this,t,me(S({},(o=e[1])!=null?o:{}),{signal:i}));r(this,H).set(t,[u,s]),u.then(m=>{if(!m.ok||s.signal.aborted)return;let f=lt(t,m);if(!f||f===t){h(this,L,void 0);return}return h(this,L,f),p(this,ne,Ye).call(this,f,e[1])}).catch(()=>{}).finally(c)}catch(i){}};function lt(n,e){let t=e.headers.get(ge),s=e.headers.get(Ve),a=e.headers.has(Ot);if(!t||!s||a)return;let o=new URL(n);if(!o.searchParams.has(O))return o.searchParams.set(se,t),o.searchParams.set(re,s),o.searchParams.sort(),o.toString()}function As(n,e){let t=Ps;if(e)if(e.aborted)n.abort();else{let s=()=>n.abort();e.addEventListener("abort",s,{once:!0,signal:n.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:n.signal,cleanup:t}}function Ps(){}import{fetchEventSource as _s}from"@microsoft/fetch-event-source";var ut=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()}},ft=new ut;var Ke=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,c,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=(c=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:c.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)&&tt(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var xs=new Set([je,se,O,re]);function Kt(n){return g(this,null,function*(){return typeof n=="function"?n():n})}function ws(n){return g(this,null,function*(){let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield Kt(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function Ms(n){return g(this,null,function*(){if(!n)return{};let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){return[s,yield Kt(a)]})));return Object.fromEntries(t)})}function Yt(n){let e=new URL(n.origin+n.pathname);for(let[t,s]of n.searchParams)ht.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ae,ie,oe,J,q,k,b,D,z,N,M,X,T,_,V,I,he,v,Z,B,ce,j,le,we,Y,F,ue,Me,Te,Q,We,fe,Ge,Je,ve,d,_e,xe,pt,$t,mt,$e,Wt,Gt,Jt,gt,Et,zt,Xt,St,Rt,Zt,es,dt=class{constructor(e){l(this,d);l(this,ae,null);l(this,ie);l(this,oe);l(this,J);l(this,q,new Map);l(this,k,!1);l(this,b,"active");l(this,D);l(this,z);l(this,N);l(this,M,!1);l(this,X,!0);l(this,T,!1);l(this,_);l(this,V);l(this,I);l(this,he);l(this,v);l(this,Z,!1);l(this,B);l(this,ce);l(this,j);l(this,le,Promise.resolve([]));l(this,we,new Ke);l(this,Y,0);l(this,F);l(this,ue);l(this,Me);l(this,Te,1e3);l(this,Q,0);l(this,We,3);l(this,fe,!1);l(this,Ge,100);l(this,Je,5e3);l(this,ve);var o,i,c,u;this.options=S({subscribe:!0},e),Ts(this.options),h(this,D,(o=this.options.offset)!=null?o:"-1"),h(this,z,""),h(this,_,this.options.handle),h(this,J,new qe(e.parser,e.transformer)),h(this,he,this.options.onError),h(this,V,(i=this.options.log)!=null?i:"full");let t=(c=e.fetchClient)!=null?c:(...m)=>fetch(...m),s=me(S({},(u=e.backoffOptions)!=null?u:Qe),{onFailedAttempt:()=>{var m,f;h(this,T,!1),(f=(m=e.backoffOptions)==null?void 0:m.onFailedAttempt)==null||f.call(m)}}),a=qt(t,s);h(this,oe,jt(Vt(a))),h(this,ie,Nt(r(this,oe))),p(this,d,Zt).call(this)}get shapeHandle(){return r(this,_)}get error(){return r(this,ae)}get isUpToDate(){return r(this,M)}get lastOffset(){return r(this,D)}get mode(){return r(this,V)}subscribe(e,t=()=>{}){let s=Math.random();return r(this,q).set(s,[e,t]),r(this,k)||p(this,d,_e).call(this),()=>{r(this,q).delete(s)}}unsubscribeAll(){var e;r(this,q).clear(),(e=r(this,ve))==null||e.call(this)}lastSyncedAt(){return r(this,N)}lastSynced(){return r(this,N)===void 0?1/0:Date.now()-r(this,N)}isConnected(){return r(this,T)}isLoading(){return!r(this,M)}hasStarted(){return r(this,k)}isPaused(){return r(this,b)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;h(this,Z,!0),r(this,M)&&!((e=r(this,v))!=null&&e.signal.aborted)&&((t=r(this,v))==null||t.abort(at)),yield p(this,d,zt).call(this),h(this,Z,!1)})}requestSnapshot(e){return g(this,null,function*(){if(r(this,V)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,V)} mode, as the consumer is guaranteed to observe all data`);r(this,k)||(yield p(this,d,_e).call(this)),yield p(this,d,Xt).call(this),Oe(this,Y)._++;try{r(this,Y)===1&&p(this,d,gt).call(this);let{metadata:t,data:s}=yield this.fetchSnapshot(e),a=s.concat([{headers:S({control:"snapshot-end"},t)}]);return r(this,we).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,d,$e).call(this,a,!1),{metadata:t,data:s}}finally{Oe(this,Y)._--,r(this,Y)===0&&p(this,d,Et).call(this)}})}fetchSnapshot(e){return g(this,null,function*(){var m;let{fetchUrl:t,requestHeaders:s}=yield p(this,d,pt).call(this,this.options.url,!0,e),a=yield r(this,ie).call(this,t.toString(),{headers:s});if(!a.ok)throw new A(a.status,void 0,void 0,Object.fromEntries([...a.headers.entries()]),t.toString());let o=(m=r(this,I))!=null?m:Qt(a.headers,{required:!0,url:t.toString()}),{metadata:i,data:c}=yield a.json(),u=r(this,J).parseSnapshotData(c,o);return{metadata:i,data:u}})}};ae=new WeakMap,ie=new WeakMap,oe=new WeakMap,J=new WeakMap,q=new WeakMap,k=new WeakMap,b=new WeakMap,D=new WeakMap,z=new WeakMap,N=new WeakMap,M=new WeakMap,X=new WeakMap,T=new WeakMap,_=new WeakMap,V=new WeakMap,I=new WeakMap,he=new WeakMap,v=new WeakMap,Z=new WeakMap,B=new WeakMap,ce=new WeakMap,j=new WeakMap,le=new WeakMap,we=new WeakMap,Y=new WeakMap,F=new WeakMap,ue=new WeakMap,Me=new WeakMap,Te=new WeakMap,Q=new WeakMap,We=new WeakMap,fe=new WeakMap,Ge=new WeakMap,Je=new WeakMap,ve=new WeakMap,d=new WeakSet,_e=function(){return g(this,null,function*(){var e,t,s,a,o;h(this,k,!0);try{yield p(this,d,xe).call(this)}catch(i){if(h(this,ae,i),r(this,he)){let c=yield r(this,he).call(this,i);if(c&&typeof c=="object"){c.params&&(this.options.params=S(S({},(e=this.options.params)!=null?e:{}),c.params)),c.headers&&(this.options.headers=S(S({},(t=this.options.headers)!=null?t:{}),c.headers)),h(this,ae,null),h(this,k,!1),yield p(this,d,_e).call(this);return}i instanceof Error&&p(this,d,Rt).call(this,i),h(this,T,!1),(s=r(this,j))==null||s.call(this);return}throw i instanceof Error&&p(this,d,Rt).call(this,i),h(this,T,!1),(a=r(this,j))==null||a.call(this),i}h(this,T,!1),(o=r(this,j))==null||o.call(this)})},xe=function(){return g(this,null,function*(){var u,m;if(r(this,b)==="pause-requested"){h(this,b,"paused");return}if(!this.options.subscribe&&((u=this.options.signal)!=null&&u.aborted||r(this,M)))return;let e=r(this,b)==="paused";h(this,b,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield p(this,d,pt).call(this,t,e),i=yield p(this,d,$t).call(this,s),c=r(this,v);try{yield p(this,d,Wt).call(this,{fetchUrl:a,requestAbortController:c,headers:o,resumingFromPause:e})}catch(f){if((f instanceof A||f instanceof U)&&c.signal.aborted&&c.signal.reason===at)return p(this,d,xe).call(this);if(f instanceof U){let E=r(this,b);c.signal.aborted&&c.signal.reason===it&&E==="pause-requested"&&h(this,b,"paused");return}if(!(f instanceof A))throw f;if(f.status==409){if(r(this,_)){let x=Yt(a);ft.markExpired(x,r(this,_))}let E=f.headers[ge]||`${r(this,_)}-next`;return p(this,d,es).call(this,E),yield p(this,d,St).call(this,Array.isArray(f.json)?f.json:[f.json]),p(this,d,xe).call(this)}else throw f}finally{i&&s&&s.removeEventListener("abort",i),h(this,v,void 0)}return(m=r(this,ce))==null||m.call(this),p(this,d,xe).call(this)})},pt=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([Ms(this.options.headers),this.options.params?ws(vs(this.options.params)):void 0]);o&&ts(o);let i=new URL(e);if(o){o.table&&w(i,Lt,o.table),o.where&&w(i,Dt,o.where),o.columns&&w(i,Ht,o.columns),o.replica&&w(i,It,o.replica),o.params&&w(i,Bt,o.params);let f=S({},o);delete f.table,delete f.where,delete f.columns,delete f.replica,delete f.params;for(let[E,x]of Object.entries(f))w(i,E,x)}s&&(s.where&&w(i,Ee,s.where),s.params&&w(i,ye,s.params),s.limit&&w(i,Se,s.limit),s.offset&&w(i,Re,s.offset),s.orderBy&&w(i,be,s.orderBy)),i.searchParams.set(re,r(this,D)),i.searchParams.set(ot,r(this,V));let c=s!==void 0;r(this,M)&&!c&&(!r(this,Z)&&!t&&i.searchParams.set(O,"true"),i.searchParams.set(je,r(this,z))),r(this,_)&&i.searchParams.set(se,r(this,_));let u=Yt(i),m=ft.getExpiredHandle(u);return m&&i.searchParams.set(rt,m),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},$t=function(e){return g(this,null,function*(){var t;if(h(this,v,new AbortController),e){let s=()=>{var a;(a=r(this,v))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=r(this,v))==null||t.abort(e.reason)),s}})},mt=function(e){return g(this,null,function*(){var c;let{headers:t,status:s}=e,a=t.get(ge);a&&h(this,_,a);let o=t.get(Ve);o&&h(this,D,o);let i=t.get(Ut);i&&h(this,z,i),h(this,I,(c=r(this,I))!=null?c:Qt(t)),s===204&&h(this,N,Date.now())})},$e=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){h(this,X,!0);let a=e[e.length-1];if(et(a)){if(t){let i=kt(a);i&&h(this,D,i)}h(this,N,Date.now()),h(this,M,!0),h(this,X,!1),(s=r(this,ue))==null||s.call(this)}let o=e.filter(i=>te(i)?!r(this,we).shouldRejectMessage(i):!0);yield p(this,d,St).call(this,o)}})},Wt=function(e){return g(this,null,function*(){var s;let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return r(this,M)&&t&&!r(this,Z)&&!e.resumingFromPause&&!r(this,fe)?(e.fetchUrl.searchParams.set(Ft,"true"),e.fetchUrl.searchParams.set(nt,"true"),p(this,d,Jt).call(this,e)):p(this,d,Gt).call(this,e)})},Gt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield r(this,ie).call(this,t.toString(),{signal:s.signal,headers:a});h(this,T,!0),yield p(this,d,mt).call(this,o);let i=r(this,I),u=(yield o.text())||"[]",m=r(this,J).parse(u,i);yield p(this,d,$e).call(this,m)})},Jt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=r(this,oe);h(this,Me,Date.now());try{let i=[];yield _s(t.toString(),{headers:a,fetch:o,onopen:c=>g(this,null,function*(){h(this,T,!0),yield p(this,d,mt).call(this,c)}),onmessage:c=>{if(c.data){let u=r(this,I),m=r(this,J).parse(c.data,u);i.push(m),et(m)&&(p(this,d,$e).call(this,i,!0),i=[])}},onerror:c=>{throw c},signal:s.signal})}catch(i){throw s.signal.aborted?new U:i}finally{let i=Date.now()-r(this,Me),c=s.signal.aborted;if(i<r(this,Te)&&!c)if(Oe(this,Q)._++,r(this,Q)>=r(this,We))h(this,fe,!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 u=Math.min(r(this,Je),r(this,Ge)*Math.pow(2,r(this,Q))),m=Math.floor(Math.random()*u);yield new Promise(f=>setTimeout(f,m))}else i>=r(this,Te)&&h(this,Q,0)}})},gt=function(){var e;r(this,k)&&r(this,b)==="active"&&(h(this,b,"pause-requested"),(e=r(this,v))==null||e.abort(it))},Et=function(){r(this,k)&&(r(this,b)==="paused"||r(this,b)==="pause-requested")&&(r(this,b)==="pause-requested"&&h(this,b,"active"),p(this,d,_e).call(this))},zt=function(){return g(this,null,function*(){return r(this,B)?r(this,B):(h(this,B,new Promise((e,t)=>{h(this,ce,e),h(this,j,t)})),r(this,B).finally(()=>{h(this,B,void 0),h(this,ce,void 0),h(this,j,void 0)}),r(this,B))})},Xt=function(){return g(this,null,function*(){if(r(this,X))return r(this,F)?r(this,F):(h(this,F,new Promise(e=>{h(this,ue,e)})),r(this,F).finally(()=>{h(this,F,void 0),h(this,ue,void 0)}),r(this,F))})},St=function(e){return g(this,null,function*(){return h(this,le,r(this,le).then(()=>Promise.all(Array.from(r(this,q).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),r(this,le)})},Rt=function(e){r(this,q).forEach(([t,s])=>{s==null||s(e)})},Zt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?p(this,d,gt).call(this):p(this,d,Et).call(this)};document.addEventListener("visibilitychange",e),h(this,ve,()=>{document.removeEventListener("visibilitychange",e)})}},es=function(e){h(this,D,"-1"),h(this,z,""),h(this,_,e),h(this,M,!1),h(this,X,!0),h(this,T,!1),h(this,I,void 0),h(this,Y,0),h(this,Q,0),h(this,fe,!1)},dt.Replica={FULL:"full",DEFAULT:"default"};function Qt(n,e){let t=n.get(st);if(!t){if(e!=null&&e.required&&(e!=null&&e.url))throw new ee(e.url,[st]);return{}}return JSON.parse(t)}function ts(n){if(!n)return;let e=Object.keys(n).filter(t=>xs.has(t));if(e.length>0)throw new Ie(e)}function Ts(n){if(!n.url)throw new He;if(n.signal&&!(n.signal instanceof AbortSignal))throw new Le;if(n.offset!==void 0&&n.offset!=="-1"&&n.offset!=="now"&&!n.handle)throw new De;ts(n.params)}function w(n,e,t){if(!(t===void 0||t==null))if(typeof t=="string")n.searchParams.set(e,t);else if(typeof t=="object")for(let[s,a]of Object.entries(t))n.searchParams.set(`${e}[${s}]`,a);else n.searchParams.set(e,t.toString())}function vs(n){return Array.isArray(n.params)?me(S({},n),{params:Object.fromEntries(n.params.map((e,t)=>[t+1,e]))}):n}var P,K,$,Ce,de,pe,W,R,rs,ns,bt,ze,as,yt,ss=class{constructor(e){l(this,R);l(this,P,new Map);l(this,K,new Map);l(this,$,new Set);l(this,Ce,new Set);l(this,de,!1);l(this,pe,"syncing");l(this,W,!1);this.stream=e,this.stream.subscribe(p(this,R,rs).bind(this),p(this,R,as).bind(this))}get isUpToDate(){return r(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:a})=>{s(),r(this,W)&&t(r(this,W)),e(a)})}})}get currentValue(){return r(this,P)}get error(){return r(this,W)}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 g(this,null,function*(){let t=JSON.stringify(e);r(this,Ce).add(t),yield p(this,R,bt).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return r(this,K).set(t,e),()=>{r(this,K).delete(t)}}unsubscribeAll(){r(this,K).clear()}get numSubscribers(){return r(this,K).size}};P=new WeakMap,K=new WeakMap,$=new WeakMap,Ce=new WeakMap,de=new WeakMap,pe=new WeakMap,W=new WeakMap,R=new WeakSet,rs=function(e){let t=!1;e.forEach(s=>{if(te(s))if(t=p(this,R,ze).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":r(this,P).set(s.key,s.value);break;case"update":r(this,P).set(s.key,S(S({},r(this,P).get(s.key)),s.value));break;case"delete":r(this,P).delete(s.key);break}else switch(s.headers.operation){case"insert":r(this,$).add(s.key),r(this,P).set(s.key,s.value);break;case"update":r(this,$).has(s.key)&&r(this,P).set(s.key,S(S({},r(this,P).get(s.key)),s.value));break;case"delete":r(this,$).has(s.key)&&(r(this,P).delete(s.key),r(this,$).delete(s.key));break}if(Ne(s))switch(s.headers.control){case"up-to-date":t=p(this,R,ze).call(this,"up-to-date"),r(this,de)&&(h(this,de,!1),p(this,R,ns).call(this));break;case"must-refetch":r(this,P).clear(),r(this,$).clear(),h(this,W,!1),t=p(this,R,ze).call(this,"syncing"),h(this,de,!0);break}}),t&&p(this,R,yt).call(this)},ns=function(){return g(this,null,function*(){yield p(this,R,bt).call(this),yield Promise.all(Array.from(r(this,Ce)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},bt=function(){return g(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()}))})},ze=function(e){let t=r(this,pe)!==e;return h(this,pe,e),t&&e==="up-to-date"},as=function(e){e instanceof A&&(h(this,W,e),p(this,R,yt).call(this))},yt=function(){r(this,K).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Qe as BackoffDefaults,ht as ELECTRIC_PROTOCOL_QUERY_PARAMS,A as FetchError,ss as Shape,dt as ShapeStream,te as isChangeMessage,Ne as isControlMessage,tt as isVisibleInSnapshot,Kt as resolveValue};
|
|
6
6
|
//# sourceMappingURL=index.browser.mjs.map
|