@live-state/sync 0.0.4-beta.9 → 0.0.6-canary-1
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-NJ7LXJAY.js +1 -0
- package/dist/{chunk-WZ7JXHZL.js → chunk-RCXJM33Z.js} +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +6 -3
- package/dist/fetch-client.js +1 -1
- package/dist/index-BtsKDfTE.d.cts +282 -0
- package/dist/index-BtsKDfTE.d.ts +282 -0
- package/dist/{index-BgowrRDR.d.ts → index-D8jFoiy6.d.ts} +14 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -244
- package/dist/index.d.ts +1 -244
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +4 -5
- package/dist/server.d.ts +4 -5
- package/dist/server.js +2 -2
- package/package.json +4 -1
- package/dist/chunk-XNKBHWSC.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import'js-xxhash';var O=Object.create;var I=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty;var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var S=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of A(e))!M.call(t,a)&&a!==n&&I(t,a,{get:()=>e[a],enumerable:!(i=K(e,a))||i.enumerable});return t};var V=(t,e,n)=>(n=t!=null?O(j(t)):{},S(e||!t||!t.__esModule?I(n,"default",{value:t,enumerable:true}):n,t));var o=class{_value;_meta;_encodeInput;_decodeInput};var m=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,n,i){return this.inner.encodeMutation(e,n,i)}mergeMutation(e,n,i){return this.inner.mergeMutation(e,n,i)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},y=class t extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,n,i,a,s,l,r){super(),this.storageType=e,this.convertFunc=n,this.isIndex=i??false,this.isUnique=a??false,this.defaultValue=s,this.foreignReference=l,this.isPrimary=r??false;}encodeMutation(e,n,i){return {value:n,_meta:{timestamp:i}}}mergeMutation(e,n,i){return i&&i._meta.timestamp&&n._meta.timestamp&&i._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[i,null]:[{value:this.convertFunc?this.convertFunc(n.value):n.value,_meta:n._meta},n]}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,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new t(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,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,this.defaultValue,this.foreignReference,true)}nullable(){return new m(this)}},v=class t extends y{constructor(){super("integer",e=>Number(e));}static create(){return new t}},F=v.create,p=class t extends y{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)}},q=p.create,N=p.createId,D=p.createReference,L=class t extends y{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},W=L.create,h=class t extends y{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},P=h.create;var g=class t extends o{name;fields;relations;constructor(e,n,i){super(),this.name=e,this.fields=n,this.relations=i??{};}encodeMutation(e,n,i){return Object.fromEntries(Object.entries(n).map(([a,s])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",s,i)]))}mergeMutation(e,n,i){let a={};return [{value:{...(i==null?void 0:i.value)??{},...Object.fromEntries(Object.entries(n).map(([s,l])=>{let r=this.fields[s]??this.relations[s];if(!r)return [s,l];let[u,d]=r.mergeMutation(e,l,i==null?void 0:i.value[s]);return d&&(a[s]=d),[s,u]}))}},a]}setRelations(e){return new t(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,n){return new t(e,n)}},z=g.create,f=class t extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,n,i,a,s){super(),this.entity=e,this.type=n,this.required=s??false,this.relationalColumn=i,this.foreignColumn=a;}encodeMutation(e,n,i){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:n,_meta:{timestamp:i}}}mergeMutation(e,n,i){if(this.type==="many")throw new Error("Many not implemented.");return i&&i._meta.timestamp&&n._meta.timestamp&&i._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[i,null]:[n,n]}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,n,i)=>new t(e,"one",n,void 0,i??false)}static createManyFactory(){return (e,n,i)=>new t(e,"many",void 0,n,i??false)}},G=(t,e)=>({$type:"relations",objectName:t.name,relations:e({one:f.createOneFactory(),many:f.createManyFactory()})}),x=t=>t?Array.isArray(t.value)?t.value.map(n=>x(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(a=>x(a))]:[n,x(i)])):void 0,H=t=>Object.fromEntries(Object.entries(t).flatMap(([e,n])=>{if(n.$type==="relations")return [];let i=n,a=Object.values(t).find(s=>s.$type==="relations"&&s.objectName===n.name);return a&&(i=i.setRelations(a.relations)),[[i.name,i]]}));var w=(t,e,n)=>{let i={},a=n[e];if(!a)return i;let s=l=>{l.$and?l.$and.forEach(s):l.$or?l.$or.forEach(s):Object.entries(l).forEach(([r,u])=>{var d;if((d=a.relations)!=null&&d[r]&&(i[r]=true,typeof u=="object"&&u!==null&&!Array.isArray(u))){let b=w(u,a.relations[r].entity.name,n);Object.keys(b).length>0&&(i[r]=b);}});};return s(t),i},c=(t,e,n=false)=>Object.entries(e).every(([i,a])=>{if(i==="$and")return a.every(l=>c(t,l,n));if(i==="$or")return a.some(l=>c(t,l,n));let s=(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 r=t[i];return r===void 0?false:n?!a.$in.includes(r):a.$in.includes(r)}if(a.$not!==void 0&&!n)return c(t,{[i]:a.$not},true);if(a.$gt!==void 0){let r=t[i];return typeof r!="number"?false:n?r<=a.$gt:r>a.$gt}if(a.$gte!==void 0){let r=t[i];return typeof r!="number"?false:n?r<a.$gte:r>=a.$gte}if(a.$lt!==void 0){let r=t[i];return typeof r!="number"?false:n?r>=a.$lt:r<a.$lt}if(a.$lte!==void 0){let r=t[i];return typeof r!="number"?false:n?r>a.$lte:r<=a.$lte}let l=t[i];return !l||typeof l!="object"&&!Array.isArray(l)?false:Array.isArray(l)?n?!l.some(r=>c(r,a,false)):l.some(r=>c(r,a,false)):c(l,a,n)}return n?t[i]!==s:t[i]===s}),T={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},R=class{level;prefix;constructor(e={}){this.level=e.level??T.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=T.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=T.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=T.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=T.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=T.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},Z=t=>new R(t);export{C as a,V as b,o as c,m as d,y as e,v as f,F as g,p as h,q as i,N as j,D as k,L as l,W as m,h as n,P as o,g as p,z as q,f as r,G as s,x as t,H as u,w as v,c as w,T as x,Z as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b="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 _(t){let e=Math.floor(t()*32);return e===32&&(e=31),b.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=_(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 r=e;r>0;r--)n=t%32,i=b.charAt(n)+i,t=(t-n)/32;return i}function E(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function I(t,e){let n=R(),i=Date.now();return M(i,10)+A(16,n)}var N=()=>I().toLowerCase(),j=(t,e)=>typeof t=="function"?t(e):t;var L=class t{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,n,i,r,a,s,o,d){this._collection=e,this._client=n,this._where=i??{},this._include=r??{},this._limit=a,this._single=s,this._sort=o,this._shouldAwait=d,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,r)=>{var d,y;if(r==="__isProxy__")return true;let a=(d=e.get)==null?void 0:d.call(e,i,[...n,r]);if(a!==void 0)return a;let s=i,o=r;return (y=s[o])!=null&&y.__isProxy__||(s[o]=O(typeof s[o]=="object"?s[o]:()=>{},e,[...n,r])),s[o]},apply:(i,r,a)=>{var s;return (s=e.apply)==null?void 0:s.call(e,i,n,a)}}),D=(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 g=t=>t?Array.isArray(t.value)?t.value.map(n=>g(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=>g(r))]:[n,g(i)])):void 0;export{N as a,j as b,L as c,O as d,D as e,g as f};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as Client, c as ClientEvents, C as ClientOptions, b as ConnectionStateChangeEvent, M as MessageReceivedEvent, S as SubscriptionProvider, e as createClient, u as useLiveQuery } from './index-
|
|
1
|
+
export { d as Client, c as ClientEvents, C as ClientOptions, b as ConnectionStateChangeEvent, M as MessageReceivedEvent, S as SubscriptionProvider, e as createClient, u as useLiveQuery } from './index-D8jFoiy6.js';
|
|
2
2
|
import 'react/jsx-runtime';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'zod/v3';
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,c,a,f,e,b}from'./chunk-WZ7JXHZL.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 ne from'fast-deep-equal';import {openDB}from'idb';var y=u=>xxHash32(JSON.stringify(u)).toString(32),g=(u,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>g(u,n,t));if(i==="$or")return s.some(n=>g(u,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=u[i];return n===void 0?false:t?!s.$in.includes(n):s.$in.includes(n)}if(s.$not!==void 0&&!t)return g(u,{[i]:s.$not},true);if(s.$gt!==void 0){let n=u[i];return typeof n!="number"?false:t?n<=s.$gt:n>s.$gt}if(s.$gte!==void 0){let n=u[i];return typeof n!="number"?false:t?n<s.$gte:n>=s.$gte}if(s.$lt!==void 0){let n=u[i];return typeof n!="number"?false:t?n>=s.$lt:n<s.$lt}if(s.$lte!==void 0){let n=u[i];return typeof n!="number"?false:t?n>s.$lte:n<=s.$lte}return !u[i]||typeof u[i]!="object"?false:g(u[i],s,t)}return t?u[i]!==r:u[i]===r});var R=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 R,le=u=>useSyncExternalStore(N.getOrStoreSubscription(u),u.get),ue=({children:u,client:e})=>(useEffect(()=>{e.subscribe();},[e.subscribe]),jsx(Fragment,{children:u}));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.coerce.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()})),Y=C.superRefine((u,e)=>{u.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()}),j=G.extend({procedure:z.string(),payload:z.any().optional()}),k=G.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:Y});z.union([k,j]);var v=z.string(),F=z.object({id:v,type:z.literal("SUBSCRIBE"),resource:z.string()}),Z=$.extend({id:v,type:z.literal("QUERY")}),I=k.extend({id:v}),X=j.extend({id:v}),ee=z.union([X,I]);z.union([F,Z,ee]);var te=z.object({id:v,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),ie=z.object({id:v,type:z.literal("REPLY"),data:z.any()}),H=z.union([te,ie,I]),Q=z.object({resource:z.string(),data:z.record(z.string(),C)});var M=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 w=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 A="__meta",E="databases",O=class{db;async init(e,t){var p,h;if(typeof window>"u")return;let s=((p=(await window.indexedDB.databases()).find(c=>c.name===t))==null?void 0:p.version)??1,r=await y(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,d])=>[c,await y(d)]))),o=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(E)||c.createObjectStore(E);}}),a=(h=await this.getAll(o,E))==null?void 0:h[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(c){[...Object.keys(e),A].forEach(d=>{(a==null?void 0:a.objectHashes[d])!==n[d]&&c.objectStoreNames.contains(d)&&c.deleteObjectStore(d),c.objectStoreNames.contains(d)||c.createObjectStore(d);}),await o.put(E,{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(A,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(A,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 T=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(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 w;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 h of e$1.sort){let c=a[h.key],d=p[h.key];if(c<d)return h.direction==="asc"?-1:1;if(c>d)return h.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 r;let i=y(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}),(r=this.collectionSubscriptions.get(i))==null||r.callbacks.add(t),()=>{var n,o;(n=this.collectionSubscriptions.get(i))==null||n.callbacks.delete(t),((o=this.collectionSubscriptions.get(i))==null?void 0:o.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(c=>c.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 h=p.value;delete h.id,this.kvStorage.set(e,t.resourceId,h);}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,h])=>h.type==="one"?[[h.relationalColumn,p]]:[]));Object.entries(i).forEach(([p,h])=>{let c=this.schema[e].relations[a[p]];if(!a[p])return;let d=s==null?void 0:s.value[p],[,m]=c.mergeMutation("set",h,d);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let S=c.entity.name;this.optimisticObjGraph.createNode(m.value,S,Object.values(this.schema[S].relations).flatMap(x=>x.type==="many"?[x.entity.name]:[]));}d!=null&&d.value&&this.optimisticObjGraph.removeLink(t,c.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.entries(t).reduce((p,[h,c])=>{let d=this.schema[s].relations[h];return d&&(d.type==="one"?p[0].push([h,d.entity.name,c??true]):d.type==="many"&&p[1].push([h,d.entity.name,c??true])),p},[[],[]]);return {value:{...r.value,...Object.fromEntries(n.map(([p,h,c])=>[p,this.materializeOneWithInclude(i.references.get(h),typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(o.map(([p,h,c])=>{let d=i.referencedBy.get(h),m=d instanceof Set;return [p,m?{value:Array.from(d.values()).map(S=>this.materializeOneWithInclude(S,typeof c=="object"&&c!==null?c:{}))}:this.materializeOneWithInclude(d,typeof c=="object"&&c!==null?c:{})]}))}}}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(ne(r,s))return;this.querySnapshots[i]=r,t.callbacks.forEach(n=>{n(r);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,r])=>{var a;let n=(a=this.schema[t])==null?void 0:a.relations[s];if(!n)return;let o=n.entity.name;i.push(o),typeof r=="object"&&r!==null&&i.push(...this.flattenIncludes(r,o));}),Array.from(new Set(i))}};var L=class{url;ws;store;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,r;this.url=e.url,this.store=new T(e.schema,e.storage,n=>{var o,a;(a=(o=Object.values(n))==null?void 0:o.flat())==null||a.forEach(p=>{this.sendWsMessage(p);});}),this.ws=new M({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:(r=e.connection)==null?void 0:r.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",n=>{this.handleServerMessage(n.data);}),this.ws.addEventListener("connectionChange",n=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:n.open}),n.open&&(Object.keys(this.store.schema).forEach(o=>{this.sendWsMessage({id:a(),type:"QUERY",resource:o});}),Object.entries(this.remoteSubCounters).forEach(([o,a$1])=>{a$1>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:o});}),Object.values(this.store.optimisticMutationStack).forEach(o=>{o&&o.forEach(a=>{this.sendWsMessage(a);});}));});}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);});}},Ie=u=>{let e=new L(u);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(u.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{ue as SubscriptionProvider,Ie as createClient,le as useLiveQuery};
|
|
1
|
+
import {d,c,a,f,e,b}from'./chunk-RCXJM33Z.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 ae from'fast-deep-equal';import {openDB}from'idb';var g=l=>xxHash32(JSON.stringify(l)).toString(32);var m=(l,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(o=>m(l,o,t));if(i==="$or")return s.some(o=>m(l,o,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 m(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}let o=l[i];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?t?!o.some(n=>m(n,s,false)):o.some(n=>m(n,s,false)):m(o,s,t)}return t?l[i]!==r:l[i]===r}),y={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},C=class{level;prefix;constructor(e={}){this.level=e.level??y.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=y.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=y.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=y.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=y.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=y.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},T=l=>new C(l);var j=class{subscriptions=new Map;getOrStoreSubscription(e){let t=g(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 o;(o=this.subscriptions.get(t))==null||o.callbacks.forEach(n=>{n();});});return ()=>{var o;(o=this.subscriptions.get(t))==null||o.callbacks.delete(i),setTimeout(()=>{var n;((n=this.subscriptions.get(t))==null?void 0:n.callbacks.size)===0&&(this.subscriptions.delete(t),s());},10);}},callbacks:new Set}),this.subscriptions.get(t).subscribe)}},J=new j,de=l=>useSyncExternalStore(J.getOrStoreSubscription(l),l.get),he=({children:l,client:e})=>(useEffect(()=>{e.subscribe();},[e.subscribe]),jsx(Fragment,{children:l}));var N=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.coerce.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),x=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()})),X=x.superRefine((l,e)=>{l.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()}),k=U.extend({procedure:z.string(),payload:z.any().optional()}),A=U.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:X});z.union([A,k]);var S=z.string(),ee=z.object({id:S,type:z.literal("SUBSCRIBE"),resource:z.string()}),te=N.extend({id:S,type:z.literal("QUERY")}),H=A.extend({id:S}),ie=k.extend({id:S}),se=z.union([ie,H]);z.union([ee,te,se]);var ne=z.object({id:S,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),re=z.object({id:S,type:z.literal("REPLY"),data:z.any()}),Q=z.union([ne,re,H]),K=z.object({resource:z.string(),data:z.record(z.string(),x)});var E=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 w=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(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 o=r.referencedBy.get(i.type);o&&(o instanceof Set?o.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(o=>{let n=this.nodes.get(o);!n||!n.references.get(i)||(n.references.delete(i),this.notifySubscribers(o));});}),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(r){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,r);}});}getAllNodes(){return Array.from(this.nodes.values())}};var W="__meta",O="databases",R=class{db;async init(e,t){var p,h;if(typeof window>"u")return;let s=((p=(await window.indexedDB.databases()).find(c=>c.name===t))==null?void 0:p.version)??1,r=await g(e),o=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,d])=>[c,await g(d)]))),n=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(O)||c.createObjectStore(O);}}),a=(h=await this.getAll(n,O))==null?void 0:h[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(c){[...Object.keys(e),W].forEach(d=>{(a==null?void 0:a.objectHashes[d])!==o[d]&&c.objectStoreNames.contains(d)&&c.deleteObjectStore(d),c.objectStoreNames.contains(d)||c.createObjectStore(d);}),await n.put(O,{schemaHash:r,objectHashes:o},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(W,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(W,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,o)=>[s[o],r]))}};var L=class{constructor(e,t,i,s){this.schema=e;this.logger=i,this.optimisticObjGraph=new w(i),this.kvStorage=new R,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{this.kvStorage.getMeta("mutationStack").then(r=>{!r||Object.keys(r).length===0||(this.optimisticMutationStack=r,s==null||s(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([r,o])=>{this.kvStorage.get(r).then(n=>{!n||Object.keys(n).length===0||this.loadConsolidatedState(r,n);});});}).catch(r=>{i.debug("Storage initialization failed (may not be available in this environment):",r);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph;optimisticRawObjPool={};logger;collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var o;let s=t??g(e$1);if(this.querySnapshots[s]&&!i){let n=this.querySnapshots[s];if(n)return n}let r=((o=e$1.where)!=null&&o.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(n=>{let a=f(this.materializeOneWithInclude(n,e$1.include));return a?[a]:[]});if(e$1.sort&&e$1.sort.length>0){let n=(a,p)=>{for(let h of e$1.sort){let c=a[h.key],d=p[h.key];if(c<d)return h.direction==="asc"?-1:1;if(c>d)return h.direction==="asc"?1:-1}return 0};r.sort(n);}if(e$1.where||e$1.limit){let n=e$1.where?a=>m(a,e$1.where):()=>true;r=e(r,n,e$1.limit);}return i||(this.querySnapshots[s]=r),r}subscribe(e,t){var r;let i=g(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}),(r=this.collectionSubscriptions.get(i))==null||r.callbacks.add(t),()=>{var o,n;(o=this.collectionSubscriptions.get(i))==null||o.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 o,n,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let r=(o=this.optimisticRawObjPool[e])==null?void 0:o[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(c=>c.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 h=p.value;delete h.id,this.kvStorage.set(e,t.resourceId,h);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,r);}undoMutation(e,t){var o,n;if(!this.optimisticMutationStack[e])return;let i=(o=this.optimisticMutationStack[e])==null?void 0:o.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let r=(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:{}}])),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 n;if(!this.schema[e])return;let r=(n=this.rawObjPool[e])==null?void 0:n[t],o=(this.optimisticMutationStack[e]??[]).reduce((a,p)=>p.resourceId!==t?a:this.schema[e].mergeMutation("set",p.payload,a)[0],r);if(this.optimisticRawObjPool[e]??={},o?this.optimisticRawObjPool[e][t]={value:{...o.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!o)){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,h])=>h.type==="one"?[[h.relationalColumn,p]]:[]));Object.entries(i).forEach(([p,h])=>{let c=this.schema[e].relations[a[p]];if(!a[p])return;let d=s==null?void 0:s.value[p],[,b]=c.mergeMutation("set",h,d);if(b){if(!this.optimisticObjGraph.hasNode(b.value)){let M=c.entity.name;this.optimisticObjGraph.createNode(b.value,M,Object.values(this.schema[M].relations).flatMap(I=>I.type==="many"?[I.entity.name]:[]));}d!=null&&d.value&&this.optimisticObjGraph.removeLink(t,c.entity.name),this.optimisticObjGraph.createLink(t,b.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[o,n]=Object.entries(t).reduce((p,[h,c])=>{let d=this.schema[s].relations[h];return d&&(d.type==="one"?p[0].push([h,d.entity.name,c??true]):d.type==="many"&&p[1].push([h,d.entity.name,c??true])),p},[[],[]]);return {value:{...r.value,...Object.fromEntries(o.map(([p,h,c])=>[p,this.materializeOneWithInclude(i.references.get(h),typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(n.map(([p,h,c])=>{let d=i.referencedBy.get(h),b=d instanceof Set;return [p,b?{value:Array.from(d.values()).map(M=>this.materializeOneWithInclude(M,typeof c=="object"&&c!==null?c:{}))}:this.materializeOneWithInclude(d,typeof c=="object"&&c!==null?c:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{if(t.query.resource===e||t.flatInclude&&t.flatInclude.includes(e)){let i=g(t.query),s=this.querySnapshots[i],r=this.get(t.query,void 0,true);if(ae(r,s))return;this.querySnapshots[i]=r,t.callbacks.forEach(o=>{o(r);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,r])=>{var a;let o=(a=this.schema[t])==null?void 0:a.relations[s];if(!o)return;let n=o.entity.name;i.push(n),typeof r=="object"&&r!==null&&i.push(...this.flattenIncludes(r,n));}),Array.from(new Set(i))}};var P=class{url;ws;store;logger;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,r;this.url=e.url,this.logger=T({level:e.logLevel??y.INFO}),this.store=new L(e.schema,e.storage,this.logger,o=>{var n,a;(a=(n=Object.values(o))==null?void 0:n.flat())==null||a.forEach(p=>{this.sendWsMessage(p);});}),this.ws=new E({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:(r=e.connection)==null?void 0:r.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",o=>{this.handleServerMessage(o.data);}),this.ws.addEventListener("connectionChange",o=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:o.open}),o.open&&(Object.keys(this.store.schema).forEach(n=>{this.sendWsMessage({id:a(),type:"QUERY",resource:n});}),Object.entries(this.remoteSubCounters).forEach(([n,a$1])=>{a$1>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:n});}),Object.values(this.store.optimisticMutationStack).forEach(n=>{n&&n.forEach(a=>{this.sendWsMessage(a);});}));});}get(e){return this.store.get(e)}handleServerMessage(e){try{this.logger.debug("Message received from the server:",e);let t=Q.parse(JSON.parse(e));if(this.logger.debug("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){this.logger.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=K.parse(s);this.store.loadConsolidatedState(r.resource,r.data);}}catch(t){this.logger.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 o;let r={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i};(o=this.store)==null||o.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,o)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],o(new Error("Reply timeout"));},5e3),handler:n=>{delete this.replyHandlers[s.id],r(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);});}},Qe=l=>{let e=new P(l),t=T({level:l.logLevel??y.INFO,prefix:"Client"});return {client:{ws:e.ws,subscribe:i=>{let s=[];for(let r of i??Object.keys(e.store.schema))s.push(e.subscribeToRemote(r));return ()=>{t.debug("Removing listeners",s),s.forEach(r=>{r();});}},addEventListener:i=>e.addEventListener(i)},store:{query:Object.entries(l.schema).reduce((i,[s,r])=>(i[s]=c._init(r,e),i),{}),mutate:d(()=>{},{apply:(i,s,r)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[o,n]=s;if(n==="insert"){let{id:a,...p}=r[0];return e.mutate(o,a,"INSERT",p)}if(n==="update"){let[a,p]=r;return e.mutate(o,a,"UPDATE",p)}return e.genericMutate(o,n,r[0])}})}}};export{he as SubscriptionProvider,Qe as createClient,de as useLiveQuery};
|
package/dist/fetch-client.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as ClientOptions, A as AnyRouter, a as Client } from './index-D8jFoiy6.js';
|
|
2
2
|
import 'react/jsx-runtime';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'zod/v3';
|
|
5
5
|
import 'zod/v4/core';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
type FetchClientOptions = Omit<ClientOptions, "storage"> & {
|
|
8
|
+
fetchOptions?: RequestInit;
|
|
9
|
+
};
|
|
10
|
+
declare const createClient: <TRouter extends AnyRouter>(opts: FetchClientOptions) => Client<TRouter, true>;
|
|
8
11
|
|
|
9
|
-
export { createClient };
|
|
12
|
+
export { type FetchClientOptions, createClient };
|
package/dist/fetch-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,b,c,f}from'./chunk-
|
|
1
|
+
import {d as d$1,b,c,f}from'./chunk-RCXJM33Z.js';import {stringify}from'qs';var d=async(e,u,t)=>{let r=o=>{if(!o)return {};if(o instanceof Headers){let y={};return o.forEach((f,O)=>{y[O]=f;}),y}return Array.isArray(o)?Object.fromEntries(o):o},a=r(t==null?void 0:t.headers),n=r(u==null?void 0:u.headers),c={...t,...u,headers:{...a,...n}},i=await fetch(e,c),s;try{s=await i.json();}catch{s=await i.text().catch(()=>{});}if(!i.ok)throw new Error(`Failed to fetch: ${i.status} ${i.statusText}`,{cause:s});return s},$=e=>{let u={get:async t=>{let r=stringify(t),a=await b(e.credentials)??{},n=await d(`${e.url}/${t.resource}${r?`?${r}`:""}`,{headers:{...a,"Content-Type":"application/json"}},e.fetchOptions);return !n||typeof n!="object"?[]:Object.entries(n).map(([c,i])=>({...f(i),id:c}))},subscribe:()=>{throw new Error("Fetch client does not support subscriptions")}};return {query:Object.entries(e.schema).reduce((t,[r,a])=>(t[r]=c._init(a,u,true),t),{}),mutate:d$1(()=>{},{apply:async(t,r,a)=>{if(r.length<2)return;if(r.length>2)throw new Error("Trying to access an invalid path");let[n,c]=r,i=await b(e.credentials)??{};if(c==="insert"){let{id:s,...o}=a[0];await d(`${e.url}/${n}/insert`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify({resourceId:s,payload:e.schema[n].encodeMutation("set",o,new Date().toISOString())})},e.fetchOptions);return}if(c==="update"){let[s,o]=a,{id:y,...f}=o;await d(`${e.url}/${n}/update`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify({resourceId:s,payload:e.schema[n].encodeMutation("set",f,new Date().toISOString())})},e.fetchOptions);return}await d(`${e.url}/${n}/${c}`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify({payload:a[0]})},e.fetchOptions);}})}};export{$ as createClient};
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
type LiveTypeMeta = {};
|
|
2
|
+
type MutationType = "set";
|
|
3
|
+
type StorageFieldType = {
|
|
4
|
+
type: string;
|
|
5
|
+
nullable: boolean;
|
|
6
|
+
default?: any;
|
|
7
|
+
unique?: boolean;
|
|
8
|
+
index?: boolean;
|
|
9
|
+
primary?: boolean;
|
|
10
|
+
references?: string;
|
|
11
|
+
};
|
|
12
|
+
declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTypeMeta, EncodeInput = Partial<Value> | Value, DecodeInput = {
|
|
13
|
+
value: Value;
|
|
14
|
+
_meta: keyof Meta extends never ? never : Meta;
|
|
15
|
+
}> {
|
|
16
|
+
readonly _value: Value;
|
|
17
|
+
readonly _meta: Meta;
|
|
18
|
+
readonly _encodeInput: EncodeInput;
|
|
19
|
+
readonly _decodeInput: DecodeInput;
|
|
20
|
+
abstract encodeMutation(mutationType: MutationType, input: EncodeInput, timestamp: string): DecodeInput;
|
|
21
|
+
/**
|
|
22
|
+
* Merges the materialized shape with the encoded mutation
|
|
23
|
+
* @param mutationType The type of mutation
|
|
24
|
+
* @param encodedMutation The encoded mutation
|
|
25
|
+
* @param materializedShape The materialized shape
|
|
26
|
+
* @returns A tuple of the new materialized shape and the accepted diff
|
|
27
|
+
*/
|
|
28
|
+
abstract mergeMutation(mutationType: MutationType, encodedMutation: DecodeInput, materializedShape?: MaterializedLiveType<LiveType<Value, Meta>>): [MaterializedLiveType<LiveType<Value, Meta>>, DecodeInput | null];
|
|
29
|
+
abstract getStorageFieldType(): StorageFieldType;
|
|
30
|
+
}
|
|
31
|
+
type LiveTypeAny = LiveType<any, LiveTypeMeta, any, any>;
|
|
32
|
+
type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
33
|
+
[K in keyof T["_value"]]: InferLiveType<T["_value"][K]>;
|
|
34
|
+
} : T["_value"];
|
|
35
|
+
type InferIndex<T extends LiveTypeAny> = string;
|
|
36
|
+
|
|
37
|
+
declare class NullableLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | null, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
|
|
38
|
+
readonly inner: T;
|
|
39
|
+
constructor(inner: T);
|
|
40
|
+
encodeMutation(mutationType: MutationType, input: T["_value"] | null, timestamp: string): T["_decodeInput"];
|
|
41
|
+
mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>> | undefined): [
|
|
42
|
+
MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>>,
|
|
43
|
+
T["_decodeInput"] | null
|
|
44
|
+
];
|
|
45
|
+
getStorageFieldType(): StorageFieldType;
|
|
46
|
+
}
|
|
47
|
+
type LiveAtomicTypeMeta = {
|
|
48
|
+
timestamp: string | null;
|
|
49
|
+
} & LiveTypeMeta;
|
|
50
|
+
declare class LiveAtomicType<Value, DefaultValue = undefined> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
|
|
51
|
+
value: Value;
|
|
52
|
+
_meta: LiveAtomicTypeMeta;
|
|
53
|
+
}> {
|
|
54
|
+
readonly storageType: string;
|
|
55
|
+
readonly convertFunc?: (value: any) => Value;
|
|
56
|
+
readonly isIndex: boolean;
|
|
57
|
+
readonly isUnique: boolean;
|
|
58
|
+
readonly defaultValue: DefaultValue;
|
|
59
|
+
readonly foreignReference?: string;
|
|
60
|
+
readonly isPrimary: boolean;
|
|
61
|
+
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: DefaultValue, references?: string, primary?: boolean);
|
|
62
|
+
encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
|
|
63
|
+
value: Value;
|
|
64
|
+
_meta: LiveAtomicTypeMeta;
|
|
65
|
+
};
|
|
66
|
+
mergeMutation(mutationType: MutationType, encodedMutation: {
|
|
67
|
+
value: Value;
|
|
68
|
+
_meta: LiveAtomicTypeMeta;
|
|
69
|
+
}, materializedShape?: MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
|
|
70
|
+
value: Value;
|
|
71
|
+
_meta: LiveAtomicTypeMeta;
|
|
72
|
+
}>>): [
|
|
73
|
+
MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
|
|
74
|
+
value: Value;
|
|
75
|
+
_meta: LiveAtomicTypeMeta;
|
|
76
|
+
}>>,
|
|
77
|
+
{
|
|
78
|
+
value: Value;
|
|
79
|
+
_meta: LiveAtomicTypeMeta;
|
|
80
|
+
} | null
|
|
81
|
+
];
|
|
82
|
+
getStorageFieldType(): StorageFieldType;
|
|
83
|
+
unique(): LiveAtomicType<Value, undefined>;
|
|
84
|
+
index(): LiveAtomicType<Value, undefined>;
|
|
85
|
+
default(value: Value): LiveAtomicType<Value, Value>;
|
|
86
|
+
primary(): LiveAtomicType<Value, undefined>;
|
|
87
|
+
nullable(): NullableLiveType<this>;
|
|
88
|
+
}
|
|
89
|
+
declare class LiveNumber extends LiveAtomicType<number> {
|
|
90
|
+
private constructor();
|
|
91
|
+
static create(): LiveNumber;
|
|
92
|
+
}
|
|
93
|
+
declare const number: typeof LiveNumber.create;
|
|
94
|
+
declare class LiveString extends LiveAtomicType<string> {
|
|
95
|
+
private constructor();
|
|
96
|
+
static create(): LiveString;
|
|
97
|
+
static createId(): LiveAtomicType<string, undefined>;
|
|
98
|
+
static createReference(foreignField: `${string}.${string}`): LiveString;
|
|
99
|
+
}
|
|
100
|
+
declare const string: typeof LiveString.create;
|
|
101
|
+
declare const id: typeof LiveString.createId;
|
|
102
|
+
declare const reference: typeof LiveString.createReference;
|
|
103
|
+
declare class LiveBoolean extends LiveAtomicType<boolean> {
|
|
104
|
+
private constructor();
|
|
105
|
+
static create(): LiveBoolean;
|
|
106
|
+
}
|
|
107
|
+
declare const boolean: typeof LiveBoolean.create;
|
|
108
|
+
declare class LiveTimestamp extends LiveAtomicType<Date> {
|
|
109
|
+
private constructor();
|
|
110
|
+
static create(): LiveTimestamp;
|
|
111
|
+
}
|
|
112
|
+
declare const timestamp: typeof LiveTimestamp.create;
|
|
113
|
+
|
|
114
|
+
/** biome-ignore-all lint/complexity/noBannedTypes: false positive */
|
|
115
|
+
|
|
116
|
+
type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
117
|
+
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
118
|
+
};
|
|
119
|
+
type InferLiveObject<T extends LiveObjectAny, Include extends IncludeClause<T> | undefined = undefined> = InferLiveObjectWithoutRelations<T> & (Include extends IncludeClause<T> ? {
|
|
120
|
+
[K in keyof T["relations"] as Include[K] extends true | IncludeClause<T["relations"][K]["entity"]> ? K : never]: Include[K] extends true ? T["relations"][K]["type"] extends "one" ? T["fields"][Exclude<T["relations"][K]["relationalColumn"], undefined>] extends NullableLiveType<any> ? InferLiveObject<T["relations"][K]["entity"]> | null : InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[] : Include[K] extends IncludeClause<T["relations"][K]["entity"]> ? T["relations"][K]["type"] extends "one" ? T["fields"][Exclude<T["relations"][K]["relationalColumn"], undefined>] extends NullableLiveType<any> ? InferLiveObject<T["relations"][K]["entity"], Include[K]> | null : InferLiveObject<T["relations"][K]["entity"], Include[K]> : InferLiveObject<T["relations"][K]["entity"], Include[K]>[] : never;
|
|
121
|
+
} : {});
|
|
122
|
+
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
123
|
+
[K in keyof T as T[K]["type"] extends "many" ? never : T[K]["relationalColumn"]]: T[K]["required"] extends true ? InferIndex<T[K]["entity"]> : InferIndex<T[K]["entity"]> | null;
|
|
124
|
+
};
|
|
125
|
+
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
126
|
+
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
|
|
127
|
+
declare class LiveObject<TName extends string, TSchema extends Record<string, LiveTypeAny>, TRelations extends Record<string, RelationAny>> extends LiveType<TSchema, LiveTypeMeta, LiveObjectMutationInput<any>, Record<string, MaterializedLiveType<LiveTypeAny>>> {
|
|
128
|
+
readonly name: TName;
|
|
129
|
+
readonly fields: TSchema;
|
|
130
|
+
readonly relations: TRelations;
|
|
131
|
+
constructor(name: TName, fields: TSchema, relations?: TRelations);
|
|
132
|
+
encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
|
|
133
|
+
mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
|
|
134
|
+
setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
|
|
135
|
+
getStorageFieldType(): StorageFieldType;
|
|
136
|
+
static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
|
|
137
|
+
}
|
|
138
|
+
declare const object: typeof LiveObject.create;
|
|
139
|
+
type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
|
|
140
|
+
declare class Relation<TEntity extends LiveObjectAny, TSourceEntity extends LiveObjectAny, TType extends "one" | "many", TRelationalColumn extends keyof TSourceEntity["fields"], TForeignColumn extends keyof TEntity["fields"], TRequired extends boolean> extends LiveType<InferIndex<TEntity>, {
|
|
141
|
+
timestamp: string | null;
|
|
142
|
+
} & LiveTypeMeta> {
|
|
143
|
+
readonly entity: TEntity;
|
|
144
|
+
readonly type: TType;
|
|
145
|
+
readonly required: TRequired;
|
|
146
|
+
readonly relationalColumn?: TRelationalColumn;
|
|
147
|
+
readonly foreignColumn?: TForeignColumn;
|
|
148
|
+
readonly sourceEntity: TSourceEntity;
|
|
149
|
+
private constructor();
|
|
150
|
+
encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
|
|
151
|
+
value: string;
|
|
152
|
+
_meta: {
|
|
153
|
+
timestamp: string;
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
mergeMutation(mutationType: MutationType, encodedMutation: {
|
|
157
|
+
value: string;
|
|
158
|
+
_meta: {
|
|
159
|
+
timestamp: string;
|
|
160
|
+
};
|
|
161
|
+
}, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
|
|
162
|
+
MaterializedLiveType<LiveString>,
|
|
163
|
+
{
|
|
164
|
+
value: string;
|
|
165
|
+
_meta: {
|
|
166
|
+
timestamp: string;
|
|
167
|
+
};
|
|
168
|
+
} | null
|
|
169
|
+
];
|
|
170
|
+
getStorageFieldType(): StorageFieldType;
|
|
171
|
+
toJSON(): {
|
|
172
|
+
entityName: string;
|
|
173
|
+
type: TType;
|
|
174
|
+
required: TRequired;
|
|
175
|
+
relationalColumn: TRelationalColumn | undefined;
|
|
176
|
+
foreignColumn: TForeignColumn | undefined;
|
|
177
|
+
};
|
|
178
|
+
static createOneFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TOriginEntity["fields"], TRequired extends boolean = false>(entity: TEntity, column: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "one", TColumn, never, TRequired>;
|
|
179
|
+
static createManyFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TEntity["fields"], TRequired extends boolean = false>(entity: TEntity, foreignColumn: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "many", never, TColumn, TRequired>;
|
|
180
|
+
}
|
|
181
|
+
type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
|
|
182
|
+
declare const createRelations: <TSourceObject extends LiveObjectAny, TRelations extends Record<string, RelationAny>>(liveObject: TSourceObject, factory: (connectors: {
|
|
183
|
+
one: ReturnType<typeof Relation.createOneFactory<TSourceObject>>;
|
|
184
|
+
many: ReturnType<typeof Relation.createManyFactory<TSourceObject>>;
|
|
185
|
+
}) => TRelations) => RelationsDecl<TSourceObject["name"], TRelations>;
|
|
186
|
+
type MaterializedLiveType<T extends LiveTypeAny> = {
|
|
187
|
+
value: T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
188
|
+
[K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
|
|
189
|
+
} : T["_value"];
|
|
190
|
+
_meta: T["_meta"];
|
|
191
|
+
};
|
|
192
|
+
declare const inferValue: <T extends LiveTypeAny>(type?: MaterializedLiveType<T>) => InferLiveType<T> | undefined;
|
|
193
|
+
type ExtractObjectValues<T> = T[keyof T];
|
|
194
|
+
type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
|
|
195
|
+
$type: "relations";
|
|
196
|
+
objectName: TObjectName;
|
|
197
|
+
relations: TRelations;
|
|
198
|
+
};
|
|
199
|
+
type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
200
|
+
[K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
|
|
201
|
+
[K2 in keyof TRawSchema[K]["relations"]]: Relation<ParseObjectFromSchema<TRawSchema, TRawSchema[K]["relations"][K2]["entity"]["name"]>, TRawSchema[K]["relations"][K2]["sourceEntity"], TRawSchema[K]["relations"][K2]["type"], Exclude<TRawSchema[K]["relations"][K2]["relationalColumn"], undefined>, Exclude<TRawSchema[K]["relations"][K2]["foreignColumn"], undefined>, TRawSchema[K]["relations"][K2]["required"]>;
|
|
202
|
+
} : never : never;
|
|
203
|
+
}>;
|
|
204
|
+
type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
205
|
+
[K in keyof TRawSchema]: TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] extends TObjectName ? LiveObject<TRawSchema[K]["name"], TRawSchema[K]["fields"], ParseRelationsFromSchema<TRawSchema, TRawSchema[K]["name"]>> : never : never;
|
|
206
|
+
}>;
|
|
207
|
+
type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
|
|
208
|
+
type Schema<TRawSchema extends RawSchema> = {
|
|
209
|
+
[K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
|
|
210
|
+
};
|
|
211
|
+
declare const createSchema: <TRawSchema extends RawSchema>(schema: TRawSchema) => Schema<TRawSchema>;
|
|
212
|
+
type WhereClause<T extends LiveObjectAny> = ({
|
|
213
|
+
[K in keyof T["fields"]]?: InferLiveType<T["fields"][K]> | ({
|
|
214
|
+
$eq?: InferLiveType<T["fields"][K]>;
|
|
215
|
+
$in?: InferLiveType<T["fields"][K]>[];
|
|
216
|
+
$not?: InferLiveType<T["fields"][K]> | {
|
|
217
|
+
$in?: InferLiveType<T["fields"][K]>[];
|
|
218
|
+
$eq?: InferLiveType<T["fields"][K]>;
|
|
219
|
+
};
|
|
220
|
+
} & (Exclude<InferLiveType<T["fields"][K]>, null | undefined> extends number | Date ? {
|
|
221
|
+
$gt?: InferLiveType<T["fields"][K]>;
|
|
222
|
+
$gte?: InferLiveType<T["fields"][K]>;
|
|
223
|
+
$lt?: InferLiveType<T["fields"][K]>;
|
|
224
|
+
$lte?: InferLiveType<T["fields"][K]>;
|
|
225
|
+
} : {}));
|
|
226
|
+
} & {
|
|
227
|
+
[K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
|
|
228
|
+
}) | {
|
|
229
|
+
$and?: WhereClause<T>[];
|
|
230
|
+
$or?: WhereClause<T>[];
|
|
231
|
+
};
|
|
232
|
+
type IncludeClause<T extends LiveObjectAny> = {
|
|
233
|
+
[K in keyof T["relations"]]?: boolean | IncludeClause<T["relations"][K]["entity"]>;
|
|
234
|
+
};
|
|
235
|
+
type GetFieldType<T> = T extends NullableLiveType<any> ? T["inner"] : T;
|
|
236
|
+
type HasDefaultValue<T> = T extends LiveAtomicType<any, undefined> ? false : true;
|
|
237
|
+
type InferInsert<T extends LiveObjectAny> = {
|
|
238
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends true ? never : K]: InferLiveType<T["fields"][K]>;
|
|
239
|
+
} & {
|
|
240
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends false ? never : K]?: InferLiveType<T["fields"][K]>;
|
|
241
|
+
};
|
|
242
|
+
type InferUpdate<T extends LiveObjectAny> = Omit<LiveObjectMutationInput<T>, "id">;
|
|
243
|
+
|
|
244
|
+
type Simplify<T> = T extends Record<string, unknown> ? {
|
|
245
|
+
[K in keyof T]: Simplify<T[K]>;
|
|
246
|
+
} : T extends Array<infer U> ? Array<Simplify<U>> : T;
|
|
247
|
+
declare const LogLevel: {
|
|
248
|
+
readonly CRITICAL: 0;
|
|
249
|
+
readonly ERROR: 1;
|
|
250
|
+
readonly WARN: 2;
|
|
251
|
+
readonly INFO: 3;
|
|
252
|
+
readonly DEBUG: 4;
|
|
253
|
+
};
|
|
254
|
+
type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];
|
|
255
|
+
/**
|
|
256
|
+
* Logger configuration options
|
|
257
|
+
*/
|
|
258
|
+
interface LoggerOptions {
|
|
259
|
+
/**
|
|
260
|
+
* Minimum log level to display. Anything below this level will be muted.
|
|
261
|
+
* @default LogLevel.INFO
|
|
262
|
+
*/
|
|
263
|
+
level?: LogLevel;
|
|
264
|
+
/**
|
|
265
|
+
* Optional prefix to add to all log messages
|
|
266
|
+
*/
|
|
267
|
+
prefix?: string;
|
|
268
|
+
}
|
|
269
|
+
declare class Logger {
|
|
270
|
+
private level;
|
|
271
|
+
private prefix;
|
|
272
|
+
constructor(options?: LoggerOptions);
|
|
273
|
+
critical(...args: any[]): void;
|
|
274
|
+
error(...args: any[]): void;
|
|
275
|
+
warn(...args: any[]): void;
|
|
276
|
+
info(...args: any[]): void;
|
|
277
|
+
debug(...args: any[]): void;
|
|
278
|
+
setLevel(level: LogLevel): void;
|
|
279
|
+
getLevel(): LogLevel;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export { type MutationType as A, type StorageFieldType as B, LiveType as C, type LiveTypeAny as D, type InferLiveType as E, type InferIndex as F, type InferLiveObjectWithRelationalIds as I, type LiveObjectAny as L, type MaterializedLiveType as M, NullableLiveType as N, Relation as R, type Simplify as S, type WhereClause as W, type Schema as a, type IncludeClause as b, type InferLiveObject as c, type InferInsert as d, type InferUpdate as e, Logger as f, LogLevel as g, type InferLiveObjectWithoutRelations as h, type LiveObjectMutationInput as i, LiveObject as j, createRelations as k, inferValue as l, createSchema as m, LiveAtomicType as n, object as o, LiveNumber as p, number as q, LiveString as r, string as s, id as t, reference as u, LiveBoolean as v, boolean as w, LiveTimestamp as x, timestamp as y, type LiveTypeMeta as z };
|