@live-state/sync 0.0.4-beta.5 → 0.0.4-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var l;(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";})(l||(l={}));var u=class extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e;}};function L(t){let e=Math.floor(t()*32);return e===32&&(e=31),x.charAt(e)}function R(t){let e=w(),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 u(l.PRNGDetectFailure,"Failed to find a reliable PRNG")}function w(){return E()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function A(t,e){let n="";for(;t>0;t--)n=L(e)+n;return n}function M(t,e=10){if(isNaN(t))throw new u(l.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>0xffffffffffff)throw new u(l.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${t}`);if(t<0)throw new u(l.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===false)throw new u(l.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,i="";for(let a=e;a>0;a--)n=t%32,i=x.charAt(n)+i,t=(t-n)/32;return i}function E(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function b(t,e){let n=R(),i=Date.now();return M(i,10)+A(16,n)}var C=()=>b().toLowerCase(),j=(t,e)=>typeof t=="function"?t(e):t;var I=class t{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,n,i,a,r,s,o,T){this._collection=e,this._client=n,this._where=i??{},this._include=a??{},this._limit=r,this._single=s,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)}get(){let e=this._client.get({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort});return this._shouldAwait?Promise.resolve(e).then(n=>this._single?n[0]:n):this._single?e[0]:e}subscribe(e){return this._client.subscribe({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort},n=>{if(this._single)return e(n[0]);e(n);})}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}}static _init(e,n,i){return new t(e,n,void 0,void 0,void 0,void 0,void 0,i??false)}};var O=(t,e,n=[])=>new Proxy(t,{get:(i,a)=>{var T,y;if(a==="__isProxy__")return true;let r=(T=e.get)==null?void 0:T.call(e,i,[...n,a]);if(r!==void 0)return r;let s=i,o=a;return (y=s[o])!=null&&y.__isProxy__||(s[o]=O(typeof s[o]=="object"?s[o]:()=>{},e,[...n,a])),s[o]},apply:(i,a,r)=>{var s;return (s=e.apply)==null?void 0:s.call(e,i,n,r)}}),D=(t,e,n)=>{let i=[],a=0;for(let r=0;r<t.length&&(n===void 0||a<n);r++)e(t[r],r)&&(i.push(t[r]),a++);return i};var _=t=>{if(t)return Array.isArray(t.value)?t.value.map(e=>_(e)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([e,n])=>[e,_(n)]))};export{C as a,j as b,I as c,O as d,D as e,_ as f};
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,c,a,e,b as b$1}from'./chunk-VYWZ6RGP.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {jsx,Fragment}from'react/jsx-runtime';import {z}from'zod';import {stringify}from'qs';import pe from'fast-deep-equal';import {openDB}from'idb';var m=a=>xxHash32(JSON.stringify(a)).toString(32),b=(a,e,t=false)=>Object.entries(e).every(([i,n])=>{if(i==="$and")return n.every(r=>b(a,r,t));if(i==="$or")return n.some(r=>b(a,r,t));let s=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let r=a[i];return r===void 0?false:t?!n.$in.includes(r):n.$in.includes(r)}if(n.$not!==void 0&&!t)return b(a,{[i]:n.$not},true);if(n.$gt!==void 0){let r=a[i];return typeof r!="number"?false:t?r<=n.$gt:r>n.$gt}if(n.$gte!==void 0){let r=a[i];return typeof r!="number"?false:t?r<n.$gte:r>=n.$gte}if(n.$lt!==void 0){let r=a[i];return typeof r!="number"?false:t?r>=n.$lt:r<n.$lt}if(n.$lte!==void 0){let r=a[i];return typeof r!="number"?false:t?r>n.$lte:r<=n.$lte}return !a[i]||typeof a[i]!="object"?false:b(a[i],n,t)}return t?a[i]!==s:a[i]===s});var j=class{subscriptions=new Map;getOrStoreSubscription(e){let t=m(e);return this.subscriptions.has(t)?this.subscriptions.get(t).subscribe:(this.subscriptions.set(t,{subscribe:i=>{var s;(s=this.subscriptions.get(t))==null||s.callbacks.add(i);let n=e.subscribe(()=>{var r;(r=this.subscriptions.get(t))==null||r.callbacks.forEach(o=>{o();});});return ()=>{var r;(r=this.subscriptions.get(t))==null||r.callbacks.delete(i),setTimeout(()=>{var o;((o=this.subscriptions.get(t))==null?void 0:o.callbacks.size)===0&&(this.subscriptions.delete(t),n());},10);}},callbacks:new Set}),this.subscriptions.get(t).subscribe)}},te=new j,fe=a=>useSyncExternalStore(te.getOrStoreSubscription(a),a.get),Te=({children:a,client:e})=>(useEffect(()=>{e.subscribe();},[e.subscribe]),jsx(Fragment,{children:a}));var B=z.object({resource:z.string(),where:z.record(z.string(),z.any()).optional(),include:z.record(z.string(),z.any()).optional(),lastSyncedAt:z.string().optional(),limit:z.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),C=z.record(z.string(),z.object({value:z.string().or(z.number()).or(z.boolean()).or(z.date()).nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})).superRefine((a,e)=>{a.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),U=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),A=U.extend({procedure:z.string(),payload:z.any().optional()}),I=U.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:C});z.union([I,A]);var g=z.string(),re=z.object({id:g,type:z.literal("SUBSCRIBE"),resource:z.string()}),se=B.extend({id:g,type:z.literal("QUERY")}),H=I.extend({id:g}),ae=A.extend({id:g}),oe=z.union([ae,H]);z.union([re,se,oe]);var ce=z.object({id:g,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),le=z.object({id:g,type:z.literal("REPLY"),data:z.any()}),Q=z.union([ce,le,H]),J=z.object({resource:z.string(),data:z.record(z.string(),C)});var R=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(n=>{n(t);});}};var w=a=>{if(a)return Array.isArray(a.value)?a.value.map(e=>w(e)):typeof a.value!="object"||a.value===null||a.value instanceof Date?a.value:Object.fromEntries(Object.entries(a.value).map(([e,t])=>[e,w(t)]))};var x=class{nodes;constructor(){this.nodes=new Map;}createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let n={id:e,type:t,referencedBy:new Map(i.map(s=>[s,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,n),n}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),n=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!n)throw new Error(`Target node with id ${t} does not exist`);i.references.set(n.type,t);let s=n.referencedBy.get(i.type);s&&s instanceof Set?s.add(e):n.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 n=i.references.get(t);if(!n)return;i.references.delete(t);let s=this.nodes.get(n);if(!s)return;let r=s.referencedBy.get(i.type);r&&(r instanceof Set?r.delete(e):s.referencedBy.delete(i.type),this.notifySubscribers(n)),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,n])=>{(n instanceof Set?Array.from(n.values()):[n]).forEach(r=>{let o=this.nodes.get(r);!o||!o.references.get(i)||(o.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=>{try{i(e);}catch(n){console.error(`Error in node subscription for node ${e}:`,n);}});}getAllNodes(){return Array.from(this.nodes.values())}};var D="__meta",L="databases",O=class{db;async init(e,t){var p,d;if(typeof window>"u")return;let n=((p=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:p.version)??1,s=await m(e),r=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,h])=>[u,await m(h)]))),o=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(L)||u.createObjectStore(L);}}),c=(d=await this.getAll(o,L))==null?void 0:d[t];(c==null?void 0:c.schemaHash)!==s&&n++,this.db=await openDB(t,n,{async upgrade(u){[...Object.keys(e),D].forEach(h=>{(c==null?void 0:c.objectHashes[h])!==r[h]&&u.objectStoreNames.contains(h)&&u.deleteObjectStore(h),u.objectStoreNames.contains(h)||u.createObjectStore(h);}),await o.put(L,{schemaHash:s,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 n;return (n=this.db)==null?void 0:n.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,n]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((s,r)=>[n[r],s]))}};var E=class{constructor(e,t,i){this.schema=e;this.kvStorage=new O,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,i==null||i(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([n,s])=>{this.kvStorage.get(n).then(r=>{!r||Object.keys(r).length===0||this.loadConsolidatedState(n,r);});});}).catch(n=>{console.error("Failed to load state from storage",n);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new x;optimisticRawObjPool={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var r;let n=t??m(e$1);if(this.querySnapshots[n]&&!i){let o=this.querySnapshots[n];if(o)return o}let s=((r=e$1.where)!=null&&r.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(o=>{let c=w(this.materializeOneWithInclude(o,e$1.include));return c?[c]:[]});if(e$1.sort&&e$1.sort.length>0){let o=(c,p)=>{for(let d of e$1.sort){let u=c[d.key],h=p[d.key];if(u<h)return d.direction==="asc"?-1:1;if(u>h)return d.direction==="asc"?1:-1}return 0};s.sort(o);}if(e$1.where||e$1.limit){let o=e$1.where?c=>b(c,e$1.where):()=>true;s=e(s,o,e$1.limit);}return i||(this.querySnapshots[n]=s),s}subscribe(e,t){var r;let i=m(e),n=this.collectionSubscriptions.get(i),s=this.schema[e.resource];return n||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?Object.keys(e.include).map(o=>s.relations[o].entity.name):void 0}),(r=this.collectionSubscriptions.get(i))==null||r.callbacks.add(t),()=>{var o,c;(o=this.collectionSubscriptions.get(i))==null||o.callbacks.delete(t),((c=this.collectionSubscriptions.get(i))==null?void 0:c.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var r,o,c;let n=this.schema[e];if(console.log("Adding mutation",t),!n)throw new Error("Schema not found");let s=(r=this.optimisticRawObjPool[e])==null?void 0:r[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((c=(o=this.optimisticMutationStack)==null?void 0:o[e])==null?void 0:c.filter(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let p={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=p;let d=p.value;delete d.id,this.kvStorage.set(e,t.resourceId,d);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,s);}undoMutation(e,t){var r,o;if(!this.optimisticMutationStack[e])return;let i=(r=this.optimisticMutationStack[e])==null?void 0:r.findIndex(c=>c.id===t);if(i===-1)return;let n=this.optimisticMutationStack[e][i];console.log("Removing mutation",n);let s=(o=this.optimisticRawObjPool[e])==null?void 0:o[n.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,n.resourceId,Object.fromEntries(Object.entries(n.payload).map(([c])=>[c,{value:null,_meta:{}}])),s);}loadConsolidatedState(e,t){Object.entries(t).forEach(([i,n])=>{this.addMutation(e,{id:i,type:"MUTATE",resource:e,resourceId:i,procedure:"INSERT",payload:n});});}updateRawObjPool(e,t,i,n){var o;if(!this.schema[e])return;let s=(o=this.rawObjPool[e])==null?void 0:o[t],r=(this.optimisticMutationStack[e]??[]).reduce((c,p)=>p.resourceId!==t?c:this.schema[e].mergeMutation("set",p.payload,c)[0],s);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(c=>c.type==="many"?[c.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let c=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([p,d])=>d.type==="one"?[[d.relationalColumn,p]]:[]));Object.entries(i).forEach(([p,d])=>{let u=this.schema[e].relations[c[p]];if(!c[p])return;let h=n==null?void 0:n.value[p],[,T]=u.mergeMutation("set",d,h);if(T){if(!this.optimisticObjGraph.hasNode(T.value)){let $=u.entity.name;this.optimisticObjGraph.createNode(T.value,$,Object.values(this.schema[$].relations).flatMap(q=>q.type==="many"?[q.entity.name]:[]));}h!=null&&h.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,T.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var c;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let n=i.type,s=(c=this.optimisticRawObjPool[n])==null?void 0:c[e];if(!s)return;let[r,o]=Object.keys(t).reduce((p,d)=>{let u=this.schema[n].relations[d];return u.type==="one"?p[0].push([d,u.entity.name]):u.type==="many"&&p[1].push([d,u.entity.name]),p},[[],[]]);return {value:{...s.value,...Object.fromEntries(r.map(([p,d])=>[p,this.materializeOneWithInclude(i.references.get(d))])),...Object.fromEntries(o.map(([p,d])=>{let u=i.referencedBy.get(d),h=u instanceof Set;return [p,h?{value:Array.from(u.values()).map(T=>this.materializeOneWithInclude(T))}:this.materializeOneWithInclude(u)]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{if(t.query.resource===e||t.flatInclude&&t.flatInclude.includes(e)){let i=m(t.query),n=this.querySnapshots[i],s=this.get(t.query,void 0,true);if(pe(s,n))return;this.querySnapshots[i]=s,t.callbacks.forEach(r=>{r(s);});}});}};var W=class{url;ws;store;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){this.url=e.url,this.store=new E(e.schema,e.storage,t=>{var i,n;(n=(i=Object.values(t))==null?void 0:i.flat())==null||n.forEach(s=>{this.sendWsMessage(s);});}),this.ws=new R({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3,credentials:e.credentials}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:t.open}),t.open&&(Object.keys(this.store.schema).forEach(i=>{this.sendWsMessage({id:a(),type:"QUERY",resource:i});}),Object.entries(this.remoteSubCounters).forEach(([i,n])=>{n>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:i});}),Object.values(this.store.optimisticMutationStack).forEach(i=>{i&&i.forEach(n=>{this.sendWsMessage(n);});}));});}get(e){return this.store.get(e)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=Q.parse(JSON.parse(e));if(console.log("Parsed message:",t),this.emitEvent({type:"MESSAGE_RECEIVED",message:t}),t.type==="MUTATE"){let{resource:i}=t;try{this.store.addMutation(i,t);}catch(n){console.error("Error merging mutation from the server:",n);}}else if(t.type==="REJECT")this.store.undoMutation(t.resource,t.id);else if(t.type==="REPLY"){let{id:i,data:n}=t;if(this.replyHandlers[i]){clearTimeout(this.replyHandlers[i].timeoutHandle),this.replyHandlers[i].handler(n);return}let s=J.parse(n);this.store.loadConsolidatedState(s.resource,s.data);}}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.remoteSubCounters[e]=(this.remoteSubCounters[e]??0)+1,this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:e}),()=>{this.remoteSubCounters[e]-=1,this.remoteSubCounters[e];}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,n){var r;let s={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",n,new Date().toISOString()),resourceId:t,procedure:i};(r=this.store)==null||r.addMutation(e,s,true),this.sendWsMessage(s);}genericMutate(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let n={id:a(),type:"MUTATE",resource:e,procedure:t,payload:i};return this.sendWsMessage(n),new Promise((s,r)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],r(new Error("Reply timeout"));},5e3),handler:o=>{delete this.replyHandlers[n.id],s(o);}};})}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);});}},ot=a=>{let e=new W(a);return {client:{ws:e.ws,subscribe:t=>{let i=[];for(let n of t??Object.keys(e.store.schema))i.push(e.subscribeToRemote(n));return ()=>{console.log("Removing listeners",i),i.forEach(n=>{n();});}},addEventListener:t=>e.addEventListener(t)},store:{query:Object.entries(a.schema).reduce((t,[i,n])=>(t[i]=c._init(n,e),t),{}),mutate:d(()=>{},{apply:(t,i,n)=>{if(i.length<2)return;if(i.length>2)throw new Error("Trying to access an invalid path");let[s,r]=i;if(r==="insert"){let{id:o,...c}=n[0];return e.mutate(s,o,"INSERT",c)}if(r==="update"){let[o,c]=n;return e.mutate(s,o,"UPDATE",c)}return e.genericMutate(s,r,n[0])}})}}};export{Te as SubscriptionProvider,ot as createClient,fe as useLiveQuery};
|
|
1
|
+
import {d,c,a,f,e,b}from'./chunk-444SZWDS.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {jsx,Fragment}from'react/jsx-runtime';import {z}from'zod';import {stringify}from'qs';import se from'fast-deep-equal';import {openDB}from'idb';var y=l=>xxHash32(JSON.stringify(l)).toString(32),g=(l,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>g(l,n,t));if(i==="$or")return s.some(n=>g(l,n,t));let r=(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=l[i];return n===void 0?false:t?!s.$in.includes(n):s.$in.includes(n)}if(s.$not!==void 0&&!t)return g(l,{[i]:s.$not},true);if(s.$gt!==void 0){let n=l[i];return typeof n!="number"?false:t?n<=s.$gt:n>s.$gt}if(s.$gte!==void 0){let n=l[i];return typeof n!="number"?false:t?n<s.$gte:n>=s.$gte}if(s.$lt!==void 0){let n=l[i];return typeof n!="number"?false:t?n>=s.$lt:n<s.$lt}if(s.$lte!==void 0){let n=l[i];return typeof n!="number"?false:t?n>s.$lte:n<=s.$lte}return !l[i]||typeof l[i]!="object"?false:g(l[i],s,t)}return t?l[i]!==r:l[i]===r});var T=class{subscriptions=new Map;getOrStoreSubscription(e){let t=y(e);return this.subscriptions.has(t)?this.subscriptions.get(t).subscribe:(this.subscriptions.set(t,{subscribe:i=>{var r;(r=this.subscriptions.get(t))==null||r.callbacks.add(i);let s=e.subscribe(()=>{var n;(n=this.subscriptions.get(t))==null||n.callbacks.forEach(o=>{o();});});return ()=>{var n;(n=this.subscriptions.get(t))==null||n.callbacks.delete(i),setTimeout(()=>{var o;((o=this.subscriptions.get(t))==null?void 0:o.callbacks.size)===0&&(this.subscriptions.delete(t),s());},10);}},callbacks:new Set}),this.subscriptions.get(t).subscribe)}},N=new T,ce=l=>useSyncExternalStore(N.getOrStoreSubscription(l),l.get),le=({children:l,client:e})=>(useEffect(()=>{e.subscribe();},[e.subscribe]),jsx(Fragment,{children:l}));var $=z.object({resource:z.string(),where:z.record(z.string(),z.any()).optional(),include:z.record(z.string(),z.any()).optional(),lastSyncedAt:z.string().optional(),limit:z.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),R=z.record(z.string(),z.object({value:z.string().or(z.number()).or(z.boolean()).or(z.date()).nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})).superRefine((l,e)=>{l.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),G=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),C=G.extend({procedure:z.string(),payload:z.any().optional()}),k=G.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:R});z.union([k,C]);var v=z.string(),Y=z.object({id:v,type:z.literal("SUBSCRIBE"),resource:z.string()}),F=$.extend({id:v,type:z.literal("QUERY")}),I=k.extend({id:v}),Z=C.extend({id:v}),X=z.union([Z,I]);z.union([Y,F,X]);var ee=z.object({id:v,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),te=z.object({id:v,type:z.literal("REPLY"),data:z.any()}),H=z.union([ee,te,I]),Q=z.object({resource:z.string(),data:z.record(z.string(),R)});var S=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(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 M=class{nodes;constructor(){this.nodes=new Map;}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(r=>[r,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 r=s.referencedBy.get(i.type);r&&r instanceof Set?r.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 r=this.nodes.get(s);if(!r)return;let n=r.referencedBy.get(i.type);n&&(n instanceof Set?n.delete(e):r.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 o=this.nodes.get(n);!o||!o.references.get(i)||(o.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=>{try{i(e);}catch(s){console.error(`Error in node subscription for node ${e}:`,s);}});}getAllNodes(){return Array.from(this.nodes.values())}};var j="__meta",w="databases",E=class{db;async init(e,t){var p,d;if(typeof window>"u")return;let s=((p=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:p.version)??1,r=await y(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,f])=>[u,await y(f)]))),o=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(w)||u.createObjectStore(w);}}),a=(d=await this.getAll(o,w))==null?void 0:d[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),j].forEach(f=>{(a==null?void 0:a.objectHashes[f])!==n[f]&&u.objectStoreNames.contains(f)&&u.deleteObjectStore(f),u.objectStoreNames.contains(f)||u.createObjectStore(f);}),await o.put(w,{schemaHash:r,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(j,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(j,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((r,n)=>[s[n],r]))}};var O=class{constructor(e,t,i){this.schema=e;this.kvStorage=new E,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{this.kvStorage.getMeta("mutationStack").then(s=>{!s||Object.keys(s).length===0||(this.optimisticMutationStack=s,i==null||i(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([s,r])=>{this.kvStorage.get(s).then(n=>{!n||Object.keys(n).length===0||this.loadConsolidatedState(s,n);});});}).catch(s=>{console.error("Failed to load state from storage",s);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new M;optimisticRawObjPool={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var n;let s=t??y(e$1);if(this.querySnapshots[s]&&!i){let o=this.querySnapshots[s];if(o)return o}let r=((n=e$1.where)!=null&&n.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(o=>{let a=f(this.materializeOneWithInclude(o,e$1.include));return a?[a]:[]});if(e$1.sort&&e$1.sort.length>0){let o=(a,p)=>{for(let d of e$1.sort){let u=a[d.key],f=p[d.key];if(u<f)return d.direction==="asc"?-1:1;if(u>f)return d.direction==="asc"?1:-1}return 0};r.sort(o);}if(e$1.where||e$1.limit){let o=e$1.where?a=>g(a,e$1.where):()=>true;r=e(r,o,e$1.limit);}return i||(this.querySnapshots[s]=r),r}subscribe(e,t){var n;let i=y(e),s=this.collectionSubscriptions.get(i),r=this.schema[e.resource];return s||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?Object.keys(e.include).map(o=>r.relations[o].entity.name):void 0}),(n=this.collectionSubscriptions.get(i))==null||n.callbacks.add(t),()=>{var o,a;(o=this.collectionSubscriptions.get(i))==null||o.callbacks.delete(t),((a=this.collectionSubscriptions.get(i))==null?void 0:a.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var n,o,a;let s=this.schema[e];if(console.log("Adding mutation",t),!s)throw new Error("Schema not found");let r=(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=(o=this.optimisticMutationStack)==null?void 0:o[e])==null?void 0:a.filter(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let p={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=p;let d=p.value;delete d.id,this.kvStorage.set(e,t.resourceId,d);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,r);}undoMutation(e,t){var n,o;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];console.log("Removing mutation",s);let r=(o=this.optimisticRawObjPool[e])==null?void 0:o[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:{}}])),r);}loadConsolidatedState(e,t){Object.entries(t).forEach(([i,s])=>{this.addMutation(e,{id:i,type:"MUTATE",resource:e,resourceId:i,procedure:"INSERT",payload:s});});}updateRawObjPool(e,t,i,s){var o;if(!this.schema[e])return;let r=(o=this.rawObjPool[e])==null?void 0:o[t],n=(this.optimisticMutationStack[e]??[]).reduce((a,p)=>p.resourceId!==t?a:this.schema[e].mergeMutation("set",p.payload,a)[0],r);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(([p,d])=>d.type==="one"?[[d.relationalColumn,p]]:[]));Object.entries(i).forEach(([p,d])=>{let u=this.schema[e].relations[a[p]];if(!a[p])return;let f=s==null?void 0:s.value[p],[,m]=u.mergeMutation("set",d,f);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let L=u.entity.name;this.optimisticObjGraph.createNode(m.value,L,Object.values(this.schema[L].relations).flatMap(A=>A.type==="many"?[A.entity.name]:[]));}f!=null&&f.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,r=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!r)return;let[n,o]=Object.keys(t).reduce((p,d)=>{let u=this.schema[s].relations[d];return u.type==="one"?p[0].push([d,u.entity.name]):u.type==="many"&&p[1].push([d,u.entity.name]),p},[[],[]]);return {value:{...r.value,...Object.fromEntries(n.map(([p,d])=>[p,this.materializeOneWithInclude(i.references.get(d))])),...Object.fromEntries(o.map(([p,d])=>{let u=i.referencedBy.get(d),f=u instanceof Set;return [p,f?{value:Array.from(u.values()).map(m=>this.materializeOneWithInclude(m))}:this.materializeOneWithInclude(u)]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{if(t.query.resource===e||t.flatInclude&&t.flatInclude.includes(e)){let i=y(t.query),s=this.querySnapshots[i],r=this.get(t.query,void 0,true);if(se(r,s))return;this.querySnapshots[i]=r,t.callbacks.forEach(n=>{n(r);});}});}};var x=class{url;ws;store;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){this.url=e.url,this.store=new O(e.schema,e.storage,t=>{var i,s;(s=(i=Object.values(t))==null?void 0:i.flat())==null||s.forEach(r=>{this.sendWsMessage(r);});}),this.ws=new S({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3,credentials:e.credentials}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:t.open}),t.open&&(Object.keys(this.store.schema).forEach(i=>{this.sendWsMessage({id:a(),type:"QUERY",resource:i});}),Object.entries(this.remoteSubCounters).forEach(([i,s])=>{s>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:i});}),Object.values(this.store.optimisticMutationStack).forEach(i=>{i&&i.forEach(s=>{this.sendWsMessage(s);});}));});}get(e){return this.store.get(e)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=H.parse(JSON.parse(e));if(console.log("Parsed message:",t),this.emitEvent({type:"MESSAGE_RECEIVED",message:t}),t.type==="MUTATE"){let{resource:i}=t;try{this.store.addMutation(i,t);}catch(s){console.error("Error merging mutation from the server:",s);}}else if(t.type==="REJECT")this.store.undoMutation(t.resource,t.id);else if(t.type==="REPLY"){let{id:i,data:s}=t;if(this.replyHandlers[i]){clearTimeout(this.replyHandlers[i].timeoutHandle),this.replyHandlers[i].handler(s);return}let r=Q.parse(s);this.store.loadConsolidatedState(r.resource,r.data);}}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.remoteSubCounters[e]=(this.remoteSubCounters[e]??0)+1,this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:e}),()=>{this.remoteSubCounters[e]-=1,this.remoteSubCounters[e];}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var n;let r={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i};(n=this.store)==null||n.addMutation(e,r,true),this.sendWsMessage(r);}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.sendWsMessage(s),new Promise((r,n)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],n(new Error("Reply timeout"));},5e3),handler:o=>{delete this.replyHandlers[s.id],r(o);}};})}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);});}},Ge=l=>{let e=new x(l);return {client:{ws:e.ws,subscribe:t=>{let i=[];for(let s of t??Object.keys(e.store.schema))i.push(e.subscribeToRemote(s));return ()=>{console.log("Removing listeners",i),i.forEach(s=>{s();});}},addEventListener:t=>e.addEventListener(t)},store:{query:Object.entries(l.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[r,n]=i;if(n==="insert"){let{id:o,...a}=s[0];return e.mutate(r,o,"INSERT",a)}if(n==="update"){let[o,a]=s;return e.mutate(r,o,"UPDATE",a)}return e.genericMutate(r,n,s[0])}})}}};export{le as SubscriptionProvider,Ge as createClient,ce as useLiveQuery};
|
package/dist/fetch-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,b,c}from'./chunk-
|
|
1
|
+
import {d,b,c,f}from'./chunk-444SZWDS.js';import {stringify}from'qs';var u=async(...e)=>{let o=await fetch(...e),t;try{t=await o.json();}catch{t=await o.text().catch(()=>{});}if(!o.ok)throw new Error(`Failed to fetch: ${o.status} ${o.statusText}`,{cause:t});return t},S=e=>{let o={get:async t=>{let n=stringify(t),a=await b(e.credentials)??{},r=await u(`${e.url}/${t.resource}${n?`?${n}`:""}`,{headers:{...a,"Content-Type":"application/json"}});return !r||typeof r!="object"?[]:Object.entries(r).map(([i,s])=>({...f(s),id:i}))},subscribe:()=>{throw new Error("Fetch client does not support subscriptions")}};return {query:Object.entries(e.schema).reduce((t,[n,a])=>(t[n]=c._init(a,o,true),t),{}),mutate:d(()=>{},{apply:async(t,n,a)=>{if(n.length<2)return;if(n.length>2)throw new Error("Trying to access an invalid path");let[r,i]=n,s=await b(e.credentials)??{};if(i==="insert"){let{id:c,...y}=a[0];await u(`${e.url}/${r}/insert`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({resourceId:c,payload:e.schema[r].encodeMutation("set",y,new Date().toISOString())})});return}if(i==="update"){let[c,y]=a,{id:O,...m}=y;await u(`${e.url}/${r}/update`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({resourceId:c,payload:e.schema[r].encodeMutation("set",m,new Date().toISOString())})});return}await u(`${e.url}/${r}/${i}`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({payload:a[0]})});}})}};export{S as createClient};
|