@electric-sql/client 1.0.13 → 1.1.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 +10 -26
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +52 -85
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.d.ts +52 -85
- package/dist/index.legacy-esm.js +10 -26
- package/dist/index.legacy-esm.js.map +1 -1
- package/dist/index.mjs +10 -26
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +18 -51
- package/src/constants.ts +4 -0
- package/src/fetch.ts +4 -6
- package/src/helpers.ts +0 -38
- package/src/index.ts +0 -1
package/dist/cjs/index.d.cts
CHANGED
|
@@ -118,52 +118,6 @@ type Parser<Extensions = never> = {
|
|
|
118
118
|
};
|
|
119
119
|
type TransformFunction<Extensions = never> = (message: Row<Extensions>) => Row<Extensions>;
|
|
120
120
|
|
|
121
|
-
/**
|
|
122
|
-
* Type guard for checking {@link Message} is {@link ChangeMessage}.
|
|
123
|
-
*
|
|
124
|
-
* See [TS docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
|
|
125
|
-
* for information on how to use type guards.
|
|
126
|
-
*
|
|
127
|
-
* @param message - the message to check
|
|
128
|
-
* @returns true if the message is a {@link ChangeMessage}
|
|
129
|
-
*
|
|
130
|
-
* @example
|
|
131
|
-
* ```ts
|
|
132
|
-
* if (isChangeMessage(message)) {
|
|
133
|
-
* const msgChng: ChangeMessage = message // Ok
|
|
134
|
-
* const msgCtrl: ControlMessage = message // Err, type mismatch
|
|
135
|
-
* }
|
|
136
|
-
* ```
|
|
137
|
-
*/
|
|
138
|
-
declare function isChangeMessage<T extends Row<unknown> = Row>(message: Message<T>): message is ChangeMessage<T>;
|
|
139
|
-
/**
|
|
140
|
-
* Type guard for checking {@link Message} is {@link ControlMessage}.
|
|
141
|
-
*
|
|
142
|
-
* See [TS docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
|
|
143
|
-
* for information on how to use type guards.
|
|
144
|
-
*
|
|
145
|
-
* @param message - the message to check
|
|
146
|
-
* @returns true if the message is a {@link ControlMessage}
|
|
147
|
-
*
|
|
148
|
-
* * @example
|
|
149
|
-
* ```ts
|
|
150
|
-
* if (isControlMessage(message)) {
|
|
151
|
-
* const msgChng: ChangeMessage = message // Err, type mismatch
|
|
152
|
-
* const msgCtrl: ControlMessage = message // Ok
|
|
153
|
-
* }
|
|
154
|
-
* ```
|
|
155
|
-
*/
|
|
156
|
-
declare function isControlMessage<T extends Row<unknown> = Row>(message: Message<T>): message is ControlMessage;
|
|
157
|
-
/**
|
|
158
|
-
* Checks if a transaction is visible in a snapshot.
|
|
159
|
-
*
|
|
160
|
-
* @param txid - the transaction id to check
|
|
161
|
-
* @param snapshot - the information about the snapshot
|
|
162
|
-
* @returns true if the transaction is visible in the snapshot
|
|
163
|
-
*/
|
|
164
|
-
declare function isVisibleInSnapshot(txid: number | bigint | `${bigint}`, snapshot: PostgresSnapshot | NormalizedPgSnapshot): boolean;
|
|
165
|
-
type ShardSubdomainOption = `always` | `localhost` | `never` | boolean;
|
|
166
|
-
|
|
167
121
|
declare class FetchError extends Error {
|
|
168
122
|
url: string;
|
|
169
123
|
status: number;
|
|
@@ -324,49 +278,17 @@ interface ShapeStreamOptions<T = never> {
|
|
|
324
278
|
*/
|
|
325
279
|
subscribe?: boolean;
|
|
326
280
|
/**
|
|
327
|
-
*
|
|
281
|
+
* @deprecated No longer experimental, use {@link liveSse} instead.
|
|
328
282
|
*/
|
|
329
283
|
experimentalLiveSse?: boolean;
|
|
330
284
|
/**
|
|
331
|
-
*
|
|
285
|
+
* Use Server-Sent Events (SSE) for live updates.
|
|
332
286
|
*/
|
|
333
|
-
|
|
287
|
+
liveSse?: boolean;
|
|
334
288
|
/**
|
|
335
|
-
*
|
|
336
|
-
* This is useful in local development and is enabled by default for localhost URLs.
|
|
337
|
-
*
|
|
338
|
-
* See https://electric-sql.com/docs/guides/troubleshooting#slow-shapes-mdash-why-are-my-shapes-slow-in-the-browser-in-local-development
|
|
339
|
-
*
|
|
340
|
-
* When sharded, each shape stream gets a unique subdomain (e.g., `a7f2c.localhost`),
|
|
341
|
-
* which bypasses the browser HTTP/1.1 connection limits. This avoids the need to serve
|
|
342
|
-
* the development server over HTTP/2 (and thus HTTPS) in development.
|
|
343
|
-
*
|
|
344
|
-
* Options:
|
|
345
|
-
* - `'localhost'` - Automatically shard `localhost` and `*.localhost` URLs (the default)
|
|
346
|
-
* - `'always'` - Shard URLs regardless of the hostname
|
|
347
|
-
* - `'never'` - Disable sharding
|
|
348
|
-
* - `true` - Alias for `'always'`
|
|
349
|
-
* - `false` - Alias for `'never'`
|
|
350
|
-
*
|
|
351
|
-
* @default 'localhost'
|
|
352
|
-
*
|
|
353
|
-
* @example
|
|
354
|
-
* { url: 'http://localhost:3000/v1/shape', shardSubdomain: 'localhost' }
|
|
355
|
-
* // → http://a1c2f.localhost:3000/v1/shape
|
|
356
|
-
*
|
|
357
|
-
* @example
|
|
358
|
-
* { url: 'https://api.example.com', shardSubdomain: 'localhost' }
|
|
359
|
-
* // → https://api.example.com
|
|
360
|
-
*
|
|
361
|
-
* @example
|
|
362
|
-
* { url: 'https://localhost:3000', shardSubdomain: 'never' }
|
|
363
|
-
* // → https://localhost:3000
|
|
364
|
-
*
|
|
365
|
-
* @example
|
|
366
|
-
* { url: 'https://api.example.com', shardSubdomain: 'always' }
|
|
367
|
-
* // → https://b2d3g.api.example.com
|
|
289
|
+
* Initial data loading mode
|
|
368
290
|
*/
|
|
369
|
-
|
|
291
|
+
log?: LogMode;
|
|
370
292
|
signal?: AbortSignal;
|
|
371
293
|
fetchClient?: typeof fetch;
|
|
372
294
|
backoffOptions?: BackoffOptions;
|
|
@@ -430,7 +352,7 @@ interface ShapeStreamInterface<T extends Row<unknown> = Row> {
|
|
|
430
352
|
* ```
|
|
431
353
|
* const stream = new ShapeStream({
|
|
432
354
|
* url: `http://localhost:3000/v1/shape`,
|
|
433
|
-
*
|
|
355
|
+
* liveSse: true
|
|
434
356
|
* })
|
|
435
357
|
* ```
|
|
436
358
|
*
|
|
@@ -572,4 +494,49 @@ declare class Shape<T extends Row<unknown> = Row> {
|
|
|
572
494
|
get numSubscribers(): number;
|
|
573
495
|
}
|
|
574
496
|
|
|
575
|
-
|
|
497
|
+
/**
|
|
498
|
+
* Type guard for checking {@link Message} is {@link ChangeMessage}.
|
|
499
|
+
*
|
|
500
|
+
* See [TS docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
|
|
501
|
+
* for information on how to use type guards.
|
|
502
|
+
*
|
|
503
|
+
* @param message - the message to check
|
|
504
|
+
* @returns true if the message is a {@link ChangeMessage}
|
|
505
|
+
*
|
|
506
|
+
* @example
|
|
507
|
+
* ```ts
|
|
508
|
+
* if (isChangeMessage(message)) {
|
|
509
|
+
* const msgChng: ChangeMessage = message // Ok
|
|
510
|
+
* const msgCtrl: ControlMessage = message // Err, type mismatch
|
|
511
|
+
* }
|
|
512
|
+
* ```
|
|
513
|
+
*/
|
|
514
|
+
declare function isChangeMessage<T extends Row<unknown> = Row>(message: Message<T>): message is ChangeMessage<T>;
|
|
515
|
+
/**
|
|
516
|
+
* Type guard for checking {@link Message} is {@link ControlMessage}.
|
|
517
|
+
*
|
|
518
|
+
* See [TS docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
|
|
519
|
+
* for information on how to use type guards.
|
|
520
|
+
*
|
|
521
|
+
* @param message - the message to check
|
|
522
|
+
* @returns true if the message is a {@link ControlMessage}
|
|
523
|
+
*
|
|
524
|
+
* * @example
|
|
525
|
+
* ```ts
|
|
526
|
+
* if (isControlMessage(message)) {
|
|
527
|
+
* const msgChng: ChangeMessage = message // Err, type mismatch
|
|
528
|
+
* const msgCtrl: ControlMessage = message // Ok
|
|
529
|
+
* }
|
|
530
|
+
* ```
|
|
531
|
+
*/
|
|
532
|
+
declare function isControlMessage<T extends Row<unknown> = Row>(message: Message<T>): message is ControlMessage;
|
|
533
|
+
/**
|
|
534
|
+
* Checks if a transaction is visible in a snapshot.
|
|
535
|
+
*
|
|
536
|
+
* @param txid - the transaction id to check
|
|
537
|
+
* @param snapshot - the information about the snapshot
|
|
538
|
+
* @returns true if the transaction is visible in the snapshot
|
|
539
|
+
*/
|
|
540
|
+
declare function isVisibleInSnapshot(txid: number | bigint | `${bigint}`, snapshot: PostgresSnapshot | NormalizedPgSnapshot): boolean;
|
|
541
|
+
|
|
542
|
+
export { BackoffDefaults, type BackoffOptions, type BitColumn, type BpcharColumn, type ChangeMessage, type ColumnInfo, type CommonColumnProps, type ControlMessage, ELECTRIC_PROTOCOL_QUERY_PARAMS, type ExternalHeadersRecord, type ExternalParamsRecord, FetchError, type GetExtensions, type IntervalColumn, type IntervalColumnWithPrecision, type LogMode, type MaybePromise, type Message, type NormalizedPgSnapshot, type NumericColumn, type Offset, type Operation, type PostgresParams, type PostgresSnapshot, type RegularColumn, type Row, type Schema, Shape, type ShapeChangedCallback, type ShapeData, ShapeStream, type ShapeStreamInterface, type ShapeStreamOptions, type SnapshotMetadata, type SubsetParams, type TimeColumn, type TypedMessages, type Value, type VarcharColumn, isChangeMessage, isControlMessage, isVisibleInSnapshot, resolveValue };
|
package/dist/index.browser.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var $t=Object.defineProperty,Gt=Object.defineProperties;var Jt=Object.getOwnPropertyDescriptors;var _e=Object.getOwnPropertySymbols;var
|
|
1
|
+
var $t=Object.defineProperty,Gt=Object.defineProperties;var Jt=Object.getOwnPropertyDescriptors;var _e=Object.getOwnPropertySymbols;var ft=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var dt=r=>{throw TypeError(r)};var lt=(r,e,t)=>e in r?$t(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,b=(r,e)=>{for(var t in e||(e={}))ft.call(e,t)&<(r,t,e[t]);if(_e)for(var t of _e(e))ut.call(e,t)&<(r,t,e[t]);return r},le=(r,e)=>Gt(r,Jt(e));var pt=(r,e)=>{var t={};for(var s in r)ft.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&_e)for(var s of _e(r))e.indexOf(s)<0&&ut.call(r,s)&&(t[s]=r[s]);return t};var Ve=(r,e,t)=>e.has(r)||dt("Cannot "+t);var n=(r,e,t)=>(Ve(r,e,"read from private field"),t?t.call(r):e.get(r)),m=(r,e,t)=>e.has(r)?dt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),h=(r,e,t,s)=>(Ve(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),u=(r,e,t)=>(Ve(r,e,"access private method"),t);var je=(r,e,t,s)=>({set _(a){h(r,e,a,t)},get _(){return n(r,e,s)}});var E=(r,e,t)=>new Promise((s,a)=>{var o=f=>{try{c(t.next(f))}catch(d){a(d)}},i=f=>{try{c(t.throw(f))}catch(d){a(d)}},c=f=>f.done?s(f.value):Promise.resolve(f.value).then(o,i);c((t=t.apply(r,e)).next())});var y=class r 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 E(this,null,function*(){let a=t.status,o=Object.fromEntries([...t.headers.entries()]),i,c,f=t.headers.get("content-type");return t.bodyUsed||(f&&f.includes("application/json")?c=yield t.json():i=yield t.text()),new r(a,i,c,o,s)})}},v=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var xe=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},we=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Te=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Me=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},ve=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Ce=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 Ue=r=>Number(r),zt=r=>r==="true"||r==="t",Xt=r=>BigInt(r),mt=r=>JSON.parse(r),Zt=r=>r,es={int2:Ue,int4:Ue,int8:Xt,bool:zt,float4:Ue,float8:Ue,json:mt,jsonb:mt};function ts(r,e){let t=0,s=null,a="",o=!1,i=0,c;function u(m,E,Q){let R=m.slice(E,Q);return R=R==="NULL"?null:R,e?e(R):R}function d(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(d(m));else if(s==="}"){o=!1,i<t&&E.push(u(m,i,t)),i=t+1;break}else s===","&&c!=="}"&&c!=='"'&&(E.push(u(m,i,t)),i=t+1);c=s}return i<t&&E.push(E.push(u(m,i,t+1))),E}return d(r)[0]}var ke=class{constructor(e,t){this.parser=b(b({},es),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,c=pt(m,["type","dims"]),u=(E=this.parser[o])!=null?E:Zt,d=gt(u,a,e);return i&&i>0?gt((R,Ne)=>ts(R,d),a,e)(t):d(t,c)}};function gt(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new ve(t!=null?t:"unknown");return null}return r(o,e)}}function z(r){return"key"in r}function Oe(r){return!z(r)}function Ye(r){return Oe(r)&&r.headers.control==="up-to-date"}function Et(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function Qe(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)}function ss(){return Math.floor(Math.random()*1048575).toString(16).padStart(5,"0")}function rs(r){let e=r.hostname.toLowerCase();return e==="localhost"||e.endsWith(".localhost")}function St(r,e="localhost"){if(e==="never"||e===!1)return r;let t=new URL(r);if(!(e==="always"||e===!0||e==="localhost"&&rs(t)))return r;let a=ss();return t.hostname=`${a}.${t.hostname}`,t.toString()}var Rt="electric-cursor",ue="electric-handle",Le="electric-offset",bt="electric-schema",yt="electric-up-to-date",Pt="columns",He="cursor",Ke="expired_handle",X="handle",v="live",Z="offset",At="table",_t="where",xt="replica",wt="params",Tt="experimental_live_sse",We="force-disconnect-and-refresh",$e="pause-stream",Ge="log",fe="subset__where",de="subset__limit",pe="subset__offset",me="subset__order_by",ge="subset__params",Je=[v,X,Z,He,Ke,Ge,fe,de,pe,me,ge];var ns=[429],De={initialDelay:100,maxDelay:1e4,multiplier:1.3};function Mt(r,e=De){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i}=e;return(...c)=>g(this,null,function*(){var Q;let u=c[0],d=c[1],m=t,E=0;for(;;)try{let R=yield r(...c);if(R.ok)return R;throw yield y.fromResponse(R,u.toString())}catch(R){if(i==null||i(),(Q=d==null?void 0:d.signal)!=null&&Q.aborted)throw new D;if(R instanceof y&&!ns.includes(R.status)&&R.status>=400&&R.status<500)throw R;yield new Promise(Ne=>setTimeout(Ne,m)),m=Math.min(m*a,s),o&&(E++,console.log(`Retry attempt #${E} after ${m}ms`))}})}var as=[201,204,205];function vt(r){return(...e)=>g(this,null,function*(){let t=e[0],s=yield r(...e);try{if(s.status<200||as.includes(s.status))return s;let a=yield s.text();return new Response(a,s)}catch(a){throw new y(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),a instanceof Error?a.message:typeof a=="string"?a:"failed to read body")}})}var is={maxChunksToPrefetch:2};function Ct(r,e=is){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 r(...o),d=Xe(i,u);return d&&(s=new ze({fetchClient:r,maxPrefetchedRequests:t,url:d,requestInit:o[1]})),u})}var os=["electric-offset","electric-handle"],hs=["electric-cursor"],cs=["electric-schema"];function Ut(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))),c=e[0].toString(),u=new URL(c);if([fe,ge,de,pe,me].some(m=>u.searchParams.has(m)))return t;if(o(os),u.searchParams.get(v)==="true"&&o(hs),(!u.searchParams.has(v)||u.searchParams.get(v)==="false")&&o(cs),a.length>0)throw new Ce(c,a)}return t})}var Ee,Se,C,K,U,ee,Ie,ze=class{constructor(e){p(this,ee);p(this,Ee);p(this,Se);p(this,C,new Map);p(this,K);p(this,U);var t;h(this,Ee,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),h(this,Se,e.maxPrefetchedRequests),h(this,K,e.url.toString()),h(this,U,n(this,K)),f(this,ee,Ie).call(this,e.url,e.requestInit)}abort(){n(this,C).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=n(this,C).get(t))==null?void 0:a[0];if(!(!s||t!==n(this,K)))return n(this,C).delete(t),s.then(o=>{let i=Xe(t,o);h(this,K,i),n(this,U)&&!n(this,C).has(n(this,U))&&f(this,ee,Ie).call(this,n(this,U),e[1])}).catch(()=>{}),s}};Ee=new WeakMap,Se=new WeakMap,C=new WeakMap,K=new WeakMap,U=new WeakMap,ee=new WeakSet,Ie=function(...e){var a,o;let t=e[0].toString();if(n(this,C).size>=n(this,Se))return;let s=new AbortController;try{let{signal:i,cleanup:c}=ls(s,(a=e[1])==null?void 0:a.signal),u=n(this,Ee).call(this,t,le(b({},(o=e[1])!=null?o:{}),{signal:i}));n(this,C).set(t,[u,s]),u.then(d=>{if(!d.ok||s.signal.aborted)return;let m=Xe(t,d);if(!m||m===t){h(this,U,void 0);return}return h(this,U,m),f(this,ee,Ie).call(this,m,e[1])}).catch(()=>{}).finally(c)}catch(i){}};function Xe(r,e){let t=e.headers.get(ue),s=e.headers.get(Le),a=e.headers.has(yt);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(v))return o.searchParams.set(X,t),o.searchParams.set(Z,s),o.searchParams.sort(),o.toString()}function ls(r,e){let t=us;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 us(){}import{fetchEventSource as fs}from"@microsoft/fetch-event-source";var Ze=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 Ze;var Be=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)&&Qe(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([He,X,v,Z]);function Ot(r){return g(this,null,function*(){return typeof r=="function"?r():r})}function ps(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 Ot(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function ms(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 Ot(a)]})));return Object.fromEntries(t)})}function kt(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Je.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ye,te,se,W,B,M,A,k,$,F,w,G,O,_,q,L,re,T,J,H,ne,ae,ie,Pe,N,I,oe,l,Re,be,st,Lt,rt,Fe,Ht,It,Dt,nt,at,Bt,Ft,it,qt,Nt,ot,Vt,tt=class{constructor(e){p(this,l);p(this,ye,null);p(this,te);p(this,se);p(this,W);p(this,B,new Map);p(this,M,!1);p(this,A,"active");p(this,k);p(this,$);p(this,F);p(this,w,!1);p(this,G,!0);p(this,O,!1);p(this,_);p(this,q);p(this,L);p(this,re);p(this,T);p(this,J,!1);p(this,H);p(this,ne);p(this,ae);p(this,ie,Promise.resolve([]));p(this,Pe,new Be);p(this,N,0);p(this,I);p(this,oe);var o,i,c,u;this.options=b({subscribe:!0},e),gs(this.options),this.options.url=St(this.options.url,this.options.shardSubdomain),h(this,k,(o=this.options.offset)!=null?o:"-1"),h(this,$,""),h(this,_,this.options.handle),h(this,W,new ke(e.parser,e.transformer)),h(this,re,this.options.onError),h(this,q,(i=this.options.log)!=null?i:"full");let t=(c=e.fetchClient)!=null?c:(...d)=>fetch(...d),s=le(b({},(u=e.backoffOptions)!=null?u:De),{onFailedAttempt:()=>{var d,m;h(this,O,!1),(m=(d=e.backoffOptions)==null?void 0:d.onFailedAttempt)==null||m.call(d)}}),a=Mt(t,s);h(this,se,Ut(Ct(a))),h(this,te,vt(n(this,se))),f(this,l,Nt).call(this)}get shapeHandle(){return n(this,_)}get error(){return n(this,ye)}get isUpToDate(){return n(this,w)}get lastOffset(){return n(this,k)}get mode(){return n(this,q)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,B).set(s,[e,t]),n(this,M)||f(this,l,Re).call(this),()=>{n(this,B).delete(s)}}unsubscribeAll(){n(this,B).clear()}lastSyncedAt(){return n(this,F)}lastSynced(){return n(this,F)===void 0?1/0:Date.now()-n(this,F)}isConnected(){return n(this,O)}isLoading(){return!n(this,w)}hasStarted(){return n(this,M)}isPaused(){return n(this,A)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;h(this,J,!0),n(this,w)&&!((e=n(this,T))!=null&&e.signal.aborted)&&((t=n(this,T))==null||t.abort(We)),yield f(this,l,Bt).call(this),h(this,J,!1)})}requestSnapshot(e){return g(this,null,function*(){if(n(this,q)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,q)} mode, as the consumer is guaranteed to observe all data`);n(this,M)||(yield f(this,l,Re).call(this)),yield f(this,l,Ft).call(this),je(this,N)._++;try{n(this,N)===1&&f(this,l,nt).call(this);let{fetchUrl:t,requestHeaders:s}=yield f(this,l,st).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield f(this,l,Vt).call(this,t,s),i=o.concat([{headers:b({control:"snapshot-end"},a)}]);return n(this,Pe).addSnapshot(a,new Set(o.map(c=>c.key))),f(this,l,Fe).call(this,i,!1),{metadata:a,data:o}}finally{je(this,N)._--,n(this,N)===0&&f(this,l,at).call(this)}})}};ye=new WeakMap,te=new WeakMap,se=new WeakMap,W=new WeakMap,B=new WeakMap,M=new WeakMap,A=new WeakMap,k=new WeakMap,$=new WeakMap,F=new WeakMap,w=new WeakMap,G=new WeakMap,O=new WeakMap,_=new WeakMap,q=new WeakMap,L=new WeakMap,re=new WeakMap,T=new WeakMap,J=new WeakMap,H=new WeakMap,ne=new WeakMap,ae=new WeakMap,ie=new WeakMap,Pe=new WeakMap,N=new WeakMap,I=new WeakMap,oe=new WeakMap,l=new WeakSet,Re=function(){return g(this,null,function*(){var e;h(this,M,!0);try{yield f(this,l,be).call(this)}catch(t){if(h(this,ye,t),n(this,re)){let s=yield n(this,re).call(this,t);typeof s=="object"&&(f(this,l,ot).call(this),"params"in s&&(this.options.params=s.params),"headers"in s&&(this.options.headers=s.headers),h(this,M,!1),f(this,l,Re).call(this));return}throw t}finally{h(this,O,!1),(e=n(this,ae))==null||e.call(this)}})},be=function(){return g(this,null,function*(){var u,d;if(n(this,A)==="pause-requested"){h(this,A,"paused");return}if(!this.options.subscribe&&((u=this.options.signal)!=null&&u.aborted||n(this,w)))return;let e=n(this,A)==="paused";h(this,A,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield f(this,l,st).call(this,t,e),i=yield f(this,l,Lt).call(this,s),c=n(this,T);try{yield f(this,l,Ht).call(this,{fetchUrl:a,requestAbortController:c,headers:o,resumingFromPause:e})}catch(m){if((m instanceof y||m instanceof D)&&c.signal.aborted&&c.signal.reason===We)return f(this,l,be).call(this);if(m instanceof D){c.signal.aborted&&c.signal.reason===$e&&h(this,A,"paused");return}if(!(m instanceof y))throw m;if(m.status==409){if(n(this,_)){let Q=kt(a);et.markExpired(Q,n(this,_))}let E=m.headers[ue]||`${n(this,_)}-next`;return f(this,l,ot).call(this,E),yield f(this,l,it).call(this,m.json),f(this,l,be).call(this)}else throw f(this,l,qt).call(this,m),m}finally{i&&s&&s.removeEventListener("abort",i),h(this,T,void 0)}return(d=n(this,ne))==null||d.call(this),f(this,l,be).call(this)})},st=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([ms(this.options.headers),this.options.params?ps(Es(this.options.params)):void 0]);o&&jt(o);let i=new URL(e);if(o){o.table&&x(i,At,o.table),o.where&&x(i,_t,o.where),o.columns&&x(i,Pt,o.columns),o.replica&&x(i,xt,o.replica),o.params&&x(i,wt,o.params);let d=b({},o);delete d.table,delete d.where,delete d.columns,delete d.replica,delete d.params;for(let[m,E]of Object.entries(d))x(i,m,E)}s&&(s.where&&x(i,fe,s.where),s.params&&x(i,ge,s.params),s.limit&&x(i,de,s.limit),s.offset&&x(i,pe,s.offset),s.orderBy&&x(i,me,s.orderBy)),i.searchParams.set(Z,n(this,k)),i.searchParams.set(Ge,n(this,q)),n(this,w)&&(!n(this,J)&&!t&&i.searchParams.set(v,"true"),i.searchParams.set(He,n(this,$))),n(this,_)&&i.searchParams.set(X,n(this,_));let c=kt(i),u=et.getExpiredHandle(c);return u&&i.searchParams.set(Ke,u),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Lt=function(e){return g(this,null,function*(){var t;if(h(this,T,new AbortController),e){let s=()=>{var a;(a=n(this,T))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,T))==null||t.abort(e.reason)),s}})},rt=function(e){return g(this,null,function*(){var u;let{headers:t,status:s}=e,a=t.get(ue);a&&h(this,_,a);let o=t.get(Le);o&&h(this,k,o);let i=t.get(Rt);i&&h(this,$,i);let c=()=>{let d=t.get(bt);return d?JSON.parse(d):{}};h(this,L,(u=n(this,L))!=null?u:c()),s===204&&h(this,F,Date.now())})},Fe=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){h(this,G,!0);let a=e[e.length-1];if(Ye(a)){if(t){let i=Et(a);i&&h(this,k,i)}h(this,F,Date.now()),h(this,w,!0),h(this,G,!1),(s=n(this,oe))==null||s.call(this)}let o=e.filter(i=>z(i)?!n(this,Pe).shouldRejectMessage(i):!0);yield f(this,l,it).call(this,o)}})},Ht=function(e){return g(this,null,function*(){return n(this,w)&&this.options.experimentalLiveSse&&!n(this,J)&&!e.resumingFromPause?(e.fetchUrl.searchParams.set(Tt,"true"),f(this,l,Dt).call(this,e)):f(this,l,It).call(this,e)})},It=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield n(this,te).call(this,t.toString(),{signal:s.signal,headers:a});h(this,O,!0),yield f(this,l,rt).call(this,o);let i=n(this,L),u=(yield o.text())||"[]",d=n(this,W).parse(u,i);yield f(this,l,Fe).call(this,d)})},Dt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,se);try{let i=[];yield fs(t.toString(),{headers:a,fetch:o,onopen:c=>g(this,null,function*(){h(this,O,!0),yield f(this,l,rt).call(this,c)}),onmessage:c=>{if(c.data){let u=n(this,L),d=n(this,W).parse(c.data,u);i.push(d),Ye(d)&&(f(this,l,Fe).call(this,i,!0),i=[])}},onerror:c=>{throw c},signal:s.signal})}catch(i){throw s.signal.aborted?new D:i}})},nt=function(){var e;n(this,M)&&n(this,A)==="active"&&(h(this,A,"pause-requested"),(e=n(this,T))==null||e.abort($e))},at=function(){n(this,M)&&n(this,A)==="paused"&&f(this,l,Re).call(this)},Bt=function(){return g(this,null,function*(){return n(this,H)?n(this,H):(h(this,H,new Promise((e,t)=>{h(this,ne,e),h(this,ae,t)})),n(this,H).finally(()=>{h(this,H,void 0),h(this,ne,void 0),h(this,ae,void 0)}),n(this,H))})},Ft=function(){return g(this,null,function*(){if(n(this,G))return n(this,I)?n(this,I):(h(this,I,new Promise(e=>{h(this,oe,e)})),n(this,I).finally(()=>{h(this,I,void 0),h(this,oe,void 0)}),n(this,I))})},it=function(e){return g(this,null,function*(){return h(this,ie,n(this,ie).then(()=>Promise.all(Array.from(n(this,B).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,ie)})},qt=function(e){n(this,B).forEach(([t,s])=>{s==null||s(e)})},Nt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?f(this,l,nt).call(this):f(this,l,at).call(this)};document.addEventListener("visibilitychange",e)}},ot=function(e){h(this,k,"-1"),h(this,$,""),h(this,_,e),h(this,w,!1),h(this,G,!0),h(this,O,!1),h(this,L,void 0),h(this,N,0)},Vt=function(e,t){return g(this,null,function*(){let s=yield n(this,te).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,W).parse(JSON.stringify(o),n(this,L));return{metadata:a,data:i}})},tt.Replica={FULL:"full",DEFAULT:"default"};function jt(r){if(!r)return;let e=Object.keys(r).filter(t=>ds.has(t));if(e.length>0)throw new Me(e)}function gs(r){if(!r.url)throw new xe;if(r.signal&&!(r.signal instanceof AbortSignal))throw new we;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Te;jt(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 Es(r){return Array.isArray(r.params)?le(b({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,V,j,Ae,he,ce,Y,S,Qt,Kt,ht,qe,Wt,ct,Yt=class{constructor(e){p(this,S);p(this,P,new Map);p(this,V,new Map);p(this,j,new Set);p(this,Ae,new Set);p(this,he,!1);p(this,ce,"syncing");p(this,Y,!1);this.stream=e,this.stream.subscribe(f(this,S,Qt).bind(this),f(this,S,Wt).bind(this))}get isUpToDate(){return n(this,ce)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(e=>Array.from(e.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((e,t)=>{if(this.stream.isUpToDate)e(this.currentValue);else{let s=this.subscribe(({value:a})=>{s(),n(this,Y)&&t(n(this,Y)),e(a)})}})}get currentValue(){return n(this,P)}get error(){return n(this,Y)}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,Ae).add(t),yield f(this,S,ht).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,V).set(t,e),()=>{n(this,V).delete(t)}}unsubscribeAll(){n(this,V).clear()}get numSubscribers(){return n(this,V).size}};P=new WeakMap,V=new WeakMap,j=new WeakMap,Ae=new WeakMap,he=new WeakMap,ce=new WeakMap,Y=new WeakMap,S=new WeakSet,Qt=function(e){let t=!1;e.forEach(s=>{if(z(s))if(t=f(this,S,qe).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,b(b({},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,j).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,j).has(s.key)&&n(this,P).set(s.key,b(b({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,j).has(s.key)&&(n(this,P).delete(s.key),n(this,j).delete(s.key));break}if(Oe(s))switch(s.headers.control){case"up-to-date":t=f(this,S,qe).call(this,"up-to-date"),n(this,he)&&(h(this,he,!1),f(this,S,Kt).call(this));break;case"must-refetch":n(this,P).clear(),n(this,j).clear(),h(this,Y,!1),t=f(this,S,qe).call(this,"syncing"),h(this,he,!0);break}}),t&&f(this,S,ct).call(this)},Kt=function(){return g(this,null,function*(){yield f(this,S,ht).call(this),yield Promise.all(Array.from(n(this,Ae)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},ht=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()}))})},qe=function(e){let t=n(this,ce)!==e;return h(this,ce,e),t&&e==="up-to-date"},Wt=function(e){e instanceof y&&(h(this,Y,e),f(this,S,ct).call(this))},ct=function(){n(this,V).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{De as BackoffDefaults,Je as ELECTRIC_PROTOCOL_QUERY_PARAMS,y as FetchError,Yt as Shape,tt as ShapeStream,z as isChangeMessage,Oe as isControlMessage,Qe as isVisibleInSnapshot,Ot as resolveValue};
|
|
5
|
+
For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var Ue=r=>Number(r),zt=r=>r==="true"||r==="t",Xt=r=>BigInt(r),mt=r=>JSON.parse(r),Zt=r=>r,es={int2:Ue,int4:Ue,int8:Xt,bool:zt,float4:Ue,float8:Ue,json:mt,jsonb:mt};function ts(r,e){let t=0,s=null,a="",o=!1,i=0,c;function f(p,g,Q){let S=p.slice(g,Q);return S=S==="NULL"?null:S,e?e(S):S}function d(p){let g=[];for(;t<p.length;t++){if(s=p[t],o)s==="\\"?a+=p[++t]:s==='"'?(g.push(e?e(a):a),a="",o=p[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,g.push(d(p));else if(s==="}"){o=!1,i<t&&g.push(f(p,i,t)),i=t+1;break}else s===","&&c!=="}"&&c!=='"'&&(g.push(f(p,i,t)),i=t+1);c=s}return i<t&&g.push(g.push(f(p,i,t+1))),g}return d(r)[0]}var ke=class{constructor(e,t){this.parser=b(b({},es),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 g;let a=s[e];if(!a)return t;let p=a,{type:o,dims:i}=p,c=pt(p,["type","dims"]),f=(g=this.parser[o])!=null?g:Zt,d=Et(f,a,e);return i&&i>0?Et((S,Ne)=>ts(S,d),a,e)(t):d(t,c)}};function Et(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new ve(t!=null?t:"unknown");return null}return r(o,e)}}function z(r){return"key"in r}function Oe(r){return!z(r)}function Ye(r){return Oe(r)&&r.headers.control==="up-to-date"}function gt(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function Qe(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 Rt="electric-cursor",fe="electric-handle",He="electric-offset",St="electric-schema",bt="electric-up-to-date",yt="columns",Le="cursor",Ke="expired_handle",X="handle",C="live",Z="offset",At="table",Pt="where",_t="replica",xt="params",wt="experimental_live_sse",Tt="live_sse",We="force-disconnect-and-refresh",$e="pause-stream",Ge="log",ue="subset__where",de="subset__limit",pe="subset__offset",me="subset__order_by",Ee="subset__params",Je=[C,X,Z,Le,Ke,Ge,ue,de,pe,me,Ee];var ss=[429],De={initialDelay:100,maxDelay:1e4,multiplier:1.3};function Mt(r,e=De){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i}=e;return(...c)=>E(this,null,function*(){var Q;let f=c[0],d=c[1],p=t,g=0;for(;;)try{let S=yield r(...c);if(S.ok)return S;throw yield y.fromResponse(S,f.toString())}catch(S){if(i==null||i(),(Q=d==null?void 0:d.signal)!=null&&Q.aborted)throw new v;if(S instanceof y&&!ss.includes(S.status)&&S.status>=400&&S.status<500)throw S;yield new Promise(Ne=>setTimeout(Ne,p)),p=Math.min(p*a,s),o&&(g++,console.log(`Retry attempt #${g} after ${p}ms`))}})}var rs=[201,204,205];function vt(r){return(...e)=>E(this,null,function*(){var a,o;let t=e[0],s=yield r(...e);try{if(s.status<200||rs.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 v: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 ns={maxChunksToPrefetch:2};function Ct(r,e=ns){let{maxChunksToPrefetch:t}=e,s;return(...o)=>E(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 f=yield r(...o),d=Xe(i,f);return d&&(s=new ze({fetchClient:r,maxPrefetchedRequests:t,url:d,requestInit:o[1]})),f})}var as=["electric-offset","electric-handle"],is=["electric-cursor"],os=["electric-schema"];function Ut(r){return(...e)=>E(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,a=[],o=p=>a.push(...p.filter(g=>!s.has(g))),c=e[0].toString(),f=new URL(c);if([ue,Ee,de,pe,me].some(p=>f.searchParams.has(p)))return t;if(o(as),f.searchParams.get(C)==="true"&&o(is),(!f.searchParams.has(C)||f.searchParams.get(C)==="false")&&o(os),a.length>0)throw new Ce(c,a)}return t})}var ge,Re,U,K,k,ee,Ie,ze=class{constructor(e){m(this,ee);m(this,ge);m(this,Re);m(this,U,new Map);m(this,K);m(this,k);var t;h(this,ge,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),h(this,Re,e.maxPrefetchedRequests),h(this,K,e.url.toString()),h(this,k,n(this,K)),u(this,ee,Ie).call(this,e.url,e.requestInit)}abort(){n(this,U).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=n(this,U).get(t))==null?void 0:a[0];if(!(!s||t!==n(this,K)))return n(this,U).delete(t),s.then(o=>{let i=Xe(t,o);h(this,K,i),n(this,k)&&!n(this,U).has(n(this,k))&&u(this,ee,Ie).call(this,n(this,k),e[1])}).catch(()=>{}),s}};ge=new WeakMap,Re=new WeakMap,U=new WeakMap,K=new WeakMap,k=new WeakMap,ee=new WeakSet,Ie=function(...e){var a,o;let t=e[0].toString();if(n(this,U).size>=n(this,Re))return;let s=new AbortController;try{let{signal:i,cleanup:c}=hs(s,(a=e[1])==null?void 0:a.signal),f=n(this,ge).call(this,t,le(b({},(o=e[1])!=null?o:{}),{signal:i}));n(this,U).set(t,[f,s]),f.then(d=>{if(!d.ok||s.signal.aborted)return;let p=Xe(t,d);if(!p||p===t){h(this,k,void 0);return}return h(this,k,p),u(this,ee,Ie).call(this,p,e[1])}).catch(()=>{}).finally(c)}catch(i){}};function Xe(r,e){let t=e.headers.get(fe),s=e.headers.get(He),a=e.headers.has(bt);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(C))return o.searchParams.set(X,t),o.searchParams.set(Z,s),o.searchParams.sort(),o.toString()}function hs(r,e){let t=cs;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 cs(){}import{fetchEventSource as ls}from"@microsoft/fetch-event-source";var Ze=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 Ze;var Be=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,c,f;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=(f=(c=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:c.add(e.snapshot_mark))!=null?f: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)&&Qe(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var fs=new Set([Le,X,C,Z]);function Ot(r){return E(this,null,function*(){return typeof r=="function"?r():r})}function us(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 Ot(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function ds(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 Ot(a)]})));return Object.fromEntries(t)})}function kt(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Je.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ye,te,se,W,B,M,P,O,$,F,w,G,H,_,q,L,re,T,J,I,ne,ae,ie,Ae,N,D,oe,l,Se,be,st,Ht,rt,Fe,Lt,It,Dt,nt,at,Bt,Ft,it,qt,Nt,ot,Vt,tt=class{constructor(e){m(this,l);m(this,ye,null);m(this,te);m(this,se);m(this,W);m(this,B,new Map);m(this,M,!1);m(this,P,"active");m(this,O);m(this,$);m(this,F);m(this,w,!1);m(this,G,!0);m(this,H,!1);m(this,_);m(this,q);m(this,L);m(this,re);m(this,T);m(this,J,!1);m(this,I);m(this,ne);m(this,ae);m(this,ie,Promise.resolve([]));m(this,Ae,new Be);m(this,N,0);m(this,D);m(this,oe);var o,i,c,f;this.options=b({subscribe:!0},e),ps(this.options),h(this,O,(o=this.options.offset)!=null?o:"-1"),h(this,$,""),h(this,_,this.options.handle),h(this,W,new ke(e.parser,e.transformer)),h(this,re,this.options.onError),h(this,q,(i=this.options.log)!=null?i:"full");let t=(c=e.fetchClient)!=null?c:(...d)=>fetch(...d),s=le(b({},(f=e.backoffOptions)!=null?f:De),{onFailedAttempt:()=>{var d,p;h(this,H,!1),(p=(d=e.backoffOptions)==null?void 0:d.onFailedAttempt)==null||p.call(d)}}),a=Mt(t,s);h(this,se,Ut(Ct(a))),h(this,te,vt(n(this,se))),u(this,l,Nt).call(this)}get shapeHandle(){return n(this,_)}get error(){return n(this,ye)}get isUpToDate(){return n(this,w)}get lastOffset(){return n(this,O)}get mode(){return n(this,q)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,B).set(s,[e,t]),n(this,M)||u(this,l,Se).call(this),()=>{n(this,B).delete(s)}}unsubscribeAll(){n(this,B).clear()}lastSyncedAt(){return n(this,F)}lastSynced(){return n(this,F)===void 0?1/0:Date.now()-n(this,F)}isConnected(){return n(this,H)}isLoading(){return!n(this,w)}hasStarted(){return n(this,M)}isPaused(){return n(this,P)==="paused"}forceDisconnectAndRefresh(){return E(this,null,function*(){var e,t;h(this,J,!0),n(this,w)&&!((e=n(this,T))!=null&&e.signal.aborted)&&((t=n(this,T))==null||t.abort(We)),yield u(this,l,Bt).call(this),h(this,J,!1)})}requestSnapshot(e){return E(this,null,function*(){if(n(this,q)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,q)} mode, as the consumer is guaranteed to observe all data`);n(this,M)||(yield u(this,l,Se).call(this)),yield u(this,l,Ft).call(this),je(this,N)._++;try{n(this,N)===1&&u(this,l,nt).call(this);let{fetchUrl:t,requestHeaders:s}=yield u(this,l,st).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield u(this,l,Vt).call(this,t,s),i=o.concat([{headers:b({control:"snapshot-end"},a)}]);return n(this,Ae).addSnapshot(a,new Set(o.map(c=>c.key))),u(this,l,Fe).call(this,i,!1),{metadata:a,data:o}}finally{je(this,N)._--,n(this,N)===0&&u(this,l,at).call(this)}})}};ye=new WeakMap,te=new WeakMap,se=new WeakMap,W=new WeakMap,B=new WeakMap,M=new WeakMap,P=new WeakMap,O=new WeakMap,$=new WeakMap,F=new WeakMap,w=new WeakMap,G=new WeakMap,H=new WeakMap,_=new WeakMap,q=new WeakMap,L=new WeakMap,re=new WeakMap,T=new WeakMap,J=new WeakMap,I=new WeakMap,ne=new WeakMap,ae=new WeakMap,ie=new WeakMap,Ae=new WeakMap,N=new WeakMap,D=new WeakMap,oe=new WeakMap,l=new WeakSet,Se=function(){return E(this,null,function*(){var e;h(this,M,!0);try{yield u(this,l,be).call(this)}catch(t){if(h(this,ye,t),n(this,re)){let s=yield n(this,re).call(this,t);typeof s=="object"&&(u(this,l,ot).call(this),"params"in s&&(this.options.params=s.params),"headers"in s&&(this.options.headers=s.headers),h(this,M,!1),u(this,l,Se).call(this));return}throw t}finally{h(this,H,!1),(e=n(this,ae))==null||e.call(this)}})},be=function(){return E(this,null,function*(){var f,d;if(n(this,P)==="pause-requested"){h(this,P,"paused");return}if(!this.options.subscribe&&((f=this.options.signal)!=null&&f.aborted||n(this,w)))return;let e=n(this,P)==="paused";h(this,P,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield u(this,l,st).call(this,t,e),i=yield u(this,l,Ht).call(this,s),c=n(this,T);try{yield u(this,l,Lt).call(this,{fetchUrl:a,requestAbortController:c,headers:o,resumingFromPause:e})}catch(p){if((p instanceof y||p instanceof v)&&c.signal.aborted&&c.signal.reason===We)return u(this,l,be).call(this);if(p instanceof v){c.signal.aborted&&c.signal.reason===$e&&h(this,P,"paused");return}if(!(p instanceof y))throw p;if(p.status==409){if(n(this,_)){let Q=kt(a);et.markExpired(Q,n(this,_))}let g=p.headers[fe]||`${n(this,_)}-next`;return u(this,l,ot).call(this,g),yield u(this,l,it).call(this,Array.isArray(p.json)?p.json:[p.json]),u(this,l,be).call(this)}else throw u(this,l,qt).call(this,p),p}finally{i&&s&&s.removeEventListener("abort",i),h(this,T,void 0)}return(d=n(this,ne))==null||d.call(this),u(this,l,be).call(this)})},st=function(e,t,s){return E(this,null,function*(){let[a,o]=yield Promise.all([ds(this.options.headers),this.options.params?us(ms(this.options.params)):void 0]);o&&jt(o);let i=new URL(e);if(o){o.table&&x(i,At,o.table),o.where&&x(i,Pt,o.where),o.columns&&x(i,yt,o.columns),o.replica&&x(i,_t,o.replica),o.params&&x(i,xt,o.params);let d=b({},o);delete d.table,delete d.where,delete d.columns,delete d.replica,delete d.params;for(let[p,g]of Object.entries(d))x(i,p,g)}s&&(s.where&&x(i,ue,s.where),s.params&&x(i,Ee,s.params),s.limit&&x(i,de,s.limit),s.offset&&x(i,pe,s.offset),s.orderBy&&x(i,me,s.orderBy)),i.searchParams.set(Z,n(this,O)),i.searchParams.set(Ge,n(this,q)),n(this,w)&&(!n(this,J)&&!t&&i.searchParams.set(C,"true"),i.searchParams.set(Le,n(this,$))),n(this,_)&&i.searchParams.set(X,n(this,_));let c=kt(i),f=et.getExpiredHandle(c);return f&&i.searchParams.set(Ke,f),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Ht=function(e){return E(this,null,function*(){var t;if(h(this,T,new AbortController),e){let s=()=>{var a;(a=n(this,T))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,T))==null||t.abort(e.reason)),s}})},rt=function(e){return E(this,null,function*(){var f;let{headers:t,status:s}=e,a=t.get(fe);a&&h(this,_,a);let o=t.get(He);o&&h(this,O,o);let i=t.get(Rt);i&&h(this,$,i);let c=()=>{let d=t.get(St);return d?JSON.parse(d):{}};h(this,L,(f=n(this,L))!=null?f:c()),s===204&&h(this,F,Date.now())})},Fe=function(e,t=!1){return E(this,null,function*(){var s;if(e.length>0){h(this,G,!0);let a=e[e.length-1];if(Ye(a)){if(t){let i=gt(a);i&&h(this,O,i)}h(this,F,Date.now()),h(this,w,!0),h(this,G,!1),(s=n(this,oe))==null||s.call(this)}let o=e.filter(i=>z(i)?!n(this,Ae).shouldRejectMessage(i):!0);yield u(this,l,it).call(this,o)}})},Lt=function(e){return E(this,null,function*(){var s;let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,w)&&t&&!n(this,J)&&!e.resumingFromPause?(e.fetchUrl.searchParams.set(wt,"true"),e.fetchUrl.searchParams.set(Tt,"true"),u(this,l,Dt).call(this,e)):u(this,l,It).call(this,e)})},It=function(e){return E(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield n(this,te).call(this,t.toString(),{signal:s.signal,headers:a});h(this,H,!0),yield u(this,l,rt).call(this,o);let i=n(this,L),f=(yield o.text())||"[]",d=n(this,W).parse(f,i);yield u(this,l,Fe).call(this,d)})},Dt=function(e){return E(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,se);try{let i=[];yield ls(t.toString(),{headers:a,fetch:o,onopen:c=>E(this,null,function*(){h(this,H,!0),yield u(this,l,rt).call(this,c)}),onmessage:c=>{if(c.data){let f=n(this,L),d=n(this,W).parse(c.data,f);i.push(d),Ye(d)&&(u(this,l,Fe).call(this,i,!0),i=[])}},onerror:c=>{throw c},signal:s.signal})}catch(i){throw s.signal.aborted?new v:i}})},nt=function(){var e;n(this,M)&&n(this,P)==="active"&&(h(this,P,"pause-requested"),(e=n(this,T))==null||e.abort($e))},at=function(){n(this,M)&&n(this,P)==="paused"&&u(this,l,Se).call(this)},Bt=function(){return E(this,null,function*(){return n(this,I)?n(this,I):(h(this,I,new Promise((e,t)=>{h(this,ne,e),h(this,ae,t)})),n(this,I).finally(()=>{h(this,I,void 0),h(this,ne,void 0),h(this,ae,void 0)}),n(this,I))})},Ft=function(){return E(this,null,function*(){if(n(this,G))return n(this,D)?n(this,D):(h(this,D,new Promise(e=>{h(this,oe,e)})),n(this,D).finally(()=>{h(this,D,void 0),h(this,oe,void 0)}),n(this,D))})},it=function(e){return E(this,null,function*(){return h(this,ie,n(this,ie).then(()=>Promise.all(Array.from(n(this,B).values()).map(a=>E(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,ie)})},qt=function(e){n(this,B).forEach(([t,s])=>{s==null||s(e)})},Nt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?u(this,l,nt).call(this):u(this,l,at).call(this)};document.addEventListener("visibilitychange",e)}},ot=function(e){h(this,O,"-1"),h(this,$,""),h(this,_,e),h(this,w,!1),h(this,G,!0),h(this,H,!1),h(this,L,void 0),h(this,N,0)},Vt=function(e,t){return E(this,null,function*(){let s=yield n(this,te).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,W).parse(JSON.stringify(o),n(this,L));return{metadata:a,data:i}})},tt.Replica={FULL:"full",DEFAULT:"default"};function jt(r){if(!r)return;let e=Object.keys(r).filter(t=>fs.has(t));if(e.length>0)throw new Me(e)}function ps(r){if(!r.url)throw new xe;if(r.signal&&!(r.signal instanceof AbortSignal))throw new we;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Te;jt(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)?le(b({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var A,V,j,Pe,he,ce,Y,R,Qt,Kt,ht,qe,Wt,ct,Yt=class{constructor(e){m(this,R);m(this,A,new Map);m(this,V,new Map);m(this,j,new Set);m(this,Pe,new Set);m(this,he,!1);m(this,ce,"syncing");m(this,Y,!1);this.stream=e,this.stream.subscribe(u(this,R,Qt).bind(this),u(this,R,Wt).bind(this))}get isUpToDate(){return n(this,ce)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(e=>Array.from(e.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((e,t)=>{if(this.stream.isUpToDate)e(this.currentValue);else{let s=this.subscribe(({value:a})=>{s(),n(this,Y)&&t(n(this,Y)),e(a)})}})}get currentValue(){return n(this,A)}get error(){return n(this,Y)}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,Pe).add(t),yield u(this,R,ht).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,V).set(t,e),()=>{n(this,V).delete(t)}}unsubscribeAll(){n(this,V).clear()}get numSubscribers(){return n(this,V).size}};A=new WeakMap,V=new WeakMap,j=new WeakMap,Pe=new WeakMap,he=new WeakMap,ce=new WeakMap,Y=new WeakMap,R=new WeakSet,Qt=function(e){let t=!1;e.forEach(s=>{if(z(s))if(t=u(this,R,qe).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,b(b({},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,j).add(s.key),n(this,A).set(s.key,s.value);break;case"update":n(this,j).has(s.key)&&n(this,A).set(s.key,b(b({},n(this,A).get(s.key)),s.value));break;case"delete":n(this,j).has(s.key)&&(n(this,A).delete(s.key),n(this,j).delete(s.key));break}if(Oe(s))switch(s.headers.control){case"up-to-date":t=u(this,R,qe).call(this,"up-to-date"),n(this,he)&&(h(this,he,!1),u(this,R,Kt).call(this));break;case"must-refetch":n(this,A).clear(),n(this,j).clear(),h(this,Y,!1),t=u(this,R,qe).call(this,"syncing"),h(this,he,!0);break}}),t&&u(this,R,ct).call(this)},Kt=function(){return E(this,null,function*(){yield u(this,R,ht).call(this),yield Promise.all(Array.from(n(this,Pe)).map(e=>E(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},ht=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()}))})},qe=function(e){let t=n(this,ce)!==e;return h(this,ce,e),t&&e==="up-to-date"},Wt=function(e){e instanceof y&&(h(this,Y,e),u(this,R,ct).call(this))},ct=function(){n(this,V).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{De as BackoffDefaults,Je as ELECTRIC_PROTOCOL_QUERY_PARAMS,y as FetchError,Yt as Shape,tt as ShapeStream,z as isChangeMessage,Oe as isControlMessage,Qe as isVisibleInSnapshot,Ot as resolveValue};
|
|
6
6
|
//# sourceMappingURL=index.browser.mjs.map
|