@live-state/sync 0.0.6 → 0.0.7-canary-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-LSAVBBUS.js +1 -0
- package/dist/chunk-NKM6VWL7.js +1 -0
- package/dist/chunk-RSSRYEM3.js +1 -0
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +2 -2
- package/dist/fetch-client.js +1 -1
- package/dist/index-CLkafi56.d.ts +1016 -0
- package/dist/index-hO1iQ-VU.d.cts +608 -0
- package/dist/index-hO1iQ-VU.d.ts +608 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/optimistic-client.d.ts +3 -0
- package/dist/optimistic-client.js +1 -0
- package/dist/server.cjs +10 -4
- package/dist/server.d.cts +262 -86
- package/dist/server.d.ts +262 -86
- package/dist/server.js +8 -2
- package/package.json +6 -1
- package/dist/chunk-AHF6GNMI.js +0 -1
- package/dist/chunk-IT5UC7TA.js +0 -1
- package/dist/index-BtsKDfTE.d.cts +0 -282
- package/dist/index-BtsKDfTE.d.ts +0 -282
- package/dist/index-P-s1Yf1S.d.ts +0 -520
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var M=class t{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,n,i,r,a,l,o,T){this._collection=e,this._client=n,this._where=i??{},this._include=r??{},this._limit=a,this._single=l,this._sort=o,this._shouldAwait=T,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new t(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new t(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new t(this._collection,this._client,this._where,this._include,e,this._single,this._sort,this._shouldAwait)}one(e){return this.first({id:e})}first(e){return new t(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,n="asc"){let i=[...this._sort??[],{key:e,direction:n}];return new t(this._collection,this._client,this._where,this._include,this._limit,this._single,i,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}buildQueryRequest(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}get(){let e=this._client.get(this.buildQueryRequest());return this._shouldAwait?Promise.resolve(e).then(n=>this._single?n[0]:n):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),n=>{if(this._single)return e(n[0]);e(n);})}static _init(e,n,i){return new t(e,n,void 0,void 0,void 0,void 0,void 0,i??false)}};var b="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var d;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID";})(d||(d={}));var y=class extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e;}};function w(t){let e=Math.floor(t()*32);return e===32&&(e=31),b.charAt(e)}function V(t){let e=_(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return n.getRandomValues(i),i[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return ()=>n.randomBytes(1).readUInt8()/255;throw new y(d.PRNGDetectFailure,"Failed to find a reliable PRNG")}function _(){return S()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function N(t,e){let n="";for(;t>0;t--)n=w(e)+n;return n}function E(t,e=10){if(isNaN(t))throw new y(d.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>0xffffffffffff)throw new y(d.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${t}`);if(t<0)throw new y(d.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===false)throw new y(d.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,i="";for(let r=e;r>0;r--)n=t%32,i=b.charAt(n)+i,t=(t-n)/32;return i}function S(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function A(t,e){let n=V(),i=Date.now();return E(i,10)+N(16,n)}var Q=()=>A().toLowerCase();var J=(t,e)=>typeof t=="function"?t(e):t;var D=(t,e,n=[])=>new Proxy(t,{get:(i,r)=>{var T,m;if(r==="__isProxy__")return true;let a=(T=e.get)==null?void 0:T.call(e,i,[...n,r]);if(a!==void 0)return a;let l=i,o=r;return (m=l[o])!=null&&m.__isProxy__||(l[o]=D(typeof l[o]=="object"?l[o]:()=>{},e,[...n,r])),l[o]},apply:(i,r,a)=>{var l;return (l=e.apply)==null?void 0:l.call(e,i,n,a)}}),X=(t,e,n)=>{let i=[],r=0;for(let a=0;a<t.length&&(n===void 0||r<n);a++)e(t[a],a)&&(i.push(t[a]),r++);return i};var C=t=>typeof t=="object"&&t!==null&&"value"in t&&!Array.isArray(t),h=t=>t?Array.isArray(t.value)?t.value.map(n=>C(n)?h(n):n):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([n,i])=>Array.isArray(i)?[n,i.map(r=>C(r)?h(r):r)]:C(i)?[n,h(i)]:[n,i])):void 0;export{M as a,Q as b,J as c,D as d,X as e,h as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {xxHash32}from'js-xxhash';var w=Object.create;var A=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var K=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of S(e))!E.call(t,a)&&a!==i&&A(t,a,{get:()=>e[a],enumerable:!(n=N(e,a))||n.enumerable});return t};var X=(t,e,i)=>(i=t!=null?w(F(t)):{},K(e||!t||!t.__esModule?A(i,"default",{value:t,enumerable:true}):i,t));var s=class{_value;_meta;_encodeInput;_decodeInput};var y=class t extends s{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,i,n){return this.inner.encodeMutation(e,i,n)}mergeMutation(e,i,n){return this.inner.mergeMutation(e,i,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}unique(){return new t(this.inner.unique())}index(){return new t(this.inner.index())}default(e){let i=new u(this.inner.storageType,this.inner.convertFunc,this.inner.isIndex,this.inner.isUnique,e,this.inner.foreignReference,this.inner.isPrimary);return new t(i)}primary(){return new t(this.inner.primary())}},u=class t extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,i,n,a,r,o,l){super(),this.storageType=e,this.convertFunc=i,this.isIndex=n??false,this.isUnique=a??false,this.defaultValue=r,this.foreignReference=o,this.isPrimary=l??false;}encodeMutation(e,i,n){return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){return n&&n._meta.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>0?[n,null]:[{value:this.convertFunc?this.convertFunc(i.value):i.value,_meta:i._meta},i]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new t(this.storageType,this.convertFunc,this.isIndex,true,void 0,this.foreignReference,this.isPrimary)}index(){return new t(this.storageType,this.convertFunc,true,this.isUnique,void 0,this.foreignReference,this.isPrimary)}default(e){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,void 0,this.foreignReference,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,null,this.foreignReference,this.isPrimary);return new y(e)}return new y(this)}withMeta(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}},x=class t extends u{constructor(){super("integer",e=>Number(e));}static create(){return new t}},D=x.create,T=class t extends u{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new t}static createId(){return new t().index().unique().primary()}static createReference(e){return new t(e)}},O=T.create,q=T.createId,j=T.createReference,L=class t extends u{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},$=L.create,h=class t extends u{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},_=h.create,R=class t extends u{enumValues;enumName;constructor(e,i,n,a,r){super("varchar",void 0,i,n,a,void 0,r),this.enumValues=e,this.enumName=`enum_${e.slice(0,5).join("_").slice(0,50)}`;}getStorageFieldType(){return {type:"varchar",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,primary:this.isPrimary,enumValues:this.enumValues,enumName:this.enumName}}unique(){return new t(this.enumValues,this.isIndex,true,void 0,this.isPrimary)}index(){return new t(this.enumValues,true,this.isUnique,void 0,this.isPrimary)}default(e){return new t(this.enumValues,this.isIndex,this.isUnique,e,this.isPrimary)}primary(){return new t(this.enumValues,this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.enumValues,this.isIndex,this.isUnique,null,this.isPrimary);return new y(e)}return new y(this)}static create(e){return new t(e)}},P=R.create,g=class t extends u{constructor(e,i,n,a){super("jsonb",r=>typeof r=="string"?JSON.parse(r):r,e,i,n,void 0,a);}getStorageFieldType(){return {type:"jsonb",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue!==void 0?JSON.stringify(this.defaultValue):void 0,primary:this.isPrimary}}unique(){return new t(this.isIndex,true,void 0,this.isPrimary)}index(){return new t(true,this.isUnique,void 0,this.isPrimary)}default(e){return new t(this.isIndex,this.isUnique,e,this.isPrimary)}primary(){return new t(this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.isIndex,this.isUnique,null,this.isPrimary);return new y(e)}return new y(this)}static create(){return new t}},W=g.create;var c=class t extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,i,n,a,r){super(),this.entity=e,this.type=i,this.required=r??false,this.relationalColumn=n,this.foreignColumn=a;}encodeMutation(e,i,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){var a;return this.type==="many"?n?[n,null]:[i,i]:(a=n==null?void 0:n._meta)!=null&&a.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[i,i]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (e,i,n)=>new t(e,"one",i,void 0,n??false)}static createManyFactory(){return (e,i,n)=>new t(e,"many",void 0,i,n??false)}},U=(t,e)=>({$type:"relations",collectionName:t.name,objectName:t.name,relations:e({one:c.createOneFactory(),many:c.createManyFactory()})});var v=class t extends s{name;fields;relations;constructor(e,i,n){super(),this.name=e,this.fields=i,this.relations=n??{};}encodeMutation(e,i,n){return Object.fromEntries(Object.entries(i).map(([a,r])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",r,n)]))}mergeMutation(e,i,n){let a={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(i).map(([r,o])=>{let l=this.fields[r]??this.relations[r];if(!l)return [r,o];let[d,m]=l.mergeMutation(e,o,n==null?void 0:n.value[r]);return m&&(a[r]=m),[r,d]}))}},a]}setRelations(e){return new t(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,i){if(B(i)){let n=i,a=new t(e,n.fields);if(n.relations){let r=n.relations({one:c.createOneFactory(),many:c.createManyFactory()});return new t(e,n.fields,r)}return a}return new t(e,i,void 0)}};function B(t){return typeof t=="object"&&t!==null&&"fields"in t&&typeof t.fields=="object"}var b=v.create,k=b,J=v;var V=t=>typeof t=="object"&&t!==null&&"value"in t&&!Array.isArray(t),C=t=>t?Array.isArray(t.value)?t.value.map(i=>V(i)?C(i):i):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([i,n])=>Array.isArray(n)?[i,n.map(a=>V(a)?C(a):a)]:V(n)?[i,C(n)]:[i,n])):void 0;var z=t=>Object.fromEntries(Object.entries(t).flatMap(([e,i])=>{if(i.$type==="relations")return [];let n=i,a=Object.values(t).find(r=>r.$type==="relations"&&r.collectionName===i.name);return a&&(n=n.setRelations(a.relations)),[[n.name,n]]}));var ve=t=>xxHash32(JSON.stringify(t)).toString(32),H=(t,e,i)=>{let n={},a=i[e];if(!a)return n;let r=o=>{o.$and?o.$and.forEach(r):o.$or?o.$or.forEach(r):Object.entries(o).forEach(([l,d])=>{var m;if((m=a.relations)!=null&&m[l]&&(n[l]=true,typeof d=="object"&&d!==null&&!Array.isArray(d))){let I=H(d,a.relations[l].entity.name,i);Object.keys(I).length>0&&(n[l]={include:I});}});};return r(t),n},p=(t,e,i=false)=>Object.entries(e).every(([n,a])=>{if(n==="$and")return a.every(o=>p(t,o,i));if(n==="$or")return a.some(o=>p(t,o,i));let r=(a==null?void 0:a.$eq)!==void 0?a==null?void 0:a.$eq:a;if(typeof a=="object"&&a!==null&&(a==null?void 0:a.$eq)===void 0){if(a.$in!==void 0){let l=t[n];return l===void 0?false:i?!a.$in.includes(l):a.$in.includes(l)}if(a.$not!==void 0&&!i)return p(t,{[n]:a.$not},true);if(a.$gt!==void 0){let l=t[n];return typeof l!="number"?false:i?l<=a.$gt:l>a.$gt}if(a.$gte!==void 0){let l=t[n];return typeof l!="number"?false:i?l<a.$gte:l>=a.$gte}if(a.$lt!==void 0){let l=t[n];return typeof l!="number"?false:i?l>=a.$lt:l<a.$lt}if(a.$lte!==void 0){let l=t[n];return typeof l!="number"?false:i?l>a.$lte:l<=a.$lte}let o=t[n];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?i?!o.some(l=>p(l,a,false)):o.some(l=>p(l,a,false)):p(o,a,i)}return i?t[n]!==r:t[n]===r}),f={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},M=class{level;prefix;constructor(e={}){this.level=e.level??f.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=f.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=f.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=f.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=f.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=f.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},xe=t=>new M(t);export{z as A,ve as B,H as C,p as D,f as E,xe as F,Q as a,X as b,s as c,y as d,u as e,x as f,D as g,T as h,O as i,q as j,j as k,L as l,$ as m,h as n,_ as o,R as p,P as q,g as r,W as s,c as t,U as u,v,b as w,k as x,J as y,C as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=(a,p)=>{let i=[],o=n=>{let t=(e,c,s,u)=>({get:()=>{let m={resource:n,where:u?{id:u}:e??{},include:c??{},limit:s?1:void 0},d=a.get(m);return s?d[0]:d},include:m=>({get:()=>{let d={resource:n,where:u?{id:u}:e??{},include:m??{},limit:s?1:void 0},y=a.get(d);return s?y[0]:y}})});return {one:e=>t(void 0,void 0,true,e),where:e=>t(e,void 0,false),get:()=>t().get(),include:e=>t(void 0,e,false),insert:e=>{let{id:c,...s}=e;i.push({type:"insert",resource:n,id:c,data:s});},update:(e,c)=>{i.push({type:"update",resource:n,id:e,data:c});}}};return {proxy:new Proxy({},{get(n,t){if(typeof t=="string"&&t in p)return o(t)}}),getOperations:()=>i}};var x=a=>{let p=new Map;for(let[i,o]of Object.entries(a)){if(!o)continue;let r=new Map;for(let[n,t]of Object.entries(o))t&&typeof t=="function"&&r.set(n,t);r.size>0&&p.set(i,r);}return {getHandler:(i,o)=>{var r;return (r=p.get(i))==null?void 0:r.get(o)}}};export{g as a,x as b};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import 'zod';
|
|
1
|
+
export { z as Client, y as ClientEvents, C as ClientOptions, a as ClientRouterConstraint, n as ClientStorageLoadedEvent, m as ConnectionStateChangeEvent, o as DataLoadReplyEvent, D as DataLoadRequestedEvent, M as MessageReceivedEvent, q as MutationReceivedEvent, r as MutationRejectedEvent, p as MutationSentEvent, e as OptimisticHandlerContext, w as OptimisticMutationAppliedEvent, x as OptimisticMutationUndoneEvent, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, Q as QueryExecutedEvent, t as QuerySubscriptionTriggeredEvent, v as StoreStateUpdatedEvent, S as SubscriptionCreatedEvent, s as SubscriptionRemovedEvent, A as createClient, d as defineOptimisticMutations, u as useLiveQuery, l as useLoadData } from './index-CLkafi56.js';
|
|
3
2
|
import '@standard-schema/spec';
|
|
3
|
+
import 'zod';
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,c,a,f,e,b as b$1}from'./chunk-AHF6GNMI.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z as z$1}from'zod';import {stringify}from'qs';import ue from'fast-deep-equal';import {openDB}from'idb';var m=d=>xxHash32(JSON.stringify(d)).toString(32);var b=(d,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(r=>b(d,r,t));if(i==="$or")return s.some(r=>b(d,r,t));let o=(s==null?void 0:s.$eq)!==void 0?s==null?void 0:s.$eq:s;if(typeof s=="object"&&s!==null&&(s==null?void 0:s.$eq)===void 0){if(s.$in!==void 0){let n=d[i];return n===void 0?false:t?!s.$in.includes(n):s.$in.includes(n)}if(s.$not!==void 0&&!t)return b(d,{[i]:s.$not},true);if(s.$gt!==void 0){let n=d[i];return typeof n!="number"?false:t?n<=s.$gt:n>s.$gt}if(s.$gte!==void 0){let n=d[i];return typeof n!="number"?false:t?n<s.$gte:n>=s.$gte}if(s.$lt!==void 0){let n=d[i];return typeof n!="number"?false:t?n>=s.$lt:n<s.$lt}if(s.$lte!==void 0){let n=d[i];return typeof n!="number"?false:t?n>s.$lte:n<=s.$lte}let r=d[i];return !r||typeof r!="object"&&!Array.isArray(r)?false:Array.isArray(r)?t?!r.some(n=>b(n,s,false)):r.some(n=>b(n,s,false)):b(r,s,t)}return t?d[i]!==o:d[i]===o}),v={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},L=class{level;prefix;constructor(e={}){this.level=e.level??v.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=v.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=v.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=v.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=v.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=v.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},$=d=>new L(d);var I=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=m(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let s={subscribe:o=>{let r=this.subscriptions.get(i);return r.callbacks.add(o),r.unsubscribe||(r.unsubscribe=()=>{},r.unsubscribe=e.subscribe(()=>{r.callbacks.forEach(n=>{n();});})),()=>{var n;(n=this.subscriptions.get(i))==null||n.callbacks.delete(o),setTimeout(()=>{var c;let a=this.subscriptions.get(i);a&&a.callbacks.size===0&&((c=a.unsubscribe)==null||c.call(a),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,s),this.subscriptions.get(i).subscribe}},Z=new I,ye=d=>useSyncExternalStore(Z.getOrStoreSubscription(d),d.get),fe=(d,e)=>{useEffect(()=>{let t=d.load(e.buildQueryRequest());return ()=>{t();}},[e,d.load]);};var R=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),x=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),ee=x.superRefine((d,e)=>{d.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),B=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),j=B.extend({procedure:z$1.string(),payload:z$1.any().optional()}),k=B.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:ee});z$1.union([k,j]);var E=z$1.string(),te=R.extend({id:E,type:z$1.literal("SUBSCRIBE")}),ie=R.extend({id:E,type:z$1.literal("UNSUBSCRIBE")}),se=R.extend({id:E,type:z$1.literal("QUERY")}),G=k.extend({id:E}),ne=j.extend({id:E}),re=z$1.union([ne,G]);z$1.union([te,se,re,ie]);var oe=z$1.object({id:E,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),ae=z$1.object({id:E,type:z$1.literal("REPLY"),data:z$1.any()}),q=z$1.union([oe,ae,G]),z=z$1.object({resource:z$1.string(),data:z$1.array(x)});var T=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;credentials;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.credentials=e.credentials,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}async connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.intentionallyDisconnected=false;let e=await b$1(this.credentials);this.ws=new WebSocket(this.url+(e?`?${stringify(e)}`:"")),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t);}removeEventListener(e,t){var i;this.eventListeners.has(e)&&((i=this.eventListeners.get(e))==null||i.delete(t));}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){var t,i;this.dispatchEvent("error",e),this.dispatchEvent("connectionChange",{open:false}),(i=(t=e.error)==null?void 0:t.message)!=null&&i.includes("non-101")&&(this.ws&&(this.ws.close(),this.ws=null),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect());}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){var i;(i=this.eventListeners.get(e))==null||i.forEach(s=>{s(t);});}};var O=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(o=>[o,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,s),s}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),s=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);i.references.set(s.type,t);let o=s.referencedBy.get(i.type);o&&o instanceof Set?o.add(e):s.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let s=i.references.get(t);if(!s)return;i.references.delete(t);let o=this.nodes.get(s);if(!o)return;let r=o.referencedBy.get(i.type);r&&(r instanceof Set?r.delete(e):o.referencedBy.delete(i.type),this.notifySubscribers(s)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,s])=>{(s instanceof Set?Array.from(s.values()):[s]).forEach(r=>{let n=this.nodes.get(r);!n||!n.references.get(i)||(n.references.delete(i),this.notifySubscribers(r));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(o){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,o);}});}getAllNodes(){return Array.from(this.nodes.values())}};var D="__meta",C="databases",w=class{db;async init(e,t){var c,p;if(typeof window>"u")return;let s=((c=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:c.version)??1,o=await m(e),r=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,l])=>[u,await m(l)]))),n=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(C)||u.createObjectStore(C);}}),a=(p=await this.getAll(n,C))==null?void 0:p[t];(a==null?void 0:a.schemaHash)!==o&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),D].forEach(l=>{(a==null?void 0:a.objectHashes[l])!==r[l]&&u.objectStoreNames.contains(l)&&u.deleteObjectStore(l),u.objectStoreNames.contains(l)||u.createObjectStore(l);}),await n.put(C,{schemaHash:o,objectHashes:r},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var s;return (s=this.db)==null?void 0:s.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(D,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(D,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((o,r)=>[s[r],o]))}};var A=class{constructor(e,t,i,s,o,r){this.schema=e;this.logger=i,this.optimisticObjGraph=new O(i),this.kvStorage=new w,this.onQuerySubscriptionTriggered=r,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{this.kvStorage.getMeta("mutationStack").then(n=>{!n||Object.keys(n).length===0||(this.optimisticMutationStack=n,s==null||s(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([n])=>{this.kvStorage.get(n).then(a=>{if(!a||Object.keys(a).length===0){o==null||o(n,0);return}let c=Object.entries(a).map(([p,u])=>({...u,id:{value:p}}));o==null||o(n,c.length),this.loadConsolidatedState(n,c);});});}).catch(n=>{i.debug("Storage initialization failed (may not be available in this environment):",n);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var a;let s=t??m(e$1);if(this.querySnapshots[s]&&!i){let c=this.querySnapshots[s];if(c)return c}let o,r=(a=e$1.where)==null?void 0:a.id;r===void 0?o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):typeof r=="string"?o=[r]:typeof r=="object"&&r!==null?"$in"in r&&Array.isArray(r.$in)?o=r.$in:"$eq"in r&&typeof r.$eq=="string"?o=[r.$eq]:o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{});let n=o.flatMap(c=>{let p=f(this.materializeOneWithInclude(c,e$1.include));return p?[p]:[]});if(e$1.sort&&e$1.sort.length>0){let c=(p,u)=>{for(let l of e$1.sort){let f=p[l.key],g=u[l.key];if(f<g)return l.direction==="asc"?-1:1;if(f>g)return l.direction==="asc"?1:-1}return 0};n.sort(c);}if(e$1.where||e$1.limit){let c=e$1.where?p=>b(p,e$1.where):()=>true;n=e(n,c,e$1.limit);}return i||(this.querySnapshots[s]=n),n}subscribe(e,t){var o;let i=m(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(o=this.collectionSubscriptions.get(i))==null||o.callbacks.add(t),()=>{var r,n;(r=this.collectionSubscriptions.get(i))==null||r.callbacks.delete(t),((n=this.collectionSubscriptions.get(i))==null?void 0:n.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var r,n,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let o=(r=this.optimisticRawObjPool[e])==null?void 0:r[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(n=this.optimisticMutationStack)==null?void 0:n[e])==null?void 0:a.filter(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let c={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=c;let p=c.value;delete p.id,this.kvStorage.set(e,t.resourceId,p);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,o);}undoMutation(e,t){var r,n;if(!this.optimisticMutationStack[e])return;let i=(r=this.optimisticMutationStack[e])==null?void 0:r.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let o=(n=this.optimisticRawObjPool[e])==null?void 0:n[s.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,s.resourceId,Object.fromEntries(Object.entries(s.payload).map(([a])=>[a,{value:null,_meta:{}}])),o);}loadConsolidatedState(e,t){t.forEach(i=>{var n;let s=(n=i.id)==null?void 0:n.value;if(!s)return;let{cleanedPayload:o,nestedMutations:r}=this.extractNestedRelations(e,i);r.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:o});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},o=[];return i!=null&&i.relations?(Object.entries(t).forEach(([r,n])=>{var u;let a=i.relations[r];if(!a)return;let c=a.entity.name,p=n==null?void 0:n.value;if(a.type==="one"){if(p&&typeof p=="object"&&!Array.isArray(p)&&((u=p.id)!=null&&u.value)){let l=p.id.value,f={...p},{cleanedPayload:g,nestedMutations:S}=this.extractNestedRelations(c,f);o.push(...S),o.push({id:l,type:"MUTATE",resource:c,resourceId:l,procedure:"INSERT",payload:g}),delete s[r];}}else a.type==="many"&&Array.isArray(p)&&(p.forEach(l=>{var f,g;if(l&&typeof l=="object"&&!Array.isArray(l)&&((g=(f=l.value)==null?void 0:f.id)!=null&&g.value)){let S=l.value.id.value,H={...l.value},{cleanedPayload:V,nestedMutations:Y}=this.extractNestedRelations(c,H);o.push(...Y),o.push({id:S,type:"MUTATE",resource:c,resourceId:S,procedure:"INSERT",payload:V});}}),delete s[r]);}),{cleanedPayload:s,nestedMutations:o}):{cleanedPayload:s,nestedMutations:o}}updateRawObjPool(e,t,i,s){var n;if(!this.schema[e])return;let o=(n=this.rawObjPool[e])==null?void 0:n[t],r=(this.optimisticMutationStack[e]??[]).reduce((a,c)=>c.resourceId!==t?a:this.schema[e].mergeMutation("set",c.payload,a)[0],o);if(this.optimisticRawObjPool[e]??={},r?this.optimisticRawObjPool[e][t]={value:{...r.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!r)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(a=>a.type==="many"?[a.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let a=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([c,p])=>p.type==="one"?[[p.relationalColumn,c]]:[]));Object.entries(i).forEach(([c,p])=>{let u=this.schema[e].relations[a[c]];if(!a[c])return;let l=s==null?void 0:s.value[c],[,f]=u.mergeMutation("set",p,l);if(f){if(!this.optimisticObjGraph.hasNode(f.value)){let g=u.entity.name;this.optimisticObjGraph.createNode(f.value,g,Object.values(this.schema[g].relations).flatMap(S=>S.type==="many"?[S.entity.name]:[]));}l!=null&&l.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,f.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var a;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let s=i.type,o=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!o)return;let[r,n]=Object.entries(t).reduce((c,[p,u])=>{let l=this.schema[s].relations[p];return l&&(l.type==="one"?c[0].push([p,l.entity.name,u??true]):l.type==="many"&&c[1].push([p,l.entity.name,u??true])),c},[[],[]]);return {value:{...o.value,...Object.fromEntries(r.map(([c,p,u])=>[c,this.materializeOneWithInclude(i.references.get(p),typeof u=="object"&&u!==null?u:{})])),...Object.fromEntries(n.map(([c,p,u])=>{let l=i.referencedBy.get(p),f=l instanceof Set;return [c,f?{value:Array.from(l.values()).map(g=>this.materializeOneWithInclude(g,typeof u=="object"&&u!==null?u:{}))}:this.materializeOneWithInclude(l,typeof u=="object"&&u!==null?u:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,s;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let o=m(t.query),r=this.querySnapshots[o],n=this.get(t.query,void 0,true);if(ue(n,r))return;this.querySnapshots[o]=n,(s=this.onQuerySubscriptionTriggered)==null||s.call(this,t.query),t.callbacks.forEach(a=>{a(n);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,o])=>{var a;let r=(a=this.schema[t])==null?void 0:a.relations[s];if(!r)return;let n=r.entity.name;i.push(n),typeof o=="object"&&o!==null&&i.push(...this.flattenIncludes(o,n));}),Array.from(new Set(i))}};var P=class{url;ws;store;logger;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,o;this.url=e.url,this.logger=$({level:e.logLevel??v.INFO}),this.store=new A(e.schema,e.storage,this.logger,r=>{var n,a;(a=(n=Object.values(r))==null?void 0:n.flat())==null||a.forEach(c=>{this.sendWsMessage(c);});},(r,n)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:r,itemCount:n});},r=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:r});}),this.ws=new T({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(o=e.connection)==null?void 0:o.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",r=>{this.handleServerMessage(r.data);}),this.ws.addEventListener("connectionChange",r=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:r.open}),r.open&&(Array.from(this.remoteSubscriptions.values()).forEach(({query:n})=>{this.sendWsMessage({id:a(),type:"SUBSCRIBE",...n});}),Object.values(this.store.optimisticMutationStack).forEach(n=>{n&&n.forEach(a=>{this.emitEvent({type:"MUTATION_SENT",mutationId:a.id,resource:a.resource,resourceId:a.resourceId,procedure:a.procedure??"UNKNOWN",optimistic:true}),this.sendWsMessage(a);});}));});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i;try{this.logger.debug("Message received from the server:",e);let s=q.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",s),this.emitEvent({type:"MESSAGE_RECEIVED",message:s}),s.type==="MUTATE"){let{resource:o,id:r,resourceId:n,procedure:a}=s;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:r,resource:o,resourceId:n,procedure:a??"UNKNOWN"});try{this.store.addMutation(o,s);}catch(c){this.logger.error("Error merging mutation from the server:",c);}}else if(s.type==="REJECT"){let o=((t=this.store.optimisticMutationStack[s.resource])==null?void 0:t.length)??0,r=(i=this.store.optimisticMutationStack[s.resource])==null?void 0:i.find(n=>n.id===s.id);this.store.undoMutation(s.resource,s.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:s.id,resource:s.resource}),r&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s.id,resource:s.resource,resourceId:r.resourceId,pendingMutations:o-1});}else if(s.type==="REPLY"){let{id:o,data:r}=s;if(this.replyHandlers[o]){clearTimeout(this.replyHandlers[o].timeoutHandle),this.replyHandlers[o].handler(r);return}let n=z.parse(r);this.emitEvent({type:"DATA_LOAD_REPLY",resource:n.resource,itemCount:n.data.length}),this.store.loadConsolidatedState(n.resource,n.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:n.resource,itemCount:n.data.length});}}catch(s){this.logger.error("Error parsing message from the server:",s);}}load(e){let t=a(),i=m(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let s=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),s&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let o=this.remoteSubscriptions.get(i);o.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:a(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var n,a$1;let o={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i},r=(((n=this.store.optimisticMutationStack[e])==null?void 0:n.length)??0)+1;(a$1=this.store)==null||a$1.addMutation(e,o,true),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:o.id,resource:e,resourceId:t,procedure:i,pendingMutations:r}),this.emitEvent({type:"MUTATION_SENT",mutationId:o.id,resource:e,resourceId:t,procedure:i,optimistic:true}),this.sendWsMessage(o);}genericMutate(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let s={id:a(),type:"MUTATE",resource:e,procedure:t,payload:i};return this.emitEvent({type:"MUTATION_SENT",mutationId:s.id,resource:e,resourceId:"",procedure:t,optimistic:false}),this.sendWsMessage(s),new Promise((o,r)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],r(new Error("Reply timeout"));},5e3),handler:n=>{delete this.replyHandlers[s.id],o(n);}};})}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},ze=d$1=>{let e=new P(d$1);return {client:{ws:e.ws,load:t=>e.load(t),addEventListener:t=>e.addEventListener(t)},store:{query:Object.entries(d$1.schema).reduce((t,[i,s])=>(t[i]=c._init(s,e),t),{}),mutate:d(()=>{},{apply:(t,i,s)=>{if(i.length<2)return;if(i.length>2)throw new Error("Trying to access an invalid path");let[o,r]=i;if(r==="insert"){let{id:n,...a}=s[0];return e.mutate(o,n,"INSERT",a)}if(r==="update"){let[n,a]=s;return e.mutate(o,n,"UPDATE",a)}return e.genericMutate(o,r,s[0])}})}}};export{ze as createClient,ye as useLiveQuery,fe as useLoadData};
|
|
1
|
+
import {d,a,b,f as f$1,e,c}from'./chunk-LSAVBBUS.js';import {a as a$1}from'./chunk-RSSRYEM3.js';export{b as defineOptimisticMutations}from'./chunk-RSSRYEM3.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z as z$1}from'zod';import {stringify}from'qs';import ge from'fast-deep-equal';import {openDB}from'idb';var f=h=>xxHash32(JSON.stringify(h)).toString(32);var M=(h,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>M(h,n,t));if(i==="$or")return s.some(n=>M(h,n,t));let o=(s==null?void 0:s.$eq)!==void 0?s==null?void 0:s.$eq:s;if(typeof s=="object"&&s!==null&&(s==null?void 0:s.$eq)===void 0){if(s.$in!==void 0){let r=h[i];return r===void 0?false:t?!s.$in.includes(r):s.$in.includes(r)}if(s.$not!==void 0&&!t)return M(h,{[i]:s.$not},true);if(s.$gt!==void 0){let r=h[i];return typeof r!="number"?false:t?r<=s.$gt:r>s.$gt}if(s.$gte!==void 0){let r=h[i];return typeof r!="number"?false:t?r<s.$gte:r>=s.$gte}if(s.$lt!==void 0){let r=h[i];return typeof r!="number"?false:t?r>=s.$lt:r<s.$lt}if(s.$lte!==void 0){let r=h[i];return typeof r!="number"?false:t?r>s.$lte:r<=s.$lte}let n=h[i];return !n||typeof n!="object"&&!Array.isArray(n)?false:Array.isArray(n)?t?!n.some(r=>M(r,s,false)):n.some(r=>M(r,s,false)):M(n,s,t)}return t?h[i]!==o:h[i]===o}),v={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},A=class{level;prefix;constructor(e={}){this.level=e.level??v.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=v.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=v.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=v.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=v.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=v.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},B=h=>new A(h);var x=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=f(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let s={subscribe:o=>{let n=this.subscriptions.get(i);return n.callbacks.add(o),n.unsubscribe||(n.unsubscribe=()=>{},n.unsubscribe=e.subscribe(()=>{n.callbacks.forEach(r=>{r();});})),()=>{var r;(r=this.subscriptions.get(i))==null||r.callbacks.delete(o),setTimeout(()=>{var c;let a=this.subscriptions.get(i);a&&a.callbacks.size===0&&((c=a.unsubscribe)==null||c.call(a),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,s),this.subscriptions.get(i).subscribe}},re=new x,Se=h=>useSyncExternalStore(re.getOrStoreSubscription(h),h.get),Ee=(h,e)=>{useEffect(()=>{let t=h.load(e.buildQueryRequest());return ()=>{t();}},[e,h.load]);};var G=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),L=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),oe=L.superRefine((h,e)=>{h.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),H=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),z=z$1.object({timestamp:z$1.string().optional()}).optional(),j=H.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:z}),k=H.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:oe,meta:z});z$1.union([k,j]);var K=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var S=z$1.string(),D=z$1.union([K,G]),ae=z$1.object({id:S,type:z$1.literal("SUBSCRIBE")}).and(D),ce=z$1.object({id:S,type:z$1.literal("UNSUBSCRIBE")}).and(D),ue=z$1.object({id:S,type:z$1.literal("QUERY")}).and(D),le=z$1.object({id:S,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),Y=k.extend({id:S}),pe=j.extend({id:S}),de=z$1.union([pe,Y]);z$1.union([ae,ue,le,de,ce]);var he=z$1.object({id:S,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),ye=z$1.object({id:S,type:z$1.literal("REPLY"),data:z$1.any()}),V=z$1.union([he,ye,Y]),F=z$1.object({resource:z$1.string(),data:z$1.array(L)});var T=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;credentials;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.credentials=e.credentials,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}async connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.intentionallyDisconnected=false;let e=await c(this.credentials);this.ws=new WebSocket(this.url+(e?`?${stringify(e)}`:"")),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t);}removeEventListener(e,t){var i;this.eventListeners.has(e)&&((i=this.eventListeners.get(e))==null||i.delete(t));}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){var t,i;this.dispatchEvent("error",e),this.dispatchEvent("connectionChange",{open:false}),(i=(t=e.error)==null?void 0:t.message)!=null&&i.includes("non-101")&&(this.ws&&(this.ws.close(),this.ws=null),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect());}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){var i;(i=this.eventListeners.get(e))==null||i.forEach(s=>{s(t);});}};var O=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(o=>[o,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,s),s}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),s=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);i.references.set(s.type,t);let o=s.referencedBy.get(i.type);o&&o instanceof Set?o.add(e):s.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let s=i.references.get(t);if(!s)return;i.references.delete(t);let o=this.nodes.get(s);if(!o)return;let n=o.referencedBy.get(i.type);n&&(n instanceof Set?n.delete(e):o.referencedBy.delete(i.type),this.notifySubscribers(s)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,s])=>{(s instanceof Set?Array.from(s.values()):[s]).forEach(n=>{let r=this.nodes.get(n);!r||!r.references.get(i)||(r.references.delete(i),this.notifySubscribers(n));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(o){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,o);}});}getAllNodes(){return Array.from(this.nodes.values())}};var P="__meta",R="databases",C=class{db;async init(e,t){var c,l;if(typeof window>"u")return;let s=((c=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:c.version)??1,o=await f(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,p])=>[u,await f(p)]))),r=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(R)||u.createObjectStore(R);}}),a=(l=await this.getAll(r,R))==null?void 0:l[t];(a==null?void 0:a.schemaHash)!==o&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),P].forEach(p=>{(a==null?void 0:a.objectHashes[p])!==n[p]&&u.objectStoreNames.contains(p)&&u.deleteObjectStore(p),u.objectStoreNames.contains(p)||u.createObjectStore(p);}),await r.put(R,{schemaHash:o,objectHashes:n},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var s;return (s=this.db)==null?void 0:s.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(P,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(P,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((o,n)=>[s[n],o]))}};var w=class{constructor(e,t,i,s,o,n){this.schema=e;this.logger=i,this.optimisticObjGraph=new O(i),this.kvStorage=new C,this.onQuerySubscriptionTriggered=n,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{Promise.all([this.kvStorage.getMeta("mutationStack"),this.kvStorage.getMeta("customMutationStack"),this.kvStorage.getMeta("customMutationIndex")]).then(([r,a,c])=>{r&&Object.keys(r).length>0&&(this.optimisticMutationStack=r),a&&a.length>0&&(this.customMutationStack=a),c&&Object.keys(c).length>0&&(this.customMutationIndex=c),s==null||s(this.optimisticMutationStack,this.customMutationStack,this.customMutationIndex);}).then(()=>{Object.entries(this.schema).forEach(([r])=>{this.kvStorage.get(r).then(a=>{if(!a||Object.keys(a).length===0){o==null||o(r,0);return}let c=Object.entries(a).map(([l,u])=>({...u,id:{value:l}}));o==null||o(r,c.length),this.loadConsolidatedState(r,c);});});}).catch(r=>{i.debug("Storage initialization failed (may not be available in this environment):",r);});});}rawObjPool={};optimisticMutationStack={};customMutationStack=[];optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;customMutationIndex={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var a;let s=t??f(e$1);if(this.querySnapshots[s]&&!i){let c=this.querySnapshots[s];if(c)return c}let o,n=(a=e$1.where)==null?void 0:a.id;n===void 0?o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):typeof n=="string"?o=[n]:typeof n=="object"&&n!==null?"$in"in n&&Array.isArray(n.$in)?o=n.$in:"$eq"in n&&typeof n.$eq=="string"?o=[n.$eq]:o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{});let r=o.flatMap(c=>{let l=f$1(this.materializeOneWithInclude(c,e$1.include));return l?[l]:[]});if(e$1.sort&&e$1.sort.length>0){let c=(l,u)=>{for(let p of e$1.sort){let m=l[p.key],g=u[p.key];if(m<g)return p.direction==="asc"?-1:1;if(m>g)return p.direction==="asc"?1:-1}return 0};r.sort(c);}if(e$1.where||e$1.limit){let c=e$1.where?l=>M(l,e$1.where):()=>true;r=e(r,c,e$1.limit);}return !i&&this.collectionSubscriptions.has(s)&&(this.querySnapshots[s]=r),r}subscribe(e,t){var o;let i=f(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(o=this.collectionSubscriptions.get(i))==null||o.callbacks.add(t),()=>{var n,r;(n=this.collectionSubscriptions.get(i))==null||n.callbacks.delete(t),((r=this.collectionSubscriptions.get(i))==null?void 0:r.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var n,r,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let o=(n=this.optimisticRawObjPool[e])==null?void 0:n[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(r=this.optimisticMutationStack)==null?void 0:r[e])==null?void 0:a.filter(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let c={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=c;let l=c.value;delete l.id,this.kvStorage.set(e,t.resourceId,l);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,o);}undoMutation(e,t){var n,r;if(!this.optimisticMutationStack[e])return;let i=(n=this.optimisticMutationStack[e])==null?void 0:n.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let o=(r=this.optimisticRawObjPool[e])==null?void 0:r[s.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,s.resourceId,Object.fromEntries(Object.entries(s.payload).map(([a])=>[a,{value:null,_meta:{}}])),o);}addCustomMutationMessage(e){this.customMutationStack.push(e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}registerCustomMutation(e,t){this.customMutationIndex[e]=t,this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex);}confirmCustomMutation(e){let t=this.customMutationIndex[e];if(t){for(let{resource:i,mutationId:s}of t)this.undoMutation(i,s);delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(i=>i.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}}undoCustomMutation(e){var s;let t=this.customMutationIndex[e];if(!t)return [];let i=[];for(let{resource:o,mutationId:n}of t){let r=(s=this.optimisticMutationStack[o])==null?void 0:s.find(a=>a.id===n);this.undoMutation(o,n),r&&i.push({resource:o,mutationId:n,resourceId:r.resourceId});}return delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(o=>o.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack),i}getCustomMutationMutationIds(){let e=new Set;for(let t of Object.values(this.customMutationIndex))for(let{mutationId:i}of t)e.add(i);return e}loadConsolidatedState(e,t){t.forEach(i=>{var r;let s=(r=i.id)==null?void 0:r.value;if(!s)return;let{cleanedPayload:o,nestedMutations:n}=this.extractNestedRelations(e,i);n.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:o});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},o=[];return i!=null&&i.relations?(Object.entries(t).forEach(([n,r])=>{var u;let a=i.relations[n];if(!a)return;let c=a.entity.name,l=r==null?void 0:r.value;if(a.type==="one"){if(l&&typeof l=="object"&&!Array.isArray(l)&&((u=l.id)!=null&&u.value)){let p=l.id.value,m={...l},{cleanedPayload:g,nestedMutations:E}=this.extractNestedRelations(c,m);o.push(...E),o.push({id:p,type:"MUTATE",resource:c,resourceId:p,procedure:"INSERT",payload:g}),delete s[n];}}else a.type==="many"&&Array.isArray(l)&&(l.forEach(p=>{var m,g;if(p&&typeof p=="object"&&!Array.isArray(p)&&((g=(m=p.value)==null?void 0:m.id)!=null&&g.value)){let E=p.value.id.value,X={...p.value},{cleanedPayload:Z,nestedMutations:ee}=this.extractNestedRelations(c,X);o.push(...ee),o.push({id:E,type:"MUTATE",resource:c,resourceId:E,procedure:"INSERT",payload:Z});}}),delete s[n]);}),{cleanedPayload:s,nestedMutations:o}):{cleanedPayload:s,nestedMutations:o}}updateRawObjPool(e,t,i,s){var r;if(!this.schema[e])return;let o=(r=this.rawObjPool[e])==null?void 0:r[t],n=(this.optimisticMutationStack[e]??[]).reduce((a,c)=>c.resourceId!==t?a:this.schema[e].mergeMutation("set",c.payload,a)[0],o);if(this.optimisticRawObjPool[e]??={},n?this.optimisticRawObjPool[e][t]={value:{...n.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!n)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(a=>a.type==="many"?[a.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let a=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([c,l])=>l.type==="one"?[[l.relationalColumn,c]]:[]));Object.entries(i).forEach(([c,l])=>{let u=this.schema[e].relations[a[c]];if(!a[c])return;let p=s==null?void 0:s.value[c],[,m]=u.mergeMutation("set",l,p);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let g=u.entity.name;this.optimisticObjGraph.createNode(m.value,g,Object.values(this.schema[g].relations).flatMap(E=>E.type==="many"?[E.entity.name]:[]));}p!=null&&p.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,m.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var a;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let s=i.type,o=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!o)return;let[n,r]=Object.entries(t).reduce((c,[l,u])=>{let p=this.schema[s].relations[l];return p&&(p.type==="one"?c[0].push([l,p.entity.name,u??true]):p.type==="many"&&c[1].push([l,p.entity.name,u??true])),c},[[],[]]);return {value:{...o.value,...Object.fromEntries(n.map(([c,l,u])=>[c,this.materializeOneWithInclude(i.references.get(l),typeof u=="object"&&u!==null?u:{})])),...Object.fromEntries(r.map(([c,l,u])=>{let p=i.referencedBy.get(l),m=p instanceof Set;return [c,m?{value:Array.from(p.values()).map(g=>this.materializeOneWithInclude(g,typeof u=="object"&&u!==null?u:{}))}:this.materializeOneWithInclude(p,typeof u=="object"&&u!==null?u:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,s;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let o=f(t.query),n=this.querySnapshots[o],r=this.get(t.query,void 0,true);if(ge(r,n))return;this.querySnapshots[o]=r,(s=this.onQuerySubscriptionTriggered)==null||s.call(this,t.query),t.callbacks.forEach(a=>{a(r);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,o])=>{var a;let n=(a=this.schema[t])==null?void 0:a.relations[s];if(!n)return;let r=n.entity.name;i.push(r),typeof o=="object"&&o!==null&&i.push(...this.flattenIncludes(o,r));}),Array.from(new Set(i))}};var I=class{constructor(e,t){this.client=e;this.query=t;}buildQueryRequest(){return this.query}then(e,t){return this.client.genericQuery(this.query.resource,this.query.procedure,this.query.input).then(e,t)}},U=class{url;ws;store;logger;optimisticMutations;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,o;this.url=e.url,this.logger=B({level:e.logLevel??v.INFO}),this.optimisticMutations=e.optimisticMutations,this.store=new w(e.schema,e.storage,this.logger,(n,r,a)=>{var l,u;let c=new Set;if(a)for(let p of Object.values(a))for(let{mutationId:m}of p)c.add(m);(u=(l=Object.values(n))==null?void 0:l.flat())==null||u.forEach(p=>{c.has(p.id)||this.sendWsMessage(p);}),this.replayCustomMutationStack();},(n,r)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:n,itemCount:r});},n=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:n});}),this.ws=new T({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(o=e.connection)==null?void 0:o.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",n=>{this.handleServerMessage(n.data);}),this.ws.addEventListener("connectionChange",n=>{if(this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:n.open}),n.open){Array.from(this.remoteSubscriptions.values()).forEach(({query:a})=>{this.sendWsMessage({id:b(),type:"SUBSCRIBE",...a});});let r=this.store.getCustomMutationMutationIds();Object.values(this.store.optimisticMutationStack).forEach(a=>{a&&a.forEach(c=>{r.has(c.id)||(this.emitEvent({type:"MUTATION_SENT",mutationId:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure??"UNKNOWN",optimistic:true}),this.sendWsMessage(c));});}),this.replayCustomMutationStack();}});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i,s,o;try{this.logger.debug("Message received from the server:",e);let n=V.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",n),this.emitEvent({type:"MESSAGE_RECEIVED",message:n}),n.type==="MUTATE"){let{resource:r,id:a,resourceId:c,procedure:l}=n;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:a,resource:r,resourceId:c,procedure:l??"UNKNOWN"});try{this.store.addMutation(r,n);}catch(u){this.logger.error("Error merging mutation from the server:",u);}}else if(n.type==="REJECT"){if(this.replyHandlers[n.id]){clearTimeout(this.replyHandlers[n.id].timeoutHandle),this.emitUndoEvents(this.store.undoCustomMutation(n.id));let c=n.message??"Mutation rejected";(i=(t=this.replyHandlers[n.id]).reject)==null||i.call(t,new Error(c)),delete this.replyHandlers[n.id];}let r=((s=this.store.optimisticMutationStack[n.resource])==null?void 0:s.length)??0,a=(o=this.store.optimisticMutationStack[n.resource])==null?void 0:o.find(c=>c.id===n.id);this.store.undoMutation(n.resource,n.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:n.id,resource:n.resource}),a&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:n.id,resource:n.resource,resourceId:a.resourceId,pendingMutations:r-1});}else if(n.type==="REPLY"){let{id:r,data:a}=n;if(this.replyHandlers[r]){clearTimeout(this.replyHandlers[r].timeoutHandle),this.replyHandlers[r].handler(a);return}let c=F.parse(a);this.emitEvent({type:"DATA_LOAD_REPLY",resource:c.resource,itemCount:c.data.length}),this.store.loadConsolidatedState(c.resource,c.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:c.resource,itemCount:c.data.length});}}catch(n){this.logger.error("Error parsing message from the server:",n);}}load(e){let t=b(),i=f(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let s=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),s&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let o=this.remoteSubscriptions.get(i);o.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:b(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var r,a;let o={id:b(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i},n=(((r=this.store.optimisticMutationStack[e])==null?void 0:r.length)??0)+1;(a=this.store)==null||a.addMutation(e,o,true),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:o.id,resource:e,resourceId:t,procedure:i,pendingMutations:n}),this.emitEvent({type:"MUTATION_SENT",mutationId:o.id,resource:e,resourceId:t,procedure:i,optimistic:true}),this.sendWsMessage(o);}genericMutate(e,t,i){var r,a;let s=(r=this.ws)==null?void 0:r.connected(),o=(a=this.optimisticMutations)==null?void 0:a.getHandler(e,t);if(!s&&!o)throw new Error("WebSocket not connected");let n={id:b(),type:"MUTATE",resource:e,procedure:t,payload:i,meta:{timestamp:new Date().toISOString()}};if(o)try{let{proxy:c,getOperations:l}=a$1(this.store,this.store.schema);o({input:i,storage:c});let u=l(),p=this.applyOptimisticOperations(u);this.store.registerCustomMutation(n.id,p),this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:!0});}catch(c){throw this.logger.error("Error executing optimistic handler:",c),this.emitUndoEvents(this.store.undoCustomMutation(n.id)),c}else this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:false});return s?(this.sendWsMessage(n),new Promise((c,l)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],this.emitUndoEvents(this.store.undoCustomMutation(n.id)),l(new Error("Reply timeout"));},5e3),handler:u=>{delete this.replyHandlers[n.id],this.store.confirmCustomMutation(n.id),c(u);},reject:l};})):(this.store.addCustomMutationMessage(n),Promise.resolve(void 0))}applyOptimisticOperations(e){var i;let t=[];try{for(let s of e){let o=b(),n=new Date().toISOString(),r={id:o,type:"MUTATE",resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",payload:this.store.schema[s.resource].encodeMutation("set",s.data,n)},a=(((i=this.store.optimisticMutationStack[s.resource])==null?void 0:i.length)??0)+1;this.store.addMutation(s.resource,r,!0),t.push({resource:s.resource,mutationId:o}),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:o,resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",pendingMutations:a});}return t}catch(s){for(let{resource:o,mutationId:n}of t)this.store.undoMutation(o,n);throw s}}emitUndoEvents(e){var t;for(let{resource:i,mutationId:s,resourceId:o}of e){let n=((t=this.store.optimisticMutationStack[i])==null?void 0:t.length)??0;this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s,resource:i,resourceId:o,pendingMutations:n});}}genericQuery(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let s={id:b(),type:"CUSTOM_QUERY",resource:e,procedure:t,input:i};return this.sendWsMessage(s),new Promise((o,n)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],n(new Error("Reply timeout"));},5e3),handler:r=>{delete this.replyHandlers[s.id],o(r);},reject:n};})}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}replayCustomMutationStack(){var e;if((e=this.ws)!=null&&e.connected())for(let t of this.store.customMutationStack)this.sendWsMessage(t),!this.replyHandlers[t.id]&&(this.replyHandlers[t.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[t.id],this.emitUndoEvents(this.store.undoCustomMutation(t.id));},5e3),handler:()=>{delete this.replyHandlers[t.id],this.store.confirmCustomMutation(t.id);}});}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},Ze=h=>{let e=new U(h),t=(i,s)=>new Proxy(s,{get(o,n,r){if(n in o)return Reflect.get(o,n,r);if(typeof n=="string")return a=>new I(e,{resource:i,procedure:n,input:a})}});return {client:{ws:e.ws,load:i=>e.load(i),addEventListener:i=>e.addEventListener(i)},store:{query:new Proxy({},{get(i,s){if(typeof s=="string")return Object.hasOwn(h.schema,s)?t(s,a._init(h.schema[s],e)):new Proxy({},{get(o,n){if(typeof n=="string")return r=>new I(e,{resource:s,procedure:n,input:r})}})},has(i,s){return typeof s=="string"}}),mutate:d(()=>{},{apply:(i,s,o)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[n,r]=s;if(r==="insert"){let{id:a,...c}=o[0];return e.mutate(n,a,"INSERT",c)}if(r==="update"){let[a,c]=o;return e.mutate(n,a,"UPDATE",c)}return e.genericMutate(n,r,o[0])}})}}};export{Ze as createClient,Se as useLiveQuery,Ee as useLoadData};
|
package/dist/fetch-client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as ClientOptions, a as ClientRouterConstraint, b as Client } from './index-
|
|
2
|
-
import 'zod';
|
|
1
|
+
import { C as ClientOptions, a as ClientRouterConstraint, b as Client } from './index-CLkafi56.js';
|
|
3
2
|
import '@standard-schema/spec';
|
|
3
|
+
import 'zod';
|
|
4
4
|
|
|
5
5
|
type FetchClientOptions = Omit<ClientOptions, "storage"> & {
|
|
6
6
|
fetchOptions?: RequestInit;
|
package/dist/fetch-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,
|
|
1
|
+
import {d,c,a,f as f$1}from'./chunk-LSAVBBUS.js';import {stringify}from'qs';var f=async(e,c,u)=>{let s=a=>{if(!a)return {};if(a instanceof Headers){let y={};return a.forEach((l,d)=>{y[d]=l;}),y}return Array.isArray(a)?Object.fromEntries(a):a},r=s(u==null?void 0:u.headers),o=s(c==null?void 0:c.headers),i={...u,...c,headers:{...r,...o}},n=await fetch(e,i),t;try{t=await n.json();}catch{t=await n.text().catch(()=>{});}if(!n.ok)throw new Error(`Failed to fetch: ${n.status} ${n.statusText}`,{cause:t});return t},g=e=>{if(e===null)return "null";if(Array.isArray(e))return e.map(g);if(typeof e=="object"&&e!==null&&e.constructor===Object){let c={};for(let[u,s]of Object.entries(e))c[u]=g(s);return c}return e},S=e=>{let c$1={get:async s=>{let r=g(s),o=stringify(r),i=await c(e.credentials)??{},n=await f(`${e.url}/${s.resource}${o?`?${o}`:""}`,{headers:{...i,"Content-Type":"application/json"}},e.fetchOptions);return !n||typeof n!="object"?[]:Array.isArray(n)?n.map(t=>{var l,d;let a=f$1(t),y=((d=(l=t==null?void 0:t.value)==null?void 0:l.id)==null?void 0:d.value)??(t==null?void 0:t.id);return {...a,id:y}}):Object.entries(n).map(([t,a])=>({...f$1(a),id:t}))},subscribe:()=>{throw new Error("Fetch client does not support subscriptions")}},u=(s,r)=>new Proxy(r,{get(o,i,n){if(i in o)return Reflect.get(o,i,n);if(typeof i=="string")return async t=>{let a=await c(e.credentials)??{};return await f(`${e.url}/${s}/query/${i}`,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({input:t})},e.fetchOptions)}}});return {query:new Proxy({},{get(s,r){if(typeof r=="string")return Object.hasOwn(e.schema,r)?u(r,a._init(e.schema[r],c$1,true)):new Proxy({},{get(o,i){if(typeof i=="string")return async n=>{let t=await c(e.credentials)??{};return await f(`${e.url}/${r}/query/${i}`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({input:n})},e.fetchOptions)}}})},has(s,r){return typeof r=="string"}}),mutate:d(()=>{},{apply:async(s,r,o)=>{if(r.length<2)return;if(r.length>2)throw new Error("Trying to access an invalid path");let[i,n]=r,t=await c(e.credentials)??{};if(n==="insert"){let{id:a,...y}=o[0];await f(`${e.url}/${i}/insert`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({resourceId:a,payload:e.schema[i].encodeMutation("set",y,new Date().toISOString())})},e.fetchOptions);return}if(n==="update"){let[a,y]=o,{id:l,...d}=y;await f(`${e.url}/${i}/update`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({resourceId:a,payload:e.schema[i].encodeMutation("set",d,new Date().toISOString())})},e.fetchOptions);return}return await f(`${e.url}/${i}/${n}`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({payload:o[0],meta:{timestamp:new Date().toISOString()}})},e.fetchOptions)}})}};export{S as createClient};
|