@live-state/sync 0.0.6-canary-7 → 0.0.6-canary-12
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-AHF6GNMI.js +1 -0
- package/dist/chunk-IT5UC7TA.js +1 -0
- package/dist/client.d.ts +1 -2
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +1 -2
- package/dist/fetch-client.js +1 -1
- package/dist/{index-H5NdEfdH.d.ts → index-B8lFpK0h.d.ts} +66 -44
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +33 -12
- package/dist/server.d.ts +33 -12
- package/dist/server.js +2 -2
- package/package.json +6 -4
- package/dist/chunk-3SQDLIFN.js +0 -1
- package/dist/chunk-RCXJM33Z.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
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 R(t){let e=Math.floor(t()*32);return e===32&&(e=31),b.charAt(e)}function _(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 M()?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=R(e)+n;return n}function E(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 M(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function I(t,e){let n=_(),i=Date.now();return E(i,10)+A(16,n)}var N=()=>I().toLowerCase();var 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,T){this._collection=e,this._client=n,this._where=i??{},this._include=r??{},this._limit=a,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)}limit(e){return new t(this._collection,this._client,this._where,this._include,e,this._single,this._sort,this._shouldAwait)}one(e){return this.first({id:e})}first(e){return new t(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,n="asc"){let i=[...this._sort??[],{key:e,direction:n}];return new t(this._collection,this._client,this._where,this._include,this._limit,this._single,i,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}buildQueryRequest(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}get(){let e=this._client.get(this.buildQueryRequest());return this._shouldAwait?Promise.resolve(e).then(n=>this._single?n[0]:n):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),n=>{if(this._single)return e(n[0]);e(n);})}static _init(e,n,i){return new t(e,n,void 0,void 0,void 0,void 0,void 0,i??false)}};var O=(t,e,n=[])=>new Proxy(t,{get:(i,r)=>{var T,y;if(r==="__isProxy__")return true;let a=(T=e.get)==null?void 0:T.call(e,i,[...n,r]);if(a!==void 0)return a;let 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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {xxHash32}from'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 V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var S=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of A(e))!M.call(t,a)&&a!==i&&I(t,a,{get:()=>e[a],enumerable:!(n=K(e,a))||n.enumerable});return t};var $=(t,e,i)=>(i=t!=null?O(j(t)):{},S(e||!t||!t.__esModule?I(i,"default",{value:t,enumerable:true}):i,t));var o=class{_value;_meta;_encodeInput;_decodeInput};var m=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,i,n){return this.inner.encodeMutation(e,i,n)}mergeMutation(e,i,n){return this.inner.mergeMutation(e,i,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},y=class t extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,i,n,a,s,l,r){super(),this.storageType=e,this.convertFunc=i,this.isIndex=n??false,this.isUnique=a??false,this.defaultValue=s,this.foreignReference=l,this.isPrimary=r??false;}encodeMutation(e,i,n){return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){return n&&n._meta.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(i.value):i.value,_meta:i._meta},i]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new t(this.storageType,this.convertFunc,this.isIndex,true,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}},q=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)}},N=p.create,D=p.createId,W=p.createReference,L=class t extends y{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},P=L.create,x=class t extends y{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},k=x.create;var g=class t extends o{name;fields;relations;constructor(e,i,n){super(),this.name=e,this.fields=i,this.relations=n??{};}encodeMutation(e,i,n){return Object.fromEntries(Object.entries(i).map(([a,s])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",s,n)]))}mergeMutation(e,i,n){let a={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(i).map(([s,l])=>{let r=this.fields[s]??this.relations[s];if(!r)return [s,l];let[u,d]=r.mergeMutation(e,l,n==null?void 0:n.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,i){return new t(e,i)}},H=g.create,f=class t extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,i,n,a,s){super(),this.entity=e,this.type=i,this.required=s??false,this.relationalColumn=n,this.foreignColumn=a;}encodeMutation(e,i,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){var a;return this.type==="many"?n?[n,null]:[i,i]:(a=n==null?void 0:n._meta)!=null&&a.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[i,i]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (e,i,n)=>new t(e,"one",i,void 0,n??false)}static createManyFactory(){return (e,i,n)=>new t(e,"many",void 0,i,n??false)}},z=(t,e)=>({$type:"relations",objectName:t.name,relations:e({one:f.createOneFactory(),many:f.createManyFactory()})}),h=t=>t?Array.isArray(t.value)?t.value.map(i=>h(i)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([i,n])=>Array.isArray(n)?[i,n.map(a=>h(a))]:[i,h(n)])):void 0,B=t=>Object.fromEntries(Object.entries(t).flatMap(([e,i])=>{if(i.$type==="relations")return [];let n=i,a=Object.values(t).find(s=>s.$type==="relations"&&s.objectName===i.name);return a&&(n=n.setRelations(a.relations)),[[n.name,n]]}));var Z=t=>xxHash32(JSON.stringify(t)).toString(32),C=(t,e,i)=>{let n={},a=i[e];if(!a)return n;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]&&(n[r]=true,typeof u=="object"&&u!==null&&!Array.isArray(u))){let b=C(u,a.relations[r].entity.name,i);Object.keys(b).length>0&&(n[r]=b);}});};return s(t),n},c=(t,e,i=false)=>Object.entries(e).every(([n,a])=>{if(n==="$and")return a.every(l=>c(t,l,i));if(n==="$or")return a.some(l=>c(t,l,i));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[n];return r===void 0?false:i?!a.$in.includes(r):a.$in.includes(r)}if(a.$not!==void 0&&!i)return c(t,{[n]:a.$not},true);if(a.$gt!==void 0){let r=t[n];return typeof r!="number"?false:i?r<=a.$gt:r>a.$gt}if(a.$gte!==void 0){let r=t[n];return typeof r!="number"?false:i?r<a.$gte:r>=a.$gte}if(a.$lt!==void 0){let r=t[n];return typeof r!="number"?false:i?r>=a.$lt:r<a.$lt}if(a.$lte!==void 0){let r=t[n];return typeof r!="number"?false:i?r>a.$lte:r<=a.$lte}let l=t[n];return !l||typeof l!="object"&&!Array.isArray(l)?false:Array.isArray(l)?i?!l.some(r=>c(r,a,false)):l.some(r=>c(r,a,false)):c(l,a,i)}return i?t[n]!==s:t[n]===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}},ee=t=>new R(t);export{V as a,$ as b,o as c,m as d,y as e,v as f,q as g,p as h,N as i,D as j,W as k,L as l,P as m,x as n,k as o,g as p,H as q,f as r,z as s,h as t,B as u,Z as v,C as w,c as x,T as y,ee as z};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import 'react/jsx-runtime';
|
|
1
|
+
export { e as Client, d as ClientEvents, C as ClientOptions, c as ConnectionStateChangeEvent, M as MessageReceivedEvent, f as createClient, u as useLiveQuery, b as useLoadData } from './index-B8lFpK0h.js';
|
|
3
2
|
import 'zod';
|
|
4
3
|
import 'zod/v3';
|
|
5
4
|
import 'zod/v4/core';
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 n=(s==null?void 0:s.$eq)!==void 0?s==null?void 0:s.$eq:s;if(typeof s=="object"&&s!==null&&(s==null?void 0:s.$eq)===void 0){if(s.$in!==void 0){let r=l[i];return r===void 0?false:t?!s.$in.includes(r):s.$in.includes(r)}if(s.$not!==void 0&&!t)return m(l,{[i]:s.$not},true);if(s.$gt!==void 0){let r=l[i];return typeof r!="number"?false:t?r<=s.$gt:r>s.$gt}if(s.$gte!==void 0){let r=l[i];return typeof r!="number"?false:t?r<s.$gte:r>=s.$gte}if(s.$lt!==void 0){let r=l[i];return typeof r!="number"?false:t?r>=s.$lt:r<s.$lt}if(s.$lte!==void 0){let r=l[i];return typeof r!="number"?false:t?r>s.$lte:r<=s.$lte}let o=l[i];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?t?!o.some(r=>m(r,s,false)):o.some(r=>m(r,s,false)):m(o,s,t)}return t?l[i]!==n:l[i]===n}),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 n;(n=this.subscriptions.get(t))==null||n.callbacks.add(i);let s=e.subscribe(()=>{var o;(o=this.subscriptions.get(t))==null||o.callbacks.forEach(r=>{r();});});return ()=>{var o;(o=this.subscriptions.get(t))==null||o.callbacks.delete(i),setTimeout(()=>{var r;((r=this.subscriptions.get(t))==null?void 0:r.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 x=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()}),k=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=k.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()}),A=U.extend({procedure:z.string(),payload:z.any().optional()}),W=U.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:X});z.union([W,A]);var S=z.string(),ee=x.extend({id:S,type:z.literal("SUBSCRIBE")}),te=x.extend({id:S,type:z.literal("QUERY")}),H=W.extend({id:S}),ie=A.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.array(k)});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(n=>[n,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 n=s.referencedBy.get(i.type);n&&n instanceof Set?n.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 n=this.nodes.get(s);if(!n)return;let o=n.referencedBy.get(i.type);o&&(o instanceof Set?o.delete(e):n.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 r=this.nodes.get(o);!r||!r.references.get(i)||(r.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(n){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,n);}});}getAllNodes(){return Array.from(this.nodes.values())}};var P="__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,n=await g(e),o=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,d])=>[c,await g(d)]))),r=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(O)||c.createObjectStore(O);}}),a=(h=await this.getAll(r,O))==null?void 0:h[t];(a==null?void 0:a.schemaHash)!==n&&s++,this.db=await openDB(t,s,{async upgrade(c){[...Object.keys(e),P].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 r.put(O,{schemaHash:n,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(P,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(P,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((n,o)=>[s[o],n]))}};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(n=>{!n||Object.keys(n).length===0||(this.optimisticMutationStack=n,s==null||s(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([n])=>{this.kvStorage.get(n).then(o=>{if(!o||Object.keys(o).length===0)return;let r=Object.values(o);this.loadConsolidatedState(n,r);});});}).catch(n=>{i.debug("Storage initialization failed (may not be available in this environment):",n);});});}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 r=this.querySnapshots[s];if(r)return r}let n=((o=e$1.where)!=null&&o.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(r=>{let a=f(this.materializeOneWithInclude(r,e$1.include));return a?[a]:[]});if(e$1.sort&&e$1.sort.length>0){let r=(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};n.sort(r);}if(e$1.where||e$1.limit){let r=e$1.where?a=>m(a,e$1.where):()=>true;n=e(n,r,e$1.limit);}return i||(this.querySnapshots[s]=n),n}subscribe(e,t){var n;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}),(n=this.collectionSubscriptions.get(i))==null||n.callbacks.add(t),()=>{var o,r;(o=this.collectionSubscriptions.get(i))==null||o.callbacks.delete(t),((r=this.collectionSubscriptions.get(i))==null?void 0:r.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var o,r,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let n=(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=(r=this.optimisticMutationStack)==null?void 0:r[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,n);}undoMutation(e,t){var o,r;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 n=(r=this.optimisticRawObjPool[e])==null?void 0:r[s.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,s.resourceId,Object.fromEntries(Object.entries(s.payload).map(([a])=>[a,{value:null,_meta:{}}])),n);}loadConsolidatedState(e,t){t.forEach(i=>{var n;let s=(n=i.id)==null?void 0:n.value;s&&this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:i});});}updateRawObjPool(e,t,i,s){var r;if(!this.schema[e])return;let n=(r=this.rawObjPool[e])==null?void 0:r[t],o=(this.optimisticMutationStack[e]??[]).reduce((a,p)=>p.resourceId!==t?a:this.schema[e].mergeMutation("set",p.payload,a)[0],n);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(D=>D.type==="many"?[D.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,n=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!n)return;let[o,r]=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:{...n.value,...Object.fromEntries(o.map(([p,h,c])=>[p,this.materializeOneWithInclude(i.references.get(h),typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(r.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],n=this.get(t.query,void 0,true);if(ae(n,s))return;this.querySnapshots[i]=n,t.callbacks.forEach(o=>{o(n);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,n])=>{var a;let o=(a=this.schema[t])==null?void 0:a.relations[s];if(!o)return;let r=o.entity.name;i.push(r),typeof n=="object"&&n!==null&&i.push(...this.flattenIncludes(n,r));}),Array.from(new Set(i))}};var I=class{url;ws;store;logger;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,n;this.url=e.url,this.logger=T({level:e.logLevel??y.INFO}),this.store=new L(e.schema,e.storage,this.logger,o=>{var r,a;(a=(r=Object.values(o))==null?void 0:r.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:(n=e.connection)==null?void 0:n.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(r=>{this.sendWsMessage({id:a(),type:"QUERY",resource:r});}),Object.entries(this.remoteSubCounters).forEach(([r,a$1])=>{a$1>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:r});}),Object.values(this.store.optimisticMutationStack).forEach(r=>{r&&r.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 n=K.parse(s);this.store.loadConsolidatedState(n.resource,n.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 n={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,n,true),this.sendWsMessage(n);}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((n,o)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],o(new Error("Reply timeout"));},5e3),handler:r=>{delete this.replyHandlers[s.id],n(r);}};})}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 I(l),t=T({level:l.logLevel??y.INFO,prefix:"Client"});return {client:{ws:e.ws,subscribe:i=>{let s=[];for(let n of i??Object.keys(e.store.schema))s.push(e.subscribeToRemote(n));return ()=>{t.debug("Removing listeners",s),s.forEach(n=>{n();});}},addEventListener:i=>e.addEventListener(i)},store:{query:Object.entries(l.schema).reduce((i,[s,n])=>(i[s]=c._init(n,e),i),{}),mutate:d(()=>{},{apply:(i,s,n)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[o,r]=s;if(r==="insert"){let{id:a,...p}=n[0];return e.mutate(o,a,"INSERT",p)}if(r==="update"){let[a,p]=n;return e.mutate(o,a,"UPDATE",p)}return e.genericMutate(o,r,n[0])}})}}};export{he as SubscriptionProvider,Qe as createClient,de as useLiveQuery};
|
|
1
|
+
import {d,c,a,f,e,b as b$1}from'./chunk-AHF6GNMI.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z}from'zod';import {stringify}from'qs';import ue from'fast-deep-equal';import {openDB}from'idb';var g=l=>xxHash32(JSON.stringify(l)).toString(32);var b=(l,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(o=>b(l,o,t));if(i==="$or")return s.some(o=>b(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 b(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=>b(n,s,false)):o.some(n=>b(n,s,false)):b(o,s,t)}return t?l[i]!==r:l[i]===r}),v={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},x=class{level;prefix;constructor(e={}){this.level=e.level??v.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=v.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=v.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=v.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=v.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=v.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},U=l=>new x(l);var A=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)}},ee=new A,fe=l=>useSyncExternalStore(ee.getOrStoreSubscription(l),l.get),ge=(l,e)=>{useEffect(()=>{let t=l.load(e.buildQueryRequest());return ()=>{t();}},[e,l.load]);};var O=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()}),k=z.record(z.string(),z.object({value:z.any().nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})),te=k.superRefine((l,e)=>{l.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Q=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),P=Q.extend({procedure:z.string(),payload:z.any().optional()}),W=Q.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:te});z.union([W,P]);var M=z.string(),ie=O.extend({id:M,type:z.literal("SUBSCRIBE")}),se=O.extend({id:M,type:z.literal("UNSUBSCRIBE")}),ne=O.extend({id:M,type:z.literal("QUERY")}),H=W.extend({id:M}),re=P.extend({id:M}),oe=z.union([re,H]);z.union([ie,ne,oe,se]);var ae=z.object({id:M,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),ce=z.object({id:M,type:z.literal("REPLY"),data:z.any()}),q=z.union([ae,ce,H]),K=z.object({resource:z.string(),data:z.array(k)});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(s=>{s(t);});}};var L=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 D="__meta",C="databases",T=class{db;async init(e,t){var u,p;if(typeof window>"u")return;let s=((u=(await window.indexedDB.databases()).find(c=>c.name===t))==null?void 0:u.version)??1,r=await g(e),o=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,h])=>[c,await g(h)]))),n=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(C)||c.createObjectStore(C);}}),a=(p=await this.getAll(n,C))==null?void 0:p[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(c){[...Object.keys(e),D].forEach(h=>{(a==null?void 0:a.objectHashes[h])!==o[h]&&c.objectStoreNames.contains(h)&&c.deleteObjectStore(h),c.objectStoreNames.contains(h)||c.createObjectStore(h);}),await n.put(C,{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(D,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(D,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((r,o)=>[s[o],r]))}};var j=class{constructor(e,t,i,s){this.schema=e;this.logger=i,this.optimisticObjGraph=new L(i),this.kvStorage=new T,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])=>{this.kvStorage.get(r).then(o=>{if(!o||Object.keys(o).length===0)return;let n=Object.values(o);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,u)=>{for(let p of e$1.sort){let c=a[p.key],h=u[p.key];if(c<h)return p.direction==="asc"?-1:1;if(c>h)return p.direction==="asc"?1:-1}return 0};r.sort(n);}if(e$1.where||e$1.limit){let n=e$1.where?a=>b(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 u={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=u;let p=u.value;delete p.id,this.kvStorage.set(e,t.resourceId,p);}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){t.forEach(i=>{var n;let s=(n=i.id)==null?void 0:n.value;if(!s)return;let{cleanedPayload:r,nestedMutations:o}=this.extractNestedRelations(e,i);o.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:r});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},r=[];return i!=null&&i.relations?(Object.entries(t).forEach(([o,n])=>{var c,h;let a=i.relations[o];if(!a)return;let u=a.entity.name,p=n==null?void 0:n.value;if(a.type==="one"){if(p&&typeof p=="object"&&!Array.isArray(p)&&((h=(c=p.value)==null?void 0:c.id)!=null&&h.value)){let f=p.value.id.value,m={...p.value},{cleanedPayload:S,nestedMutations:w}=this.extractNestedRelations(u,m);r.push(...w),r.push({id:f,type:"MUTATE",resource:u,resourceId:f,procedure:"INSERT",payload:S}),delete s[o];}}else a.type==="many"&&Array.isArray(p)&&(p.forEach(f=>{var m,S;if(f&&typeof f=="object"&&!Array.isArray(f)&&((S=(m=f.value)==null?void 0:m.id)!=null&&S.value)){let w=f.value.id.value,F={...f.value},{cleanedPayload:V,nestedMutations:J}=this.extractNestedRelations(u,F);r.push(...J),r.push({id:w,type:"MUTATE",resource:u,resourceId:w,procedure:"INSERT",payload:V});}}),delete s[o]);}),{cleanedPayload:s,nestedMutations:r}):{cleanedPayload:s,nestedMutations:r}}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,u)=>u.resourceId!==t?a:this.schema[e].mergeMutation("set",u.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(([u,p])=>p.type==="one"?[[p.relationalColumn,u]]:[]));Object.entries(i).forEach(([u,p])=>{let c=this.schema[e].relations[a[u]];if(!a[u])return;let h=s==null?void 0:s.value[u],[,f]=c.mergeMutation("set",p,h);if(f){if(!this.optimisticObjGraph.hasNode(f.value)){let m=c.entity.name;this.optimisticObjGraph.createNode(f.value,m,Object.values(this.schema[m].relations).flatMap(S=>S.type==="many"?[S.entity.name]:[]));}h!=null&&h.value&&this.optimisticObjGraph.removeLink(t,c.entity.name),this.optimisticObjGraph.createLink(t,f.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var a;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let s=i.type,r=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!r)return;let[o,n]=Object.entries(t).reduce((u,[p,c])=>{let h=this.schema[s].relations[p];return h&&(h.type==="one"?u[0].push([p,h.entity.name,c??true]):h.type==="many"&&u[1].push([p,h.entity.name,c??true])),u},[[],[]]);return {value:{...r.value,...Object.fromEntries(o.map(([u,p,c])=>[u,this.materializeOneWithInclude(i.references.get(p),typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(n.map(([u,p,c])=>{let h=i.referencedBy.get(p),f=h instanceof Set;return [u,f?{value:Array.from(h.values()).map(m=>this.materializeOneWithInclude(m,typeof c=="object"&&c!==null?c:{}))}:this.materializeOneWithInclude(h,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(ue(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 I=class{url;ws;store;logger;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,r;this.url=e.url,this.logger=U({level:e.logLevel??v.INFO}),this.store=new j(e.schema,e.storage,this.logger,o=>{var n,a;(a=(n=Object.values(o))==null?void 0:n.flat())==null||a.forEach(u=>{this.sendWsMessage(u);});}),this.ws=new R({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&&(Array.from(this.remoteSubscriptions.values()).forEach(({query:n})=>{this.sendWsMessage({id:a(),type:"SUBSCRIBE",...n});}),Object.values(this.store.optimisticMutationStack).forEach(n=>{n&&n.forEach(a=>{this.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);}}load(e){this.sendWsMessage({id:a(),type:"SUBSCRIBE",...e});let t=g(e);return this.remoteSubscriptions.has(t)?this.remoteSubscriptions.get(t).subCounter+=1:this.remoteSubscriptions.set(t,{query:e,subCounter:1}),()=>{this.remoteSubscriptions.has(t)&&(this.remoteSubscriptions.get(t).subCounter-=1,this.remoteSubscriptions.get(t).subCounter<=0&&(this.remoteSubscriptions.delete(t),this.sendWsMessage({id:a(),type:"UNSUBSCRIBE",...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);});}},Ke=l=>{let e=new I(l);return {client:{ws:e.ws,load:t=>e.load(t),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,o]=i;if(o==="insert"){let{id:n,...a}=s[0];return e.mutate(r,n,"INSERT",a)}if(o==="update"){let[n,a]=s;return e.mutate(r,n,"UPDATE",a)}return e.genericMutate(r,o,s[0])}})}}};export{Ke as createClient,fe as useLiveQuery,ge as useLoadData};
|
package/dist/fetch-client.d.ts
CHANGED
package/dist/fetch-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,b,c,f as f$1}from'./chunk-
|
|
1
|
+
import {d,b,c,f as f$1}from'./chunk-AHF6GNMI.js';import {stringify}from'qs';var f=async(e,c,r)=>{let n=o=>{if(!o)return {};if(o instanceof Headers){let y={};return o.forEach((d,b)=>{y[b]=d;}),y}return Array.isArray(o)?Object.fromEntries(o):o},s=n(r==null?void 0:r.headers),u=n(c==null?void 0:c.headers),a={...r,...c,headers:{...s,...u}},t=await fetch(e,a),i;try{i=await t.json();}catch{i=await t.text().catch(()=>{});}if(!t.ok)throw new Error(`Failed to fetch: ${t.status} ${t.statusText}`,{cause:i});return i},h=e=>{if(e===null)return "null";if(Array.isArray(e))return e.map(h);if(typeof e=="object"&&e!==null&&e.constructor===Object){let c={};for(let[r,n]of Object.entries(e))c[r]=h(n);return c}return e},C=e=>{let c$1={get:async r=>{let n=h(r),s=stringify(n),u=await b(e.credentials)??{},a=await f(`${e.url}/${r.resource}${s?`?${s}`:""}`,{headers:{...u,"Content-Type":"application/json"}},e.fetchOptions);return !a||typeof a!="object"?[]:Array.isArray(a)?a.map(t=>{var y,d;let i=f$1(t),o=((d=(y=t==null?void 0:t.value)==null?void 0:y.id)==null?void 0:d.value)??(t==null?void 0:t.id);return {...i,id:o}}):Object.entries(a).map(([t,i])=>({...f$1(i),id:t}))},subscribe:()=>{throw new Error("Fetch client does not support subscriptions")}};return {query:Object.entries(e.schema).reduce((r,[n,s])=>(r[n]=c._init(s,c$1,true),r),{}),mutate:d(()=>{},{apply:async(r,n,s)=>{if(n.length<2)return;if(n.length>2)throw new Error("Trying to access an invalid path");let[u,a]=n,t=await b(e.credentials)??{};if(a==="insert"){let{id:i,...o}=s[0];await f(`${e.url}/${u}/insert`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({resourceId:i,payload:e.schema[u].encodeMutation("set",o,new Date().toISOString())})},e.fetchOptions);return}if(a==="update"){let[i,o]=s,{id:y,...d}=o;await f(`${e.url}/${u}/update`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({resourceId:i,payload:e.schema[u].encodeMutation("set",d,new Date().toISOString())})},e.fetchOptions);return}return await f(`${e.url}/${u}/${a}`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({payload:s[0]})},e.fetchOptions)}})}};export{C as createClient};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
1
|
import { z } from 'zod';
|
|
3
2
|
import * as z3 from 'zod/v3';
|
|
4
3
|
import * as z4 from 'zod/v4/core';
|
|
@@ -221,9 +220,9 @@ type InferInsert<T extends LiveObjectAny> = {
|
|
|
221
220
|
};
|
|
222
221
|
type InferUpdate<T extends LiveObjectAny> = Omit<LiveObjectMutationInput<T>, "id">;
|
|
223
222
|
|
|
224
|
-
type Promisify<T> = T extends Promise<
|
|
223
|
+
type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
|
|
225
224
|
type ConditionalPromise<T, P extends boolean> = P extends true ? Promise<T> : T;
|
|
226
|
-
type
|
|
225
|
+
type PromiseOrSync<T> = T | Promise<T>;
|
|
227
226
|
type Generatable<T, Arg = never> = T | ((arg: Arg) => T);
|
|
228
227
|
|
|
229
228
|
type Simplify<T> = T extends Record<string, unknown> ? {
|
|
@@ -302,45 +301,40 @@ declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends M
|
|
|
302
301
|
withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
|
|
303
302
|
mutation: typeof mutationCreator;
|
|
304
303
|
}) => T): Route<TResourceSchema, TMiddleware, T>;
|
|
304
|
+
getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
|
|
305
305
|
private handleSet;
|
|
306
306
|
private wrapInMiddlewares;
|
|
307
307
|
}
|
|
308
308
|
type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
|
|
309
309
|
|
|
310
|
-
/** biome-ignore-all lint/
|
|
310
|
+
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
311
311
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
private _client;
|
|
319
|
-
private _where;
|
|
320
|
-
private _include;
|
|
321
|
-
private _limit?;
|
|
322
|
-
private _single?;
|
|
323
|
-
private _sort?;
|
|
324
|
-
private _shouldAwait?;
|
|
325
|
-
private constructor();
|
|
326
|
-
where(where: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
327
|
-
include<TNewInclude extends IncludeClause<TCollection>>(include: TNewInclude): QueryBuilder<TCollection, TInclude & TNewInclude, TSingle, TShouldAwait>;
|
|
328
|
-
get(): ConditionalPromise<InferQueryResult<TCollection, TInclude, TSingle>, TShouldAwait>;
|
|
329
|
-
subscribe(callback: (value: InferQueryResult<TCollection, TInclude, TSingle>) => void): () => void;
|
|
330
|
-
limit(limit: number): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
331
|
-
one(id: string): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
332
|
-
first(where?: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
333
|
-
orderBy(key: keyof TCollection["fields"], direction?: "asc" | "desc"): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
334
|
-
toJSON(): {
|
|
312
|
+
declare class Batcher {
|
|
313
|
+
private storage;
|
|
314
|
+
private queue;
|
|
315
|
+
private scheduled;
|
|
316
|
+
constructor(storage: Storage);
|
|
317
|
+
rawFind<T extends LiveObjectAny>({ resource, commonWhere, uniqueWhere, ...rest }: {
|
|
335
318
|
resource: string;
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
319
|
+
commonWhere?: Record<string, any>;
|
|
320
|
+
uniqueWhere?: Record<string, any>;
|
|
321
|
+
include?: Record<string, any>;
|
|
322
|
+
limit?: number;
|
|
323
|
+
sort?: {
|
|
340
324
|
key: string;
|
|
341
325
|
direction: "asc" | "desc";
|
|
342
|
-
}[]
|
|
343
|
-
}
|
|
326
|
+
}[];
|
|
327
|
+
}): Promise<MaterializedLiveType<T>[]>;
|
|
328
|
+
private getBatchKey;
|
|
329
|
+
private processBatch;
|
|
330
|
+
private executeBatchedRequests;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
interface DataSource {
|
|
334
|
+
get(query: RawQueryRequest, extra?: {
|
|
335
|
+
context?: any;
|
|
336
|
+
batcher?: Batcher;
|
|
337
|
+
}): PromiseOrSync<any[]>;
|
|
344
338
|
}
|
|
345
339
|
|
|
346
340
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
@@ -367,8 +361,6 @@ declare abstract class Storage implements DataSource {
|
|
|
367
361
|
}) => Promise<T>): Promise<T>;
|
|
368
362
|
}
|
|
369
363
|
|
|
370
|
-
/** biome-ignore-all lint/suspicious/noExplicitAny: any's are actually used correctly */
|
|
371
|
-
|
|
372
364
|
interface BaseRequest {
|
|
373
365
|
headers: Record<string, string>;
|
|
374
366
|
cookies: Record<string, string>;
|
|
@@ -386,20 +378,50 @@ interface MutationRequest<TInput = any> extends BaseRequest {
|
|
|
386
378
|
procedure: string;
|
|
387
379
|
}
|
|
388
380
|
type Request = QueryRequest | MutationRequest;
|
|
389
|
-
type NextFunction<O, R = Request> = (req: R) =>
|
|
381
|
+
type NextFunction<O, R = Request> = (req: R) => PromiseOrSync<O>;
|
|
390
382
|
type Middleware<T = any> = (opts: {
|
|
391
383
|
req: Request;
|
|
392
384
|
next: NextFunction<T>;
|
|
393
385
|
}) => ReturnType<NextFunction<T>>;
|
|
394
386
|
|
|
387
|
+
/** biome-ignore-all lint/complexity/noBannedTypes: <explanation> */
|
|
388
|
+
|
|
389
|
+
type InferQueryResult<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection>, TSingle extends boolean = false> = TSingle extends true ? Simplify<InferLiveObject<TCollection, TInclude>> | undefined : Simplify<InferLiveObject<TCollection, TInclude>>[];
|
|
390
|
+
declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection> = {}, TSingle extends boolean = false, TShouldAwait extends boolean = false> {
|
|
391
|
+
private _collection;
|
|
392
|
+
private _client;
|
|
393
|
+
private _where;
|
|
394
|
+
private _include;
|
|
395
|
+
private _limit?;
|
|
396
|
+
private _single?;
|
|
397
|
+
private _sort?;
|
|
398
|
+
private _shouldAwait?;
|
|
399
|
+
private constructor();
|
|
400
|
+
where(where: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
401
|
+
include<TNewInclude extends IncludeClause<TCollection>>(include: TNewInclude): QueryBuilder<TCollection, TInclude & TNewInclude, TSingle, TShouldAwait>;
|
|
402
|
+
limit(limit: number): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
403
|
+
one(id: string): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
404
|
+
first(where?: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
405
|
+
orderBy(key: keyof TCollection["fields"], direction?: "asc" | "desc"): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
406
|
+
toJSON(): {
|
|
407
|
+
resource: string;
|
|
408
|
+
where: WhereClause<TCollection>;
|
|
409
|
+
include: TInclude;
|
|
410
|
+
limit: number | undefined;
|
|
411
|
+
sort: {
|
|
412
|
+
key: string;
|
|
413
|
+
direction: "asc" | "desc";
|
|
414
|
+
}[] | undefined;
|
|
415
|
+
};
|
|
416
|
+
get(): ConditionalPromise<InferQueryResult<TCollection, TInclude, TSingle>, TShouldAwait>;
|
|
417
|
+
subscribe(callback: (value: InferQueryResult<TCollection, TInclude, TSingle>) => void): () => void;
|
|
418
|
+
}
|
|
419
|
+
|
|
395
420
|
declare const useLiveQuery: <T extends {
|
|
396
421
|
get: () => U;
|
|
397
422
|
subscribe: (cb: (v: U) => void) => () => void;
|
|
398
423
|
}, U>(observable: T) => ReturnType<T["get"]>;
|
|
399
|
-
declare const
|
|
400
|
-
children: React.ReactNode;
|
|
401
|
-
client: Client<AnyRouter>["client"];
|
|
402
|
-
}) => react_jsx_runtime.JSX.Element;
|
|
424
|
+
declare const useLoadData: (client: Client<AnyRouter>["client"], query: QueryBuilder<any, any>) => void;
|
|
403
425
|
|
|
404
426
|
declare const serverMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
405
427
|
id: z.ZodString;
|
|
@@ -419,7 +441,7 @@ declare const serverMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
419
441
|
UPDATE: "UPDATE";
|
|
420
442
|
}>;
|
|
421
443
|
payload: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
422
|
-
value: z.ZodNullable<z.
|
|
444
|
+
value: z.ZodNullable<z.ZodAny>;
|
|
423
445
|
_meta: z.ZodOptional<z.ZodObject<{
|
|
424
446
|
timestamp: z.ZodNullable<z.ZodOptional<z.ZodString>>;
|
|
425
447
|
}, z.core.$strip>>;
|
|
@@ -501,8 +523,8 @@ type ClientEvents = ConnectionStateChangeEvent | MessageReceivedEvent;
|
|
|
501
523
|
type Client<TRouter extends AnyRouter> = {
|
|
502
524
|
client: {
|
|
503
525
|
ws: WebSocketClient;
|
|
504
|
-
subscribe: (resourceType?: string[]) => () => void;
|
|
505
526
|
addEventListener: (listener: (event: ClientEvents) => void) => () => void;
|
|
527
|
+
load: (query: RawQueryRequest) => () => void;
|
|
506
528
|
};
|
|
507
529
|
store: Client$1<TRouter>;
|
|
508
530
|
};
|
|
@@ -511,11 +533,11 @@ declare const createClient: <TRouter extends AnyRouter>(opts: WebSocketClientOpt
|
|
|
511
533
|
type ClientOptions = {
|
|
512
534
|
url: string;
|
|
513
535
|
schema: Schema<any>;
|
|
514
|
-
credentials?: Generatable<
|
|
536
|
+
credentials?: Generatable<PromiseOrSync<Record<string, string>>>;
|
|
515
537
|
storage: {
|
|
516
538
|
name: string;
|
|
517
539
|
} | false;
|
|
518
540
|
logLevel?: LogLevel;
|
|
519
541
|
};
|
|
520
542
|
|
|
521
|
-
export { type AnyRouter as A, type ClientOptions as C, type MessageReceivedEvent as M,
|
|
543
|
+
export { type AnyRouter as A, type ClientOptions as C, type MessageReceivedEvent as M, type Client$1 as a, useLoadData as b, type ConnectionStateChangeEvent as c, type ClientEvents as d, type Client as e, createClient as f, useLiveQuery as u };
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';require('js-xxhash');var s=class{_value;_meta;_encodeInput;_decodeInput};var T=class extends s{inner;constructor(
|
|
1
|
+
'use strict';require('js-xxhash');var s=class{_value;_meta;_encodeInput;_decodeInput};var T=class extends s{inner;constructor(t){super(),this.inner=t;}encodeMutation(t,n,e){return this.inner.encodeMutation(t,n,e)}mergeMutation(t,n,e){return this.inner.mergeMutation(t,n,e)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},l=class i extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(t,n,e,a,r,u,y){super(),this.storageType=t,this.convertFunc=n,this.isIndex=e??false,this.isUnique=a??false,this.defaultValue=r,this.foreignReference=u,this.isPrimary=y??false;}encodeMutation(t,n,e){return {value:n,_meta:{timestamp:e}}}mergeMutation(t,n,e){return e&&e._meta.timestamp&&n._meta.timestamp&&e._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[e,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 i(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new i(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(t){return new i(this.storageType,this.convertFunc,this.isIndex,this.isUnique,t,this.foreignReference,this.isPrimary)}primary(){return new i(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}nullable(){return new T(this)}},d=class i extends l{constructor(){super("integer",t=>Number(t));}static create(){return new i}},b=d.create,o=class i extends l{constructor(t){super("varchar",void 0,void 0,void 0,void 0,t);}static create(){return new i}static createId(){return new i().index().unique().primary()}static createReference(t){return new i(t)}},I=o.create,O=o.createId,K=o.createReference,p=class i extends l{constructor(){super("boolean",t=>typeof t=="string"?t.toLowerCase()==="true":!!t);}static create(){return new i}},A=p.create,f=class i extends l{constructor(){super("timestamp",t=>typeof t=="string"?new Date(t):t);}static create(){return new i}},j=f.create;var v=class i extends s{name;fields;relations;constructor(t,n,e){super(),this.name=t,this.fields=n,this.relations=e??{};}encodeMutation(t,n,e){return Object.fromEntries(Object.entries(n).map(([a,r])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",r,e)]))}mergeMutation(t,n,e){let a={};return [{value:{...(e==null?void 0:e.value)??{},...Object.fromEntries(Object.entries(n).map(([r,u])=>{let y=this.fields[r]??this.relations[r];if(!y)return [r,u];let[x,L]=y.mergeMutation(t,u,e==null?void 0:e.value[r]);return L&&(a[r]=L),[r,x]}))}},a]}setRelations(t){return new i(this.name,this.fields,t)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(t,n){return new i(t,n)}},w=v.create,c=class i extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(t,n,e,a,r){super(),this.entity=t,this.type=n,this.required=r??false,this.relationalColumn=e,this.foreignColumn=a;}encodeMutation(t,n,e){if(t!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:n,_meta:{timestamp:e}}}mergeMutation(t,n,e){var a;return this.type==="many"?e?[e,null]:[n,n]:(a=e==null?void 0:e._meta)!=null&&a.timestamp&&n._meta.timestamp&&e._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[e,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 (t,n,e)=>new i(t,"one",n,void 0,e??false)}static createManyFactory(){return (t,n,e)=>new i(t,"many",void 0,n,e??false)}},C=(i,t)=>({$type:"relations",objectName:i.name,relations:t({one:c.createOneFactory(),many:c.createManyFactory()})}),m=i=>i?Array.isArray(i.value)?i.value.map(n=>m(n)):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([n,e])=>Array.isArray(e)?[n,e.map(a=>m(a))]:[n,m(e)])):void 0,V=i=>Object.fromEntries(Object.entries(i).flatMap(([t,n])=>{if(n.$type==="relations")return [];let e=n,a=Object.values(i).find(r=>r.$type==="relations"&&r.objectName===n.name);return a&&(e=e.setRelations(a.relations)),[[e.name,e]]}));var h={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4};exports.LiveAtomicType=l;exports.LiveBoolean=p;exports.LiveNumber=d;exports.LiveObject=v;exports.LiveString=o;exports.LiveTimestamp=f;exports.LiveType=s;exports.LogLevel=h;exports.NullableLiveType=T;exports.Relation=c;exports.boolean=A;exports.createRelations=C;exports.createSchema=V;exports.id=O;exports.inferValue=m;exports.number=b;exports.object=w;exports.reference=K;exports.string=I;exports.timestamp=j;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as LiveAtomicType,l as LiveBoolean,f as LiveNumber,p as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,y as LogLevel,d as NullableLiveType,r as Relation,m as boolean,s as createRelations,u as createSchema,j as id,t as inferValue,g as number,q as object,k as reference,i as string,o as timestamp}from'./chunk-
|
|
1
|
+
export{e as LiveAtomicType,l as LiveBoolean,f as LiveNumber,p as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,y as LogLevel,d as NullableLiveType,r as Relation,m as boolean,s as createRelations,u as createSchema,j as id,t as inferValue,g as number,q as object,k as reference,i as string,o as timestamp}from'./chunk-IT5UC7TA.js';
|
package/dist/server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var J=require('crypto'),jsXxhash=require('js-xxhash'),xt=require('qs'),zod=require('zod'),kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var J__default=/*#__PURE__*/_interopDefault(J);var xt__default=/*#__PURE__*/_interopDefault(xt);var Ge=Object.create;var we=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var Xe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var et=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of He(e))!Ye.call(r,i)&&i!==t&&we(r,i,{get:()=>e[i],enumerable:!(n=Ze(e,i))||n.enumerable});return r};var Ie=(r,e,t)=>(t=r!=null?Ge(Je(r)):{},et(we(t,"default",{value:r,enumerable:true}),r));var de=Xe(ee=>{Object.defineProperty(ee,"__esModule",{value:true});ee.parse=mt;ee.serialize=ht;var ut=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,lt=/^[\u0021-\u003A\u003C-\u007E]*$/,dt=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,yt=/^[\u0020-\u003A\u003D-\u007E]*$/,pt=Object.prototype.toString,ft=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function mt(r,e){let t=new ft,n=r.length;if(n<2)return t;let i=(e==null?void 0:e.decode)||Tt,a=0;do{let s=r.indexOf("=",a);if(s===-1)break;let o=r.indexOf(";",a),c=o===-1?n:o;if(s>c){a=r.lastIndexOf(";",s-1)+1;continue}let u=Ce(r,a,s),p=$e(r,s,u),l=r.slice(u,p);if(t[l]===void 0){let h=Ce(r,s+1,c),m=$e(r,c,h),d=i(r.slice(h,m));t[l]=d;}a=c+1;}while(a<n);return t}function Ce(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function $e(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function ht(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!ut.test(r))throw new TypeError(`argument name is invalid: ${r}`);let i=n(e);if(!lt.test(i))throw new TypeError(`argument val is invalid: ${e}`);let a=r+"="+i;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!dt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!yt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!gt(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);a+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(a+="; HttpOnly"),t.secure&&(a+="; Secure"),t.partitioned&&(a+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return a}function Tt(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function gt(r){return pt.call(r)==="[object Date]"}});var Le="0123456789ABCDEFGHJKMNPQRSTVWXYZ",q=32;var tt=16,Ae=10,Me=0xffffffffffff;var V;(function(r){r.Base32IncorrectEncoding="B32_ENC_INVALID",r.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",r.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",r.EncodeTimeNegative="ENC_TIME_NEG",r.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",r.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",r.PRNGDetectFailure="PRNG_DETECT",r.ULIDInvalid="ULID_INVALID",r.Unexpected="UNEXPECTED",r.UUIDInvalid="UUID_INVALID";})(V||(V={}));var _=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function nt(r){let e=Math.floor(r()*q);return e===q&&(e=q-1),Le.charAt(e)}function rt(r){var n;let e=it(),t=e&&(e.crypto||e.msCrypto)||(typeof J__default.default<"u"?J__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return t.getRandomValues(i),i[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=J__default.default)!=null&&n.randomBytes)return ()=>J__default.default.randomBytes(1).readUInt8()/255;throw new _(V.PRNGDetectFailure,"Failed to find a reliable PRNG")}function it(){return st()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function at(r,e){let t="";for(;r>0;r--)t=nt(e)+t;return t}function ot(r,e=Ae){if(isNaN(r))throw new _(V.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>Me)throw new _(V.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Me}: ${r}`);if(r<0)throw new _(V.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new _(V.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let i=e;i>0;i--)t=r%q,n=Le.charAt(t)+n,r=(r-t)/q;return n}function st(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Oe(r,e){let t=rt(),n=Date.now();return ot(n,Ae)+at(tt,t)}var Y=()=>Oe().toLowerCase();var D=(...r)=>{let e=r.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var I=r=>r?Array.isArray(r.value)?r.value.map(t=>I(t)):typeof r.value!="object"||r.value===null||r.value instanceof Date?r.value:Object.fromEntries(Object.entries(r.value).map(([t,n])=>Array.isArray(n)?[t,n.map(i=>I(i))]:[t,I(n)])):void 0;var je=r=>jsXxhash.xxHash32(JSON.stringify(r)).toString(32),B=(r,e,t)=>{let n={},i=t[e];if(!i)return n;let a=s=>{s.$and?s.$and.forEach(a):s.$or?s.$or.forEach(a):Object.entries(s).forEach(([o,c])=>{var u;if((u=i.relations)!=null&&u[o]&&(n[o]=true,typeof c=="object"&&c!==null&&!Array.isArray(c))){let p=B(c,i.relations[o].entity.name,t);Object.keys(p).length>0&&(n[o]=p);}});};return a(r),n},C=(r,e,t=false)=>Object.entries(e).every(([n,i])=>{if(n==="$and")return i.every(s=>C(r,s,t));if(n==="$or")return i.some(s=>C(r,s,t));let a=(i==null?void 0:i.$eq)!==void 0?i==null?void 0:i.$eq:i;if(typeof i=="object"&&i!==null&&(i==null?void 0:i.$eq)===void 0){if(i.$in!==void 0){let o=r[n];return o===void 0?false:t?!i.$in.includes(o):i.$in.includes(o)}if(i.$not!==void 0&&!t)return C(r,{[n]:i.$not},true);if(i.$gt!==void 0){let o=r[n];return typeof o!="number"?false:t?o<=i.$gt:o>i.$gt}if(i.$gte!==void 0){let o=r[n];return typeof o!="number"?false:t?o<i.$gte:o>=i.$gte}if(i.$lt!==void 0){let o=r[n];return typeof o!="number"?false:t?o>=i.$lt:o<i.$lt}if(i.$lte!==void 0){let o=r[n];return typeof o!="number"?false:t?o>i.$lte:o<=i.$lte}let s=r[n];return !s||typeof s!="object"&&!Array.isArray(s)?false:Array.isArray(s)?t?!s.some(o=>C(o,i,false)):s.some(o=>C(o,i,false)):C(s,i,t)}return t?r[n]!==a:r[n]===a}),z={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},le=class{level;prefix;constructor(e={}){this.level=e.level??z.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=z.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=z.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=z.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=z.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=z.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},Ee=r=>new le(r);var X=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...i}){return new Promise((a,s)=>{let o=this.getBatchKey({resource:e,commonWhere:t,...i}),c={resource:e,commonWhere:t,uniqueWhere:n,...i,resolve:a,reject:s};this.queue.has(o)||this.queue.set(o,[]);let u=this.queue.get(o);u&&u.push(c),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...i}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(i??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(i=>{i.reject(n);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:i,include:a,sort:s}=t,o=e.length===1?t.limit:void 0,c=e.map(m=>m.uniqueWhere).filter(m=>m!==void 0),u=i,p=(h=Object.entries(c[0]??{})[0])==null?void 0:h[0];if(c.length>0){let m=c.map(d=>d[p]).filter(d=>d!=null);m.length>0&&(u=D(i,{[p]:{$in:m}}));}let l=await this.storage.get({resource:n,where:u,include:a,sort:s,limit:o});for(let m of e){let d=l;if(m.uniqueWhere){let[R,f]=Object.entries(m.uniqueWhere)[0];d=l.filter(y=>{var g;return ((g=y.value[R])==null?void 0:g.value)===f});}m.resolve(d);}}};var Ne=Ie(de());var Q=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),ye=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()).nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),Rt=ye.superRefine((r,e)=>{r.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Pe=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),G=Pe.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),Z=Pe.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:Rt});zod.z.union([Z,G]);var ze=Q.omit({resource:true}),pe=G.omit({id:true,type:true,resource:true,procedure:true}),fe=Z.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([fe,pe]);var me=r=>{if(r==null)return r;if(r==="null")return null;if(Array.isArray(r))return r.map(me);if(typeof r=="object"&&r.constructor===Object){let e={};for(let[t,n]of Object.entries(r))e[t]=me(n);return e}return r},Ve=r=>{let e=r.logger;return async t=>{var n;try{let i=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,a={headers:i,cookies:i.cookie?Ne.default.parse(i.cookie):{}},s=new URL(t.url),o=s.pathname.split("/"),c=s.searchParams,u=me(xt__default.default.parse(c.toString())),p=await((n=r.contextProvider)==null?void 0:n.call(r,{transport:"HTTP",headers:a.headers,cookies:a.cookies,queryParams:u}))??{};if(t.method==="GET"){let l=o[o.length-1],{success:h,data:m,error:d}=ze.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:d},{status:400});let R=await r.handleQuery({req:{...a,...m,type:"QUERY",resource:l,context:p,queryParams:u}});return !R||!R.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(R.data)}if(t.method==="POST")try{let l=o[o.length-1],h=o[o.length-2],m=t.body?await t.json():{},d;if(l==="insert"||l==="update"){let{success:f,data:y,error:g}=fe.safeParse(m);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:g},{status:400});d=y;}else {let{success:f,data:y,error:g}=pe.safeParse(m);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:g},{status:400});d=y;}let R=await r.handleMutation({req:{...a,type:"MUTATE",resource:h,input:d.payload,context:p,resourceId:d.resourceId,procedure:l==="insert"||l==="update"?l.toUpperCase():l,queryParams:{}}});return Response.json(R)}catch(l){return e.error("Error parsing mutation from the client:",l),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(i){return e.error("Unexpected error:",i),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var De=Ie(de());var K=zod.z.string(),vt=Q.extend({id:K,type:zod.z.literal("SUBSCRIBE")}),St=Q.extend({id:K,type:zod.z.literal("QUERY")}),_e=Z.extend({id:K}),wt=G.extend({id:K}),It=zod.z.union([wt,_e]),We=zod.z.union([vt,St,It]),Mt=zod.z.object({id:K,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),Lt=zod.z.object({id:K,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([Mt,Lt,_e]);zod.z.object({resource:zod.z.string(),data:zod.z.array(ye)});var ke=r=>{let e={},t=r.logger;return (n,i)=>{var l;let a=h=>{n.send(JSON.stringify(h));},s=Y(),o=new Set,c={headers:i.headers,cookies:typeof i.headers.cookie=="string"?De.default.parse(i.headers.cookie):{}},u=xt.parse(i.url.split("?")[1]),p=(l=r.contextProvider)==null?void 0:l.call(r,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,queryParams:u});e[s]=n,t.info("Client connected:",s),n.on("message",async h=>{var m;try{t.debug("Message received from the client:",h);let d=We.parse(JSON.parse(h.toString()));if(d.type==="SUBSCRIBE"){let R=await p??{},f=d.resource,y=r.router.routes[f],g;if((m=y==null?void 0:y.authorization)!=null&&m.read){let S=y.authorization.read({ctx:R});g=typeof S=="object"?S:void 0;}o.add(r.subscribeToMutations(d,S=>{var v;!S.resourceId||!S.payload||!Object.keys(S.payload).length||(v=e[s])==null||v.send(JSON.stringify(S));},g));}else if(d.type==="QUERY"){let{resource:R}=d,f=await r.handleQuery({req:{...c,type:"QUERY",resource:R,context:await p??{},queryParams:u}});if(!f||!f.data)throw new Error("Invalid resource");a({id:d.id,type:"REPLY",data:{resource:R,data:(f.data??[]).map(y=>y.value)}});}else if(d.type==="MUTATE"){let{resource:R}=d;t.debug("Received mutation from client:",d);try{let f=await r.handleMutation({req:{...c,type:"MUTATE",resource:R,input:d.payload,context:{messageId:d.id,...await p??{}},resourceId:d.resourceId,procedure:d.procedure,queryParams:u}});d.procedure&&d.procedure!=="INSERT"&&d.procedure!=="UPDATE"&&a({id:d.id,type:"REPLY",data:f});}catch(f){a({id:d.id,type:"REJECT",resource:R,message:f.message}),t.error("Error parsing mutation from the client:",f);}}}catch(d){t.error("Error handling message from the client:",d);}}),n.on("close",()=>{t.info("Connection closed",s),delete e[s];for(let h of Array.from(o))h();});}};function Ke(r){let e=`${r.protocol}://${r.hostname}${r.url}`,t=new Headers;return Object.entries(r.headers).forEach(([n,i])=>{i&&t.set(n,Array.isArray(i)?i.join(","):i);}),new Request(e,{method:r.method,headers:t,body:r.body&&r.method!=="GET"?JSON.stringify(r.body):void 0})}var Ln=(r,e,t)=>{r.ws(`${(t==null?void 0:t.basePath)??""}/ws`,ke(e)),r.use(`${(t==null?void 0:t.basePath)??""}/`,(n,i)=>{Ve(e)(Ke(n)).then(s=>s.json().then(o=>i.status(s.status).send(o)));});};var he=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},$n=r=>he.create({...r}),jt=r=>({handler:e=>({inputValidator:r??zod.z.undefined(),handler:e})}),Te=class r{resourceSchema;middlewares;customMutations;authorization;constructor(e,t,n){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=n;}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new r(this.resourceSchema,e({mutation:jt}),this.authorization)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{var a,s;let i=(s=(a=this.authorization)==null?void 0:a.read)==null?void 0:s.call(a,{ctx:n.context});if(typeof i=="boolean"&&!i)throw new Error("Not authorized");return {data:await t.rawFind({resource:n.resource,commonWhere:D(n.where,typeof i=="object"?i:void 0),uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort})}})(e);handleMutation=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let a=this.customMutations[i.procedure];if(a){let s=a.inputValidator.parse(i.input);return i.input=s,a.handler({req:i,db:t})}else {if(i.procedure==="INSERT"||i.procedure==="UPDATE")return this.handleSet({req:i,db:t,operation:i.procedure,schema:n});throw new Error(`Unknown procedure: ${i.procedure}`)}})(e);handleSet=async({req:e,db:t,operation:n,schema:i})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&a)throw new Error("Resource already exists");if(n==="UPDATE"&&!a)throw new Error("Resource not found");return t.transaction(async({trx:s})=>{var p,l,h,m,d,R,f;let[o,c]=this.resourceSchema.mergeMutation("set",e.input,a);if(!c)throw new Error("Mutation rejected");if(n==="INSERT"){let y=await s.rawInsert(e.resource,e.resourceId,o,(p=e.context)==null?void 0:p.messageId),g=I(y);if(g.id=g.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let S=this.authorization.insert({ctx:e.context,value:g});if(typeof S=="boolean"){if(!S)throw new Error("Not authorized")}else {let v=B(S,e.resource,i),x=Object.keys(v).length>0?await s.rawFindById(e.resource,e.resourceId,v):y,b=I(x);if(b.id=b.id??e.resourceId,!C(b,S))throw new Error("Not authorized")}}return {data:y,acceptedValues:c}}if((m=(h=this.authorization)==null?void 0:h.update)!=null&&m.preMutation){let y=I(a);y.id=y.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:y});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let S=B(g,e.resource,i),v=Object.keys(S).length>0?await s.rawFindById(e.resource,e.resourceId,S):a,x=I(v);if(x.id=x.id??e.resourceId,!C(x,g))throw new Error("Not authorized")}}let u=await s.rawUpdate(e.resource,e.resourceId,o,(d=e.context)==null?void 0:d.messageId);if((f=(R=this.authorization)==null?void 0:R.update)!=null&&f.postMutation){let y=I(u);y.id=y.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:y});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let S=B(g,e.resource,i),v=Object.keys(S).length>0?await s.rawFindById(e.resource,e.resourceId,S):u,x=I(v);if(x.id=x.id??e.resourceId,!C(x,g))throw new Error("Not authorized")}}return {data:u,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),e)(t)}},ge=class r{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Te(e,void 0,t).use(...this.middlewares)}use(...e){return new r([...this.middlewares,...e])}static create(){return new r}},Pn=ge.create;var H=class{async insert(e,t){let n=new Date().toISOString();return I(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([i,a])=>[i,{value:a,_meta:{timestamp:n}}]))}))}async update(e,t,n){let i=new Date().toISOString(),{id:a,...s}=n;return I(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(s).map(([o,c])=>[o,{value:c,_meta:{timestamp:i}}]))}))}};function te(r,e,t,n){if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error("Resource not found");let a=n.$or,s=n.$and;return (a?t.or:t.and)(a?n.$or.map(o=>te(r,e,t,o)):s?n.$and.map(o=>te(r,e,t,o)):Object.entries(n).map(([o,c])=>{var u,p;if(i.fields[o])return (c==null?void 0:c.$eq)!==void 0?t(`${e}.${o}`,c.$eq===null?"is":"=",c.$eq):(c==null?void 0:c.$in)!==void 0?t(`${e}.${o}`,"in",c.$in):(c==null?void 0:c.$not)!==void 0?((u=c==null?void 0:c.$not)==null?void 0:u.$in)!==void 0?t(`${e}.${o}`,"not in",c.$not.$in):((p=c==null?void 0:c.$not)==null?void 0:p.$eq)!==void 0?t(`${e}.${o}`,c.$not.$eq===null?"is not":"!=",c.$not.$eq):t(`${e}.${o}`,c.$not===null?"is not":"!=",c.$not):(c==null?void 0:c.$gt)!==void 0?t(`${e}.${o}`,">",c.$gt):(c==null?void 0:c.$gte)!==void 0?t(`${e}.${o}`,">=",c.$gte):(c==null?void 0:c.$lt)!==void 0?t(`${e}.${o}`,"<",c.$lt):(c==null?void 0:c.$lte)!==void 0?t(`${e}.${o}`,"<=",c.$lte):t(`${e}.${o}`,c===null?"is":"=",c);if(i.relations[o]){let l=i.relations[o],h=l.entity.name;return l.type==="many"?t.exists(Re(r,h,t.selectFrom(h).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),c)):te(r,h,t,c)}return null}).filter(Boolean))}function ne(r,e,t,n){let i=r[e];if(!i)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let a of n.$and)t=ne(r,e,t,a);return t}else if(n.$or){for(let a of n.$or)t=ne(r,e,t,a);return t}for(let[a,s]of Object.entries(n)){if(!i.relations[a])continue;let o=i.relations[a],c=o.entity.name,u=o.type==="one"?"id":o.foreignColumn,p=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(c,`${c}.${u}`,`${e}.${p}`),s instanceof Object&&!Array.isArray(s)&&s!==null&&(t=ne(r,c,t,s));}return t}function Re(r,e,t,n){return !n||Object.keys(n).length===0?t:(t=ne(r,e,t,n),t.where(i=>te(r,e,i,n)))}function re(r,e,t,n){if(!n)return t;if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(n)){if(!i.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let s=i.relations[a],o=s.entity.name,c=n[a],u=s.type==="one"?"id":s.foreignColumn,p=s.type==="one"?s.relationalColumn:"id",l=s.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom,h=typeof c=="object"&&c!==null;t=t.select(m=>{let d=m.selectFrom(o).selectAll(o).whereRef(`${o}.${u}`,"=",`${e}.${p}`).select(R=>postgres.jsonObjectFrom(R.selectFrom(`${o}_meta`).selectAll(`${o}_meta`).whereRef(`${o}_meta.id`,"=",`${o}.id`)).as("_meta"));return h&&(d=re(r,o,d,c)),l(d).as(a)});}return t}var Be="42701",be=class r extends H{db;schema;logger;server;mutationStack=[];constructor(e,t,n,i){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.schema=t,this.logger=n,this.server=i,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,n){var a;this.schema=e,this.logger=t,this.server=n;let i=await this.db.introspection.getTables();for(let[s,o]of Object.entries(e)){let c=i.find(l=>l.name===s);c||await this.db.schema.createTable(s).ifNotExists().execute();let u=`${s}_meta`,p=i.find(l=>l.name===u);p||await this.db.schema.createTable(u).ifNotExists().execute();for(let[l,h]of Object.entries(o.fields)){let m=c==null?void 0:c.columns.find(f=>f.name===l),d=h.getStorageFieldType();m?m.dataType!==d.type&&((a=this.logger)==null||a.warn("Column type mismatch:",l,"expected to have type:",d.type,"but has type:",m.dataType)):(await this.db.schema.alterTable(s).addColumn(l,d.type,f=>{let y=f;return d.unique&&(y=y.unique()),d.nullable||(y=y.notNull()),d.references&&(y=y.references(d.references)),d.primary&&(y=y.primaryKey()),d.default!==void 0&&(y=y.defaultTo(d.default)),y}).execute().catch(f=>{var y;if(f.code!==Be)throw (y=this.logger)==null||y.error("Error adding column",l,f),f}),d.index&&await this.db.schema.createIndex(`${s}_${l}_index`).on(s).column(l).execute().catch(()=>{})),(p==null?void 0:p.columns.find(f=>f.name===l))||await this.db.schema.alterTable(u).addColumn(l,"varchar",f=>{let y=f;return d.primary&&(y=y.primaryKey().references(`${s}.${l}`)),y}).execute().catch(f=>{var y;if(f.code!==Be)throw (y=this.logger)==null||y.error("Error adding meta column",l,f),f});}}}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let i=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>postgres.jsonObjectFrom(s.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));i=re(this.schema,e,i,n);let a=await i.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t,n){let i=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(i)return I(i)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:i,limit:a,sort:s}=e,o=this.db.selectFrom(t).selectAll(t).select(u=>postgres.jsonObjectFrom(u.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));o=Re(this.schema,t,o,n),o=re(this.schema,t,o,i),a!==void 0&&(o=o.limit(a)),s!==void 0&&s.forEach(u=>{o=o.orderBy(u.key,u.direction);});let c=await o.execute();return c.length===0?[]:c.map(u=>this.convertToMaterializedLiveType(u))}async find(e,t){return (await this.get({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort})).map(i=>I(i))}async rawInsert(e,t,n,i){var c;let a={},s={};for(let[u,p]of Object.entries(n.value)){let l=(c=p._meta)==null?void 0:c.timestamp;l&&(a[u]=p.value,s[u]=l);}await this.db.insertInto(e).values({...a,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...s,id:t}).execute();});let o=this.buildMutation(e,t,"INSERT",n,i);return o&&this.trackMutation(o,n),n}async rawUpdate(e,t,n,i){var c;let a={},s={};for(let[u,p]of Object.entries(n.value)){let l=(c=p._meta)==null?void 0:c.timestamp;l&&(a[u]=p.value,s[u]=l);}await Promise.all([this.db.updateTable(e).set(a).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...s,id:t}).onConflict(u=>u.column("id").doUpdateSet(s)).execute()]);let o=this.buildMutation(e,t,"UPDATE",n,i);return o&&this.trackMutation(o,n),n}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let a=Math.random().toString(36).substring(2,15),s=this.mutationStack,o=[];this.mutationStack=o;let c=await this.db.savepoint(a).execute();try{return await e({trx:this,commit:async()=>{await c.releaseSavepoint(a).execute(),s.push(...o);},rollback:async()=>{await c.rollbackToSavepoint(a).execute(),o.length=0;}}).then(u=>c.isCommitted||c.isRolledBack?u:c.releaseSavepoint(a).execute().then(()=>(s.push(...o),u)))}catch(u){throw await c.rollbackToSavepoint(a).execute().catch(()=>{}),o.length=0,u}finally{this.mutationStack=s;}}let t=[],n=this.mutationStack;this.mutationStack=t;let i=await this.db.startTransaction().execute();try{let a=new r(i,this.schema,this.logger,this.server);return a.mutationStack=t,await e({trx:a,commit:async()=>{await i.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await i.rollback().execute(),t.length=0;}}).then(s=>i.isCommitted||i.isRolledBack?s:i.commit().execute().then(()=>(this.notifyMutations(t),s)))}catch(a){throw await i.rollback().execute(),t.length=0,a}finally{this.mutationStack=n;}}get internalDB(){return this.db}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[n,i])=>{var a,s,o;return n==="_meta"||(n==="id"?t[n]={value:i}:Array.isArray(i)?t[n]={value:i.map(c=>this.convertToMaterializedLiveType(c)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[n]}}:typeof i=="object"&&i!==null&&!(i instanceof Date)?t[n]={...this.convertToMaterializedLiveType(i),_meta:{timestamp:(s=e==null?void 0:e._meta)==null?void 0:s[n]}}:t[n]={value:i,_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[n]}}),t},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",i=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",s=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&i||a&&s}buildMutation(e,t,n,i,a){var o;let s={};for(let[c,u]of Object.entries(i.value)){if(c==="id")continue;let p=(o=u._meta)==null?void 0:o.timestamp;p&&(s[c]={value:u.value,_meta:{timestamp:p}});}return Object.keys(s).length===0?null:{id:a??Y(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:s}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let n=e;for(let i of n)this.server.notifySubscribers(i,t);}else {let n=e;for(let{mutation:i,entityData:a}of n)this.server.notifySubscribers(i,a);}}};var xe=class r{router;storage;schema;middlewares=new Set;logger;contextProvider;mutationSubscriptions=new Set;collectionSubscriptions=new Map;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=Ee({level:e.logLevel??z.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider;}static create(e){return new r(e)}handleQuery(e){let t=new X(this.storage);return this.wrapInMiddlewares(async n=>{var m,d,R,f,y,g,S;let i=Qe(n,this.schema,{stepId:"query",collectionName:n.resource,included:Object.keys(n.include??{})}),a={headers:n.headers,cookies:n.cookies,queryParams:n.queryParams,context:n.context},s={};for(let v=0;v<i.length;v++){let x=i[v],b=this.router.routes[x.resource];if(!b)throw new Error("Invalid resource");let A;if(x.getWhere&&x.referenceGetter){let w=x.referenceGetter(s);A=[];for(let M=0;M<w.length;M++)A.push(x.getWhere(w[M]));}else A=[void 0];let O=s[x.prevStepId??""],j=[];if(O)for(let w=0;w<O.length;w++){let M=O[w],N=((m=M==null?void 0:M.result)==null?void 0:m.data)??[];for(let $=0;$<N.length;$++){let ie=N[$],Se=(R=(d=ie==null?void 0:ie.value)==null?void 0:d.id)==null?void 0:R.value;Se&&j.push(Se);}}let P=[];for(let w=0;w<A.length;w++){let M=A[w],N=j[w];P.push((async()=>{let $=await b.handleQuery({req:{type:"QUERY",...x,...a,where:x.where,relationalWhere:M},batcher:t});return {includedBy:N,result:$}})());}let E=await Promise.allSettled(P),F=[];for(let w=0;w<E.length;w++){let M=E[w];M.status==="fulfilled"&&F.push(M.value);}s[x.stepId]=F;}let o=new Map,c=0;for(let v in s){let x=s[v],b=i[c];c++;for(let A=0;A<x.length;A++){let O=x[A],j=O.result.data;for(let P=0;P<j.length;P++){let E=j[P],F=(y=(f=E==null?void 0:E.value)==null?void 0:f.id)==null?void 0:y.value;if(!F)continue;let w=`${v}.${F}`,M=[];v!=="query"&&O.includedBy&&(M=[`${b.prevStepId}.${O.includedBy}`]);let N=o.get(w);if(N)for(let $=0;$<M.length;$++)N.includedBy.add(M[$]);else o.set(w,{data:E,includedBy:new Set(M),path:v.split(".").slice(-1)[0],isMany:b.isMany??false,collectionName:b.collectionName,included:b.included});}}}let u=Object.fromEntries(o),p={data:[]},l=Object.keys(u);for(let v=l.length-1;v>=0;v--){let x=l[v],b=u[x],A=b.path;if(A==="query"&&p.data.push(b.data),b.included.length)for(let O=0;O<b.included.length;O++){let j=b.included[O];b.data.value[j]??=((S=(g=this.schema[b.collectionName])==null?void 0:g.relations[j])==null?void 0:S.type)==="many"?{value:[]}:{value:null};}if(b.includedBy.size>0){let O=Array.from(b.includedBy);for(let j=0;j<O.length;j++){let P=O[j],E=u[P];E&&(b.isMany?(E.data.value[A]??={value:[]},E.data.value[A].value.push(b.data)):E.data.value[A]=b.data);}}}return p})(e.req)}async handleMutation(e){let t=await this.wrapInMiddlewares(async n=>{let i=this.router.routes[n.resource];if(!i)throw new Error("Invalid resource");return i.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req);if(t&&e.req.type==="MUTATE"&&t.acceptedValues&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&e.req.resourceId){let i=t.acceptedValues??{},a=e.req,s=a.resourceId;Object.keys(i).length&&s&&this.mutationSubscriptions.forEach(o=>{o({id:e.req.context.messageId,type:"MUTATE",resource:a.resource,payload:i,resourceId:s,procedure:a.procedure});});}return t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}subscribeToMutations(e,t,n){let i=e.resource,a={query:e,authorizationWhere:n},s=je(a),o=this.collectionSubscriptions.get(i);o||(o=new Map,this.collectionSubscriptions.set(i,o));let c=o.get(s);return c?(c.callbacks.add(t),n!==void 0&&(c.authorizationWhere=n)):o.set(s,{callbacks:new Set([t]),...a}),()=>{var p,l;let u=this.collectionSubscriptions.get(i);u&&((p=u.get(s))==null||p.callbacks.delete(t),((l=u.get(s))==null?void 0:l.callbacks.size)===0&&u.delete(s));}}notifySubscribers(e,t){let n=e.resource,i=this.collectionSubscriptions.get(n);if(i&&t)for(let a of Array.from(i.values())){let s=ve(a.query.where,this.schema[n]),o=D(s,a.authorizationWhere),c=I(t);if(!c)continue;(e.resourceId&&typeof c=="object"&&c!==null&&!("id"in c)||e.resourceId&&typeof c=="object"&&c!==null&&c.id!==e.resourceId)&&(c.id=e.resourceId);let u=Object.keys(o).length>0,p=true;u&&(p=C(c,o)),p&&a.callbacks.forEach(l=>{var h;try{l(e);}catch(m){(h=this.logger)==null||h.error(`Error in mutation subscription for resource ${n}:`,m);}});}}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),e)(t)}},er=xe.create;function Qe(r,e,t){let{include:n,where:i,...a}=r,{stepId:s}=t,o=[{...a,...t,where:i}];if(n&&typeof n=="object"&&Object.keys(n).length>0){let c=e[a.resource];if(!c)throw new Error(`Resource ${a.resource} not found`);o.push(...Object.entries(n).flatMap(([u,p])=>{let l=c.relations[u];if(!l)throw new Error(`Relation ${u} not found for resource ${a.resource}`);let h=l.entity.name;return Qe({...a,resource:h,include:p},e,{getWhere:l.type==="one"?m=>({id:m}):m=>({[l.foreignColumn]:m}),referenceGetter:m=>m[s].flatMap(d=>{let R=d.result.data??[];return l.type==="one"?R.map(f=>{var y,g;return (g=(y=f.value)==null?void 0:y[l.relationalColumn])==null?void 0:g.value}).filter(f=>f!==void 0):R.map(f=>{var y,g;return (g=(y=f.value)==null?void 0:y.id)==null?void 0:g.value}).filter(f=>f!==void 0)}),stepId:`${s}.${u}`,prevStepId:s,isMany:l.type==="many",collectionName:h,included:typeof p=="object"?Object.keys(p):[]})}));}return o}function ve(r,e){if(!r||!e||Object.keys(r).length===0)return r;if(r.$and){let n=r.$and.map(i=>ve(i,e)).filter(i=>!!i&&Object.keys(i).length>0);return n.length===0?void 0:n.length===1?n[0]:{$and:n}}if(r.$or){let n=r.$or.map(i=>ve(i,e)).filter(i=>!!i&&Object.keys(i).length>0);return n.length===0?void 0:n.length===1?n[0]:{$or:n}}let t={};for(let[n,i]of Object.entries(r))e.fields[n]&&(t[n]=i);return Object.keys(t).length>0?t:void 0}
|
|
2
|
-
exports.Route=
|
|
1
|
+
'use strict';var V=require('crypto'),jsXxhash=require('js-xxhash'),dt=require('qs'),zod=require('zod'),kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var V__default=/*#__PURE__*/_interopDefault(V);var dt__default=/*#__PURE__*/_interopDefault(dt);var ke=Object.create;var me=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var Fe=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Ke=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of De(e))!Ve.call(i,r)&&r!==t&&me(i,r,{get:()=>e[r],enumerable:!(n=ze(e,r))||n.enumerable});return i};var ge=(i,e,t)=>(t=i!=null?ke(_e(i)):{},Ke(me(t,"default",{value:i,enumerable:true}),i));var se=Fe(U=>{Object.defineProperty(U,"__esModule",{value:true});U.parse=st;U.serialize=at;var Xe=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,et=/^[\u0021-\u003A\u003C-\u007E]*$/,tt=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,rt=/^[\u0020-\u003A\u003D-\u007E]*$/,nt=Object.prototype.toString,it=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function st(i,e){let t=new it,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||ot,s=0;do{let o=i.indexOf("=",s);if(o===-1)break;let a=i.indexOf(";",s),u=a===-1?n:a;if(o>u){s=i.lastIndexOf(";",o-1)+1;continue}let l=Se(i,s,o),p=we(i,o,l),c=i.slice(l,p);if(t[c]===void 0){let y=Se(i,o+1,u),d=we(i,u,y),f=r(i.slice(y,d));t[c]=f;}s=u+1;}while(s<n);return t}function Se(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function we(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function at(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Xe.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!et.test(r))throw new TypeError(`argument val is invalid: ${e}`);let s=i+"="+r;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge;}if(t.domain){if(!tt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain;}if(t.path){if(!rt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path;}if(t.expires){if(!ut(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":s+="; Priority=Low";break;case "medium":s+="; Priority=Medium";break;case "high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":s+="; SameSite=Strict";break;case "lax":s+="; SameSite=Lax";break;case "none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}function ot(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function ut(i){return nt.call(i)==="[object Date]"}});var S=i=>i?Array.isArray(i.value)?i.value.map(t=>S(t)):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([t,n])=>Array.isArray(n)?[t,n.map(r=>S(r))]:[t,S(n)])):void 0;var be="0123456789ABCDEFGHJKMNPQRSTVWXYZ",k=32;var We=16,Re=10,Te=0xffffffffffff;var A;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})(A||(A={}));var E=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Be(i){let e=Math.floor(i()*k);return e===k&&(e=k-1),be.charAt(e)}function Ue(i){var n;let e=He(),t=e&&(e.crypto||e.msCrypto)||(typeof V__default.default<"u"?V__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=V__default.default)!=null&&n.randomBytes)return ()=>V__default.default.randomBytes(1).readUInt8()/255;throw new E(A.PRNGDetectFailure,"Failed to find a reliable PRNG")}function He(){return Je()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ge(i,e){let t="";for(;i>0;i--)t=Be(e)+t;return t}function Ze(i,e=Re){if(isNaN(i))throw new E(A.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>Te)throw new E(A.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Te}: ${i}`);if(i<0)throw new E(A.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new E(A.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%k,n=be.charAt(t)+n,i=(i-t)/k;return n}function Je(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ve(i,e){let t=Ue(),n=Date.now();return Ze(n,Re)+Ge(We,t)}var K=()=>ve().toLowerCase(),F=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:F(n)}return F(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:F(r)}throw n}}}),re=i=>i instanceof Promise?i:F(i);var P=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var W=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((s,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...r}),u={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:s,reject:o};this.queue.has(a)||this.queue.set(a,[]);let l=this.queue.get(a);l&&l.push(u),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var y;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:s,sort:o}=t,a=e.length===1?t.limit:void 0,u=e.map(d=>d.uniqueWhere).filter(d=>d!==void 0),l=r,p=(y=Object.entries(u[0]??{})[0])==null?void 0:y[0];if(u.length>0){let d=u.map(f=>f[p]).filter(f=>f!=null);d.length>0&&(l=P(r,{[p]:{$in:d}}));}let c=await this.storage.get({resource:n,where:l,include:s,sort:o,limit:a});for(let d of e){let f=c;if(d.uniqueWhere){let[m,g]=Object.entries(d.uniqueWhere)[0];f=c.filter(h=>{var T;return ((T=h.value[m])==null?void 0:T.value)===g});}d.resolve(f);}}};var j=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),N=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let s=o=>{o.$and?o.$and.forEach(s):o.$or?o.$or.forEach(s):Object.entries(o).forEach(([a,u])=>{var l;if((l=r.relations)!=null&&l[a]&&(n[a]=true,typeof u=="object"&&u!==null&&!Array.isArray(u))){let p=N(u,r.relations[a].entity.name,t);Object.keys(p).length>0&&(n[a]=p);}});};return s(i),n},I=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(o=>I(i,o,t));if(n==="$or")return r.some(o=>I(i,o,t));let s=(r==null?void 0:r.$eq)!==void 0?r==null?void 0:r.$eq:r;if(typeof r=="object"&&r!==null&&(r==null?void 0:r.$eq)===void 0){if(r.$in!==void 0){let a=i[n];return a===void 0?false:t?!r.$in.includes(a):r.$in.includes(a)}if(r.$not!==void 0&&!t)return I(i,{[n]:r.$not},true);if(r.$gt!==void 0){let a=i[n];return typeof a!="number"?false:t?a<=r.$gt:a>r.$gt}if(r.$gte!==void 0){let a=i[n];return typeof a!="number"?false:t?a<r.$gte:a>=r.$gte}if(r.$lt!==void 0){let a=i[n];return typeof a!="number"?false:t?a>=r.$lt:a<r.$lt}if(r.$lte!==void 0){let a=i[n];return typeof a!="number"?false:t?a>r.$lte:a<=r.$lte}let o=i[n];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?t?!o.some(a=>I(a,r,false)):o.some(a=>I(a,r,false)):I(o,r,t)}return t?i[n]!==s:i[n]===s}),L={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},ne=class{level;prefix;constructor(e={}){this.level=e.level??L.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=L.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=L.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=L.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=L.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=L.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},xe=i=>new ne(i);function ie(i){return j({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}var B=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,s]of Object.entries(n.relations))s.type==="one"&&s.relationalColumn&&t.set(String(s.relationalColumn),{relationName:r,targetResource:s.entity.name});return t}ensureObjectNode(e,t,n){let r=this.objectNodes.get(e);return r?n&&r.matchedQueries.add(n):(r={id:e,type:t,matchedQueries:new Set(n?[n]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,r)),r}storeRelation(e,t,n,r){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.set(n,t),o&&r){let a=o.referencedByObjects.get(r);a||(a=new Set,o.referencedByObjects.set(r,a)),a.add(e);}}removeRelation(e,t,n,r){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.delete(n),o&&r){let a=o.referencedByObjects.get(r);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let s=r.relations[n];if(!s)return;let o=this.schema[t];if(o!=null&&o.relations){if(s.type==="many"&&s.foreignColumn){for(let[a,u]of Object.entries(o.relations))if(u.entity.name===e&&u.type==="one"&&u.relationalColumn===s.foreignColumn)return a}if(s.type==="one"&&s.relationalColumn){for(let[a,u]of Object.entries(o.relations))if(u.entity.name===e&&u.type==="many"&&u.foreignColumn===s.relationalColumn)return a}}}updateRelationsFromMutation(e,t,n,r){let s=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:u,targetResource:l}]of Array.from(s)){if(!(r&&a in r))continue;let c=this.getInverseRelationName(e,l,u),y=o.referencesObjects.get(u),d=n[a];y!==d&&(y&&this.removeRelation(t,y,u,c),d&&(this.ensureObjectNode(d,l),this.storeRelation(t,d,u,c)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new W(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),s={},o=[];for(let a of r){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let u=ie(a),l=s[a.stepPath.at(-2)??""],p=a.stepPath.at(-1)??"",c=this.queryNodes.get(u);if(c)c.subscriptions.add(t);else if(c={hash:u,queryStep:a,relationName:p,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:l,childQueries:new Set},this.queryNodes.set(c.hash,c),l){let y=this.queryNodes.get(l);y&&y.childQueries.add(c.hash);}s[p]=u,o.push(()=>{let y=this.queryNodes.get(u);y&&(y.subscriptions.delete(t),y.subscriptions.size===0&&this.queryNodes.delete(u));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var g;let{query:t,stepPath:n=[],context:r={},parentResource:s}=e,{include:o}=t,a=n.length===0,u=n.at(-1),l,p,c;if(!a&&s&&u){let h=this.schema[s],T=(g=h==null?void 0:h.relations)==null?void 0:g[u];T&&(c=T.type==="many",T.type==="one"?(l=b=>({id:b}),p=b=>b.map(v=>{var x,M;return (M=(x=v.value)==null?void 0:x[T.relationalColumn])==null?void 0:M.value}).filter(v=>v!==void 0)):(l=b=>({[T.foreignColumn]:b}),p=b=>b.map(v=>{var x,M;return (M=(x=v.value)==null?void 0:x.id)==null?void 0:M.value}).filter(v=>v!==void 0)));}let{include:y,...d}=t,m=[this.router.incrementQueryStep({query:d,stepPath:[...n],getWhere:l,referenceGetter:p,isMany:c,relationName:u},r)];if(o&&typeof o=="object"&&Object.keys(o).length>0){let h=this.schema[t.resource];if(!h)throw new Error(`Resource ${t.resource} not found`);m.push(...Object.entries(o).flatMap(([T,b])=>{let v=h.relations[T];if(!v)throw new Error(`Relation ${T} not found for resource ${t.resource}`);let x=v.entity.name;return this.breakdownQuery({query:{resource:x,include:typeof b=="object"?b:void 0},stepPath:[...n,T],context:r,parentResource:t.resource})}));}return m}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(s=>s.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(s=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",s.length),n[e[0].stepPath.join(".")]=[{data:s}];});for(let s=1;s<e.length;s++){let o=e[s],a=o.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var l,p;let u=n[a];if(!u){n[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let c=new Map;for(let f of u)for(let m of f.data){let g=(p=(l=m==null?void 0:m.value)==null?void 0:l.id)==null?void 0:p.value;if(!g)continue;let T=o.referenceGetter([m])[0];if(T){c.has(T)||c.set(T,new Set);let b=c.get(T);b&&b.add(g);}}let y=Array.from(c.keys());if(y.length===0){n[o.stepPath.join(".")]=[];return}let d=[];for(let f of y){let m=o.getWhere(f),g={...o,relationalWhere:m},h=await this.resolveStep(g,t),T=c.get(f);if(T)for(let b of Array.from(T))d.push({includedBy:b,data:h});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",d.reduce((f,m)=>f+m.data.length,0)),n[o.stepPath.join(".")]=d;}else {let c=await this.resolveStep(o,t);n[o.stepPath.join(".")]=[{data:c}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var o,a,u,l,p;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let n=new Map;for(let c of e){let y=c.stepPath.join("."),d=t[y]??[],f=Object.keys(c.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${y}"`,{resource:c.query.resource,includedRelations:f,resultGroups:d.length,isMany:c.isMany,relationName:c.relationName});for(let m of d){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${y}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let g of m.data){let h=(a=(o=g==null?void 0:g.value)==null?void 0:o.id)==null?void 0:a.value;if(!h){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${y}"`);continue}let T=y?`${y}.${h}`:h,b=[];if(c.stepPath.length>0&&m.includedBy){let x=c.stepPath.slice(0,-1).join(".");b=[x?`${x}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${T}" has parent keys:`,b,{stepPath:y,parentStepPath:x,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${T}" (no parent)`);let v=n.get(T);if(v){this.logger.debug(`[QueryEngine] assembleResults: Entity "${T}" already exists, adding parent keys:`,b);for(let x of b)v.includedBy.add(x);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${T}"`,{resource:c.query.resource,path:c.stepPath.at(-1)??"",isMany:c.isMany??false,relationName:c.relationName,includedRelations:f,parentKeys:b}),n.set(T,{data:g,includedBy:new Set(b),path:c.stepPath.at(-1)??"",isMany:c.isMany??false,relationName:c.relationName,resourceName:c.query.resource,includedRelations:f});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),s=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let c=r.length-1;c>=0;c--){let[y,d]=r[c],f=this.schema[d.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${y}"`,{resource:d.resourceName,path:d.path,isMany:d.isMany,relationName:d.relationName,includedRelations:d.includedRelations,parentKeys:Array.from(d.includedBy)});for(let m of d.includedRelations){let g=(l=(u=f==null?void 0:f.relations)==null?void 0:u[m])==null?void 0:l.type,h=!!d.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${y}"`,{relationType:g,hasRelation:h,resourceHasRelation:!!((p=f==null?void 0:f.relations)!=null&&p[m])}),d.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${y}"`,d.data.value[m]);else {let T=g==="many"?{value:[]}:{value:null};d.data.value[m]=T,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${y}" with`,T);}}if(d.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${y}" to resultData`),s.push(d.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to ${d.includedBy.size} parent(s)`);for(let m of Array.from(d.includedBy)){let g=n.get(m);if(!g){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${y}"`);continue}let h=d.relationName??d.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to parent "${m}" via relation "${h}"`,{isMany:d.isMany,parentHasRelation:!!g.data.value[h]}),d.isMany?(g.data.value[h]??={value:[]},g.data.value[h].value.push(d.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${y}" to many relation "${h}" on parent "${m}"`,{arrayLength:g.data.value[h].value.length})):(g.data.value[h]=d.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${h}" on parent "${m}" to "${y}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${s.length} root items`),s}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:n,relationalWhere:r}=e,s=n.where&&r?P(n.where,r):r??n.where,o=s?{...n,where:s}:n;return re(this.router.get(o,t)).then(a=>(this.loadStepResults(e,a),a))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=ie(e),r=this.queryNodes.get(n),s=e.query.resource;if(!r)return;let o=this.getRelationalColumns(s);for(let a of t){let u=S(a),l=u.id;this.ensureObjectNode(l,s,n),r.trackedObjects.add(l);for(let[p,{relationName:c,targetResource:y}]of Array.from(o)){let d=u[p];if(d){this.ensureObjectNode(d,y);let f=this.getInverseRelationName(s,y,c);this.storeRelation(l,d,c,f);}}this.loadNestedRelations(s,l,u),this.logger.debug("[QueryEngine] Loaded nested relations for",l);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[s,o]of Object.entries(r.relations)){let a=n[s];if(!a)continue;let u=o.entity.name,l=this.getInverseRelationName(e,u,s);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,u),this.storeRelation(t,a.id,s,l),this.loadNestedRelations(u,a.id,a));else if(o.type==="many"&&Array.isArray(a)){for(let p of a)if(p&&typeof p=="object"&&p.id){this.ensureObjectNode(p.id,u);let c=this.getInverseRelationName(u,e,s);c&&this.storeRelation(p.id,t,c,s),this.loadNestedRelations(u,p.id,p);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let s=this.queryNodes.get(r);if(!s||!s.relationName)continue;let o=this.buildIncludeFromChildQueries(r);n[s.relationName]=Object.keys(o).length>0?o:true;}return n}sendInsertsForTree(e,t,n){var a,u;let r=(u=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:u.value;if(!r)return;let s={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let l of Array.from(e.subscriptions))try{l(s);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:p,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let l of Array.from(e.childQueries)){let p=this.queryNodes.get(l);if(!p||!p.relationName)continue;let c=p.relationName,y=p.queryStep.query.resource,d=t.value[c];if(!d)continue;let f=d.value;if(Array.isArray(f))for(let m of f)this.sendInsertsForTree(p,m,y);else f&&typeof f=="object"&&this.sendInsertsForTree(p,f,y);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=S(t);if(!n)return;let r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,r);let s=this.getRelationalColumns(e.resource);for(let[a,{relationName:u,targetResource:l}]of Array.from(s)){let p=n[a];if(p){this.ensureObjectNode(p,l);let c=this.getInverseRelationName(e.resource,l,u);this.storeRelation(e.resourceId,p,u,c);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(a=>{for(let u of a){let l=this.queryNodes.get(u);if(l){l.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(u);for(let p of Array.from(l.subscriptions))try{p(e);}catch(c){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:c,queryHash:l.hash,resource:e.resource,resourceId:e.resourceId,stepPath:l.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let n=S(t);if(!n)return;let r=this.objectNodes.get(e.resourceId),s=new Set((r==null?void 0:r.matchedQueries)??[]);r||(r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,r)),this.updateRelationsFromMutation(e.resource,e.resourceId,n,e.payload),this.getMatchingQueries(e,n).then(o=>{let a=new Set(o),u=[],l=[],p=[];for(let y of o)s.has(y)?p.push(y):u.push(y);for(let y of Array.from(s))a.has(y)||l.push(y);for(let y of u){let d=this.queryNodes.get(y);d&&d.trackedObjects.add(e.resourceId);}for(let y of l){let d=this.queryNodes.get(y);d&&d.trackedObjects.delete(e.resourceId);}let c=this.objectNodes.get(e.resourceId);if(c){for(let y of u)c.matchedQueries.add(y);for(let y of l)c.matchedQueries.delete(y);}for(let y of [...l,...p]){let d=this.queryNodes.get(y);if(d)for(let f of Array.from(d.subscriptions))try{f(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:d.hash,resource:e.resource,resourceId:e.resourceId,stepPath:d.queryStep.stepPath.join(".")});}}if(u.length>0)for(let y of u){let d=this.queryNodes.get(y);if(!d)continue;let f=this.buildIncludeFromChildQueries(y);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(d,m[0],e.resource);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?re([]):Promise.all(n.map(async r=>{let s=r.queryStep.query.where,o=r.queryStep.query.resource,a=e.resourceId,u=this.objectNodes.get(a);if(!u)return {hash:r.hash,matches:false};if(r.relationName){let d=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=d==null?void 0:d.queryStep.query.resource,m=f?this.getInverseRelationName(f,o,r.relationName):void 0,g=m?u.referencesObjects.get(m):void 0;if(!g)return {hash:r.hash,matches:false};let h=this.objectNodes.get(g);return !h||!d||!h.matchedQueries.has(d.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!s)return {hash:r.hash,matches:true};let l=N(s,o,this.schema),p=Object.keys(l).length>0;if(!p&&t!==void 0)return {hash:r.hash,matches:I(t,s)};let c=await this.storage.get({resource:o,where:{id:a},include:p?l:void 0});if(!c||c.length===0)return {hash:r.hash,matches:false};let y=S(c[0]);return y?{hash:r.hash,matches:I(y,s)}:{hash:r.hash,matches:false}})).then(r=>r.filter(s=>s.matches).map(s=>s.hash))}};var Le=ge(se());var q=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),ae=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.any().nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),ct=ae.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ie=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),z=Ie.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),D=Ie.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:ct});zod.z.union([D,z]);var Me=q.omit({resource:true}),oe=z.omit({id:true,type:true,resource:true,procedure:true}),ue=D.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([ue,oe]);var ce=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(ce);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=ce(n);return e}return i},je=i=>{let e=i.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,s={headers:r,cookies:r.cookie?Le.default.parse(r.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),u=o.searchParams,l=ce(dt__default.default.parse(u.toString())),p=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:s.headers,cookies:s.cookies,queryParams:l}))??{};if(t.method==="GET"){let c=a[a.length-1],{success:y,data:d,error:f}=Me.safeParse(l);if(!y)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:f},{status:400});let m=await i.handleQuery({req:{...s,...d,type:"QUERY",resource:c,context:p,queryParams:l}});return !m||!m.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(m.data)}if(t.method==="POST")try{let c=a[a.length-1],y=a[a.length-2],d=t.body?await t.json():{},f;if(c==="insert"||c==="update"){let{success:g,data:h,error:T}=ue.safeParse(d);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:T},{status:400});f=h;}else {let{success:g,data:h,error:T}=oe.safeParse(d);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:T},{status:400});f=h;}let m=await i.handleMutation({req:{...s,type:"MUTATE",resource:y,input:f.payload,context:p,resourceId:f.resourceId,procedure:c==="insert"||c==="update"?c.toUpperCase():c,queryParams:{}}});return Response.json(m)}catch(c){return e.error("Error parsing mutation from the client:",c),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var Ee=ge(se());var $=zod.z.string(),yt=q.extend({id:$,type:zod.z.literal("SUBSCRIBE")}),pt=q.extend({id:$,type:zod.z.literal("UNSUBSCRIBE")}),ft=q.extend({id:$,type:zod.z.literal("QUERY")}),Oe=D.extend({id:$}),ht=z.extend({id:$}),mt=zod.z.union([ht,Oe]),Ae=zod.z.union([yt,ft,mt,pt]),gt=zod.z.object({id:$,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),Tt=zod.z.object({id:$,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([gt,Tt,Oe]);zod.z.object({resource:zod.z.string(),data:zod.z.array(ae)});var Ne=i=>{let e={},t=i.logger;return (n,r)=>{var c;let s=y=>{n.send(JSON.stringify(y));},o=K(),a=new Map,u={headers:r.headers,cookies:typeof r.headers.cookie=="string"?Ee.default.parse(r.headers.cookie):{}},l=dt.parse(r.url.split("?")[1]),p=(c=i.contextProvider)==null?void 0:c.call(i,{transport:"WEBSOCKET",headers:u.headers,cookies:u.cookies,queryParams:l});e[o]=n,t.info("Client connected:",o),n.on("message",async y=>{try{t.debug("Message received from the client:",y);let d=Ae.parse(JSON.parse(y.toString()));if(d.type==="SUBSCRIBE"||d.type==="QUERY"){let{type:f,id:m,...g}=d,h=f==="SUBSCRIBE",T=await i.handleQuery({req:{...u,...g,type:"QUERY",context:await p??{},queryParams:l},subscription:h?b=>{var v;!b.resourceId||!b.payload||!Object.keys(b.payload).length||(v=e[o])==null||v.send(JSON.stringify(b));}:void 0});if(!T||!T.data)throw new Error("Invalid resource");h&&T.unsubscribe&&a.set(j(g),T.unsubscribe),s({id:m,type:"REPLY",data:{resource:g.resource,data:(T.data??[]).map(b=>b.value)}});}else if(d.type==="UNSUBSCRIBE"){let{type:f,id:m,...g}=d,h=a.get(j(g));h&&(h(),a.delete(j(g)));}else if(d.type==="MUTATE"){let{resource:f}=d;t.debug("Received mutation from client:",d);try{let m=await i.handleMutation({req:{...u,type:"MUTATE",resource:f,input:d.payload,context:{messageId:d.id,...await p??{}},resourceId:d.resourceId,procedure:d.procedure,queryParams:l}});d.procedure&&d.procedure!=="INSERT"&&d.procedure!=="UPDATE"&&s({id:d.id,type:"REPLY",data:m});}catch(m){s({id:d.id,type:"REJECT",resource:f,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(d){t.error("Error handling message from the client:",d);}}),n.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let y of Array.from(a.values()))y();});}};function $e(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Lr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Ne(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{je(e)($e(n)).then(o=>o.json().then(a=>r.status(o.status).send(a)));});};var le=class i{routes;constructor(e){this.routes=e.routes;}static create(e){return new i(e)}},Nr=i=>le.create({...i}),vt=i=>({handler:e=>({inputValidator:i??zod.z.undefined(),handler:e})}),de=class i{resourceSchema;middlewares;customMutations;authorization;constructor(e,t,n){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=n;}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new i(this.resourceSchema,e({mutation:vt}),this.authorization)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},s=j(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:s}})(e);handleMutation=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{if(!r.procedure)throw new Error("Procedure is required for mutations");let s=this.customMutations[r.procedure];if(s){let o=s.inputValidator.parse(r.input);return r.input=o,s.handler({req:r,db:t})}else {if(r.procedure==="INSERT"||r.procedure==="UPDATE")return this.handleSet({req:r,db:t,operation:r.procedure,schema:n});throw new Error(`Unknown procedure: ${r.procedure}`)}})(e);getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let s=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&s)throw new Error("Resource already exists");if(n==="UPDATE"&&!s)throw new Error("Resource not found");return t.transaction(async({trx:o})=>{var p,c,y,d,f,m,g;let[a,u]=this.resourceSchema.mergeMutation("set",e.input,s);if(!u)throw new Error("Mutation rejected");if(n==="INSERT"){let h=await o.rawInsert(e.resource,e.resourceId,a,(p=e.context)==null?void 0:p.messageId),T=S(h);if(T.id=T.id??e.resourceId,(c=this.authorization)!=null&&c.insert){let b=this.authorization.insert({ctx:e.context,value:T});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let v=N(b,e.resource,r),x=Object.keys(v).length>0?await o.rawFindById(e.resource,e.resourceId,v):h,M=S(x);if(M.id=M.id??e.resourceId,!I(M,b))throw new Error("Not authorized")}}return {data:h,acceptedValues:u}}if((d=(y=this.authorization)==null?void 0:y.update)!=null&&d.preMutation){let h=S(s);h.id=h.id??e.resourceId;let T=this.authorization.update.preMutation({ctx:e.context,value:h});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let b=N(T,e.resource,r),v=Object.keys(b).length>0?await o.rawFindById(e.resource,e.resourceId,b):s,x=S(v);if(x.id=x.id??e.resourceId,!I(x,T))throw new Error("Not authorized")}}let l=await o.rawUpdate(e.resource,e.resourceId,a,(f=e.context)==null?void 0:f.messageId);if((g=(m=this.authorization)==null?void 0:m.update)!=null&&g.postMutation){let h=S(l);h.id=h.id??e.resourceId;let T=this.authorization.update.postMutation({ctx:e.context,value:h});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let b=N(T,e.resource,r),v=Object.keys(b).length>0?await o.rawFindById(e.resource,e.resourceId,b):l,x=S(v);if(x.id=x.id??e.resourceId,!I(x,T))throw new Error("Not authorized")}}return {data:l,acceptedValues:u}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>s=>r({req:s,next:n}),e)(t)}},ye=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new de(e,void 0,t).use(...this.middlewares)}use(...e){return new i([...this.middlewares,...e])}static create(){return new i}},$r=ye.create;var _=class{async insert(e,t){let n=new Date().toISOString();return S(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([r,s])=>[r,{value:s,_meta:{timestamp:n}}]))}))}async update(e,t,n){let r=new Date().toISOString(),{id:s,...o}=n;return S(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([a,u])=>[a,{value:u,_meta:{timestamp:r}}]))}))}};function H(i,e,t,n){if(!i)throw new Error("Schema not initialized");let r=i[e];if(!r)throw new Error("Resource not found");let s=n.$or,o=n.$and;return (s?t.or:t.and)(s?n.$or.map(a=>H(i,e,t,a)):o?n.$and.map(a=>H(i,e,t,a)):Object.entries(n).map(([a,u])=>{var l,p;if(r.fields[a])return (u==null?void 0:u.$eq)!==void 0?t(`${e}.${a}`,u.$eq===null?"is":"=",u.$eq):(u==null?void 0:u.$in)!==void 0?t(`${e}.${a}`,"in",u.$in):(u==null?void 0:u.$not)!==void 0?((l=u==null?void 0:u.$not)==null?void 0:l.$in)!==void 0?t(`${e}.${a}`,"not in",u.$not.$in):((p=u==null?void 0:u.$not)==null?void 0:p.$eq)!==void 0?t(`${e}.${a}`,u.$not.$eq===null?"is not":"!=",u.$not.$eq):t(`${e}.${a}`,u.$not===null?"is not":"!=",u.$not):(u==null?void 0:u.$gt)!==void 0?t(`${e}.${a}`,">",u.$gt):(u==null?void 0:u.$gte)!==void 0?t(`${e}.${a}`,">=",u.$gte):(u==null?void 0:u.$lt)!==void 0?t(`${e}.${a}`,"<",u.$lt):(u==null?void 0:u.$lte)!==void 0?t(`${e}.${a}`,"<=",u.$lte):t(`${e}.${a}`,u===null?"is":"=",u);if(r.relations[a]){let c=r.relations[a],y=c.entity.name;return c.type==="many"?t.exists(pe(i,y,t.selectFrom(y).select("id").whereRef(c.foreignColumn,"=",`${e}.id`),u)):H(i,y,t,u)}return null}).filter(Boolean))}function G(i,e,t,n){let r=i[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let s of n.$and)t=G(i,e,t,s);return t}else if(n.$or){for(let s of n.$or)t=G(i,e,t,s);return t}for(let[s,o]of Object.entries(n)){if(!r.relations[s])continue;let a=r.relations[s],u=a.entity.name,l=a.type==="one"?"id":a.foreignColumn,p=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(u,`${u}.${l}`,`${e}.${p}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=G(i,u,t,o));}return t}function pe(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=G(i,e,t,n),t.where(r=>H(i,e,r,n)))}function Z(i,e,t,n){if(!n)return t;if(!i)throw new Error("Schema not initialized");let r=i[e];if(!r)throw new Error(`Resource not found: ${e}`);for(let s of Object.keys(n)){if(!r.relations[s])throw new Error(`Relation ${s} not found in resource ${e}`);let o=r.relations[s],a=o.entity.name,u=n[s],l=o.type==="one"?"id":o.foreignColumn,p=o.type==="one"?o.relationalColumn:"id",c=o.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom,y=typeof u=="object"&&u!==null;t=t.select(d=>{let f=d.selectFrom(a).selectAll(a).whereRef(`${a}.${l}`,"=",`${e}.${p}`).select(m=>postgres.jsonObjectFrom(m.selectFrom(`${a}_meta`).selectAll(`${a}_meta`).whereRef(`${a}_meta.id`,"=",`${a}.id`)).as("_meta"));return y&&(f=Z(i,a,f,u)),c(f).as(s)});}return t}var Qe="42701",fe=class i extends _{db;schema;logger;server;mutationStack=[];constructor(e,t,n,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.schema=t,this.logger=n,this.server=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,n){var s;this.schema=e,this.logger=t,this.server=n;let r=await this.db.introspection.getTables();for(let[o,a]of Object.entries(e)){let u=r.find(c=>c.name===o);u||await this.db.schema.createTable(o).ifNotExists().execute();let l=`${o}_meta`,p=r.find(c=>c.name===l);p||await this.db.schema.createTable(l).ifNotExists().execute();for(let[c,y]of Object.entries(a.fields)){let d=u==null?void 0:u.columns.find(g=>g.name===c),f=y.getStorageFieldType();d?d.dataType!==f.type&&((s=this.logger)==null||s.warn("Column type mismatch:",c,"expected to have type:",f.type,"but has type:",d.dataType)):(await this.db.schema.alterTable(o).addColumn(c,f.type,g=>{let h=g;return f.unique&&(h=h.unique()),f.nullable||(h=h.notNull()),f.references&&(h=h.references(f.references)),f.primary&&(h=h.primaryKey()),f.default!==void 0&&(h=h.defaultTo(f.default)),h}).execute().catch(g=>{var h;if(g.code!==Qe)throw (h=this.logger)==null||h.error("Error adding column",c,g),g}),f.index&&await this.db.schema.createIndex(`${o}_${c}_index`).on(o).column(c).execute().catch(()=>{})),p!=null&&p.columns.find(g=>g.name===c)||await this.db.schema.alterTable(l).addColumn(c,"varchar",g=>{let h=g;return f.primary&&(h=h.primaryKey().references(`${o}.${c}`)),h}).execute().catch(g=>{var h;if(g.code!==Qe)throw (h=this.logger)==null||h.error("Error adding meta column",c,g),g});}}}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(o=>postgres.jsonObjectFrom(o.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));r=Z(this.schema,e,r,n);let s=await r.executeTakeFirst();if(s)return this.convertToMaterializedLiveType(s)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return S(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:s,sort:o}=e,a=this.db.selectFrom(t).selectAll(t).select(l=>postgres.jsonObjectFrom(l.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));a=pe(this.schema,t,a,n),a=Z(this.schema,t,a,r),s!==void 0&&(a=a.limit(s)),o!==void 0&&o.forEach(l=>{a=a.orderBy(l.key,l.direction);});let u=await a.execute();return u.length===0?[]:u.map(l=>this.convertToMaterializedLiveType(l))}async find(e,t){return (await this.get({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort})).map(r=>S(r))}async rawInsert(e,t,n,r){var u;let s={},o={};for(let[l,p]of Object.entries(n.value)){let c=(u=p._meta)==null?void 0:u.timestamp;c&&(s[l]=p.value,o[l]=c);}await this.db.insertInto(e).values({...s,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...o,id:t}).execute();});let a=this.buildMutation(e,t,"INSERT",n,r);return a&&this.trackMutation(a,n),n}async rawUpdate(e,t,n,r){var u;let s={},o={};for(let[l,p]of Object.entries(n.value)){let c=(u=p._meta)==null?void 0:u.timestamp;c&&(s[l]=p.value,o[l]=c);}await Promise.all([this.db.updateTable(e).set(s).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...o,id:t}).onConflict(l=>l.column("id").doUpdateSet(o)).execute()]);let a=this.buildMutation(e,t,"UPDATE",n,r);if(a){let l=await this.rawFindById(e,t);l&&this.trackMutation(a,l);}return n}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let s=Math.random().toString(36).substring(2,15),o=this.mutationStack,a=[];this.mutationStack=a;let u=await this.db.savepoint(s).execute();try{return await e({trx:this,commit:async()=>{await u.releaseSavepoint(s).execute(),o.push(...a);},rollback:async()=>{await u.rollbackToSavepoint(s).execute(),a.length=0;}}).then(l=>u.isCommitted||u.isRolledBack?l:u.releaseSavepoint(s).execute().then(()=>(o.push(...a),l)))}catch(l){throw await u.rollbackToSavepoint(s).execute().catch(()=>{}),a.length=0,l}finally{this.mutationStack=o;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let s=new i(r,this.schema,this.logger,this.server);return s.mutationStack=t,await e({trx:s,commit:async()=>{await r.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(o=>r.isCommitted||r.isRolledBack?o:r.commit().execute().then(()=>(this.notifyMutations(t),o)))}catch(s){throw await r.rollback().execute(),t.length=0,s}finally{this.mutationStack=n;}}get internalDB(){return this.db}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[n,r])=>{var s,o,a;return n==="_meta"||(n==="id"?t[n]={value:r}:Array.isArray(r)?t[n]={value:r.map(u=>this.convertToMaterializedLiveType(u)),_meta:{timestamp:(s=e==null?void 0:e._meta)==null?void 0:s[n]}}:typeof r=="object"&&r!==null&&!(r instanceof Date)?t[n]={...this.convertToMaterializedLiveType(r),_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[n]}}:t[n]={value:r,_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[n]}}),t},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",r=typeof t.startTransaction=="function",s=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||s&&o}buildMutation(e,t,n,r,s){var a;let o={};for(let[u,l]of Object.entries(r.value)){if(u==="id")continue;let p=(a=l._meta)==null?void 0:a.timestamp;p&&(o[u]={value:l.value,_meta:{timestamp:p}});}return Object.keys(o).length===0?null:{id:s??K(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:o}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let n=e;for(let r of n)this.server.notifySubscribers(r,t);}else {let n=e;for(let{mutation:r,entityData:s}of n)this.server.notifySubscribers(r,s);}}};var he=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=xe({level:e.logLevel??L.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new B({router:{get:async(n,r)=>{var c;let{headers:s,cookies:o,queryParams:a,context:u}=(r==null?void 0:r.context)??{};if(!(r!=null&&r.batcher))throw new Error("Batcher is required");let l={...n,type:"QUERY",headers:s,cookies:o,queryParams:a,context:u},p=await((c=this.router.routes[n.resource])==null?void 0:c.handleQuery({req:l,batcher:r.batcher}));return (p==null?void 0:p.data)??[]},incrementQueryStep:(n,r={})=>{var a;let s=(a=this.router.routes[n.query.resource])==null?void 0:a.getAuthorizationClause({...n.query,type:"QUERY",headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context});if(typeof s=="boolean"&&!s)throw new Error("Not authorized");let o=P(n.query.where,typeof s=="object"?s:void 0);return {...n,query:{...n.query,where:o}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:s,context:o,...a}=t,u={headers:n,cookies:r,queryParams:s,context:o},l=e.subscription?this.queryEngine.subscribe(a,c=>{var y;(y=e.subscription)==null||y.call(e,c);},u):void 0;return {data:await this.queryEngine.get(a,{context:u}),unsubscribe:l}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}notifySubscribers(e,t){this.queryEngine.handleMutation(e,t);}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>s=>r({req:s,next:n}),e)(t)}},Yr=he.create;
|
|
2
|
+
exports.Route=de;exports.RouteFactory=ye;exports.Router=le;exports.SQLStorage=fe;exports.Server=he;exports.Storage=_;exports.expressAdapter=Lr;exports.routeFactory=$r;exports.router=Nr;exports.server=Yr;
|
package/dist/server.d.cts
CHANGED
|
@@ -30,7 +30,7 @@ declare const defaultMutationSchema: z.ZodObject<{
|
|
|
30
30
|
UPDATE: "UPDATE";
|
|
31
31
|
}>;
|
|
32
32
|
payload: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
33
|
-
value: z.ZodNullable<z.
|
|
33
|
+
value: z.ZodNullable<z.ZodAny>;
|
|
34
34
|
_meta: z.ZodOptional<z.ZodObject<{
|
|
35
35
|
timestamp: z.ZodNullable<z.ZodOptional<z.ZodString>>;
|
|
36
36
|
}, z.core.$strip>>;
|
|
@@ -40,7 +40,7 @@ type DefaultMutation = Omit<z.infer<typeof defaultMutationSchema>, "resourceId">
|
|
|
40
40
|
resourceId: string;
|
|
41
41
|
};
|
|
42
42
|
|
|
43
|
-
type
|
|
43
|
+
type PromiseOrSync<T> = T | Promise<T>;
|
|
44
44
|
|
|
45
45
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
46
46
|
/** biome-ignore-all lint/style/noNonNullAssertion: false positive */
|
|
@@ -60,6 +60,7 @@ declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof
|
|
|
60
60
|
type AnyRouter = Router<any>;
|
|
61
61
|
type QueryResult<TShape extends LiveObjectAny> = {
|
|
62
62
|
data: MaterializedLiveType<TShape>[];
|
|
63
|
+
unsubscribe?: () => void;
|
|
63
64
|
};
|
|
64
65
|
type MutationResult<TShape extends LiveObjectAny> = {
|
|
65
66
|
data: MaterializedLiveType<TShape>;
|
|
@@ -101,6 +102,7 @@ declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends M
|
|
|
101
102
|
withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
|
|
102
103
|
mutation: typeof mutationCreator;
|
|
103
104
|
}) => T): Route<TResourceSchema, TMiddleware, T>;
|
|
105
|
+
getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
|
|
104
106
|
private handleSet;
|
|
105
107
|
private wrapInMiddlewares;
|
|
106
108
|
}
|
|
@@ -114,10 +116,34 @@ declare class RouteFactory {
|
|
|
114
116
|
declare const routeFactory: typeof RouteFactory.create;
|
|
115
117
|
type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
|
|
116
118
|
|
|
117
|
-
/** biome-ignore-all lint/
|
|
119
|
+
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
120
|
+
|
|
121
|
+
declare class Batcher {
|
|
122
|
+
private storage;
|
|
123
|
+
private queue;
|
|
124
|
+
private scheduled;
|
|
125
|
+
constructor(storage: Storage);
|
|
126
|
+
rawFind<T extends LiveObjectAny>({ resource, commonWhere, uniqueWhere, ...rest }: {
|
|
127
|
+
resource: string;
|
|
128
|
+
commonWhere?: Record<string, any>;
|
|
129
|
+
uniqueWhere?: Record<string, any>;
|
|
130
|
+
include?: Record<string, any>;
|
|
131
|
+
limit?: number;
|
|
132
|
+
sort?: {
|
|
133
|
+
key: string;
|
|
134
|
+
direction: "asc" | "desc";
|
|
135
|
+
}[];
|
|
136
|
+
}): Promise<MaterializedLiveType<T>[]>;
|
|
137
|
+
private getBatchKey;
|
|
138
|
+
private processBatch;
|
|
139
|
+
private executeBatchedRequests;
|
|
140
|
+
}
|
|
118
141
|
|
|
119
142
|
interface DataSource {
|
|
120
|
-
get(query: RawQueryRequest
|
|
143
|
+
get(query: RawQueryRequest, extra?: {
|
|
144
|
+
context?: any;
|
|
145
|
+
batcher?: Batcher;
|
|
146
|
+
}): PromiseOrSync<any[]>;
|
|
121
147
|
}
|
|
122
148
|
|
|
123
149
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
@@ -195,8 +221,6 @@ declare const expressAdapter: (app: Application, server: Server<AnyRouter>, opti
|
|
|
195
221
|
basePath?: string;
|
|
196
222
|
}) => void;
|
|
197
223
|
|
|
198
|
-
/** biome-ignore-all lint/suspicious/noExplicitAny: any's are actually used correctly */
|
|
199
|
-
|
|
200
224
|
interface BaseRequest {
|
|
201
225
|
headers: Record<string, string>;
|
|
202
226
|
cookies: Record<string, string>;
|
|
@@ -217,8 +241,7 @@ type Request = QueryRequest | MutationRequest;
|
|
|
217
241
|
type ContextProvider = (req: Omit<BaseRequest, "context"> & {
|
|
218
242
|
transport: "HTTP" | "WEBSOCKET";
|
|
219
243
|
}) => Record<string, any>;
|
|
220
|
-
type
|
|
221
|
-
type NextFunction<O, R = Request> = (req: R) => Awaitable<O>;
|
|
244
|
+
type NextFunction<O, R = Request> = (req: R) => PromiseOrSync<O>;
|
|
222
245
|
type Middleware<T = any> = (opts: {
|
|
223
246
|
req: Request;
|
|
224
247
|
next: NextFunction<T>;
|
|
@@ -230,9 +253,6 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
230
253
|
readonly middlewares: Set<Middleware<any>>;
|
|
231
254
|
readonly logger: Logger;
|
|
232
255
|
contextProvider?: ContextProvider;
|
|
233
|
-
/** @deprecated */
|
|
234
|
-
private mutationSubscriptions;
|
|
235
|
-
private collectionSubscriptions;
|
|
236
256
|
private constructor();
|
|
237
257
|
static create<TRouter extends AnyRouter>(opts: {
|
|
238
258
|
router: TRouter;
|
|
@@ -244,6 +264,7 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
244
264
|
}): Server<TRouter>;
|
|
245
265
|
handleQuery(opts: {
|
|
246
266
|
req: QueryRequest;
|
|
267
|
+
subscription?: (mutation: DefaultMutation) => void;
|
|
247
268
|
}): Promise<QueryResult<any>>;
|
|
248
269
|
handleMutation(opts: {
|
|
249
270
|
req: MutationRequest;
|
|
@@ -254,4 +275,4 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
254
275
|
}
|
|
255
276
|
declare const server: typeof Server.create;
|
|
256
277
|
|
|
257
|
-
export { type AnyRoute, type AnyRouter, type Authorization, type BaseRequest, type ContextProvider, type Middleware, type Mutation, type MutationAuthorizationHandler, type
|
|
278
|
+
export { type AnyRoute, type AnyRouter, type Authorization, type BaseRequest, type ContextProvider, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationRequest, type MutationResult, type NextFunction, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, Storage, expressAdapter, routeFactory, router, server };
|
package/dist/server.d.ts
CHANGED
|
@@ -30,7 +30,7 @@ declare const defaultMutationSchema: z.ZodObject<{
|
|
|
30
30
|
UPDATE: "UPDATE";
|
|
31
31
|
}>;
|
|
32
32
|
payload: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
33
|
-
value: z.ZodNullable<z.
|
|
33
|
+
value: z.ZodNullable<z.ZodAny>;
|
|
34
34
|
_meta: z.ZodOptional<z.ZodObject<{
|
|
35
35
|
timestamp: z.ZodNullable<z.ZodOptional<z.ZodString>>;
|
|
36
36
|
}, z.core.$strip>>;
|
|
@@ -40,7 +40,7 @@ type DefaultMutation = Omit<z.infer<typeof defaultMutationSchema>, "resourceId">
|
|
|
40
40
|
resourceId: string;
|
|
41
41
|
};
|
|
42
42
|
|
|
43
|
-
type
|
|
43
|
+
type PromiseOrSync<T> = T | Promise<T>;
|
|
44
44
|
|
|
45
45
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
46
46
|
/** biome-ignore-all lint/style/noNonNullAssertion: false positive */
|
|
@@ -60,6 +60,7 @@ declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof
|
|
|
60
60
|
type AnyRouter = Router<any>;
|
|
61
61
|
type QueryResult<TShape extends LiveObjectAny> = {
|
|
62
62
|
data: MaterializedLiveType<TShape>[];
|
|
63
|
+
unsubscribe?: () => void;
|
|
63
64
|
};
|
|
64
65
|
type MutationResult<TShape extends LiveObjectAny> = {
|
|
65
66
|
data: MaterializedLiveType<TShape>;
|
|
@@ -101,6 +102,7 @@ declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends M
|
|
|
101
102
|
withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
|
|
102
103
|
mutation: typeof mutationCreator;
|
|
103
104
|
}) => T): Route<TResourceSchema, TMiddleware, T>;
|
|
105
|
+
getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
|
|
104
106
|
private handleSet;
|
|
105
107
|
private wrapInMiddlewares;
|
|
106
108
|
}
|
|
@@ -114,10 +116,34 @@ declare class RouteFactory {
|
|
|
114
116
|
declare const routeFactory: typeof RouteFactory.create;
|
|
115
117
|
type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
|
|
116
118
|
|
|
117
|
-
/** biome-ignore-all lint/
|
|
119
|
+
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
120
|
+
|
|
121
|
+
declare class Batcher {
|
|
122
|
+
private storage;
|
|
123
|
+
private queue;
|
|
124
|
+
private scheduled;
|
|
125
|
+
constructor(storage: Storage);
|
|
126
|
+
rawFind<T extends LiveObjectAny>({ resource, commonWhere, uniqueWhere, ...rest }: {
|
|
127
|
+
resource: string;
|
|
128
|
+
commonWhere?: Record<string, any>;
|
|
129
|
+
uniqueWhere?: Record<string, any>;
|
|
130
|
+
include?: Record<string, any>;
|
|
131
|
+
limit?: number;
|
|
132
|
+
sort?: {
|
|
133
|
+
key: string;
|
|
134
|
+
direction: "asc" | "desc";
|
|
135
|
+
}[];
|
|
136
|
+
}): Promise<MaterializedLiveType<T>[]>;
|
|
137
|
+
private getBatchKey;
|
|
138
|
+
private processBatch;
|
|
139
|
+
private executeBatchedRequests;
|
|
140
|
+
}
|
|
118
141
|
|
|
119
142
|
interface DataSource {
|
|
120
|
-
get(query: RawQueryRequest
|
|
143
|
+
get(query: RawQueryRequest, extra?: {
|
|
144
|
+
context?: any;
|
|
145
|
+
batcher?: Batcher;
|
|
146
|
+
}): PromiseOrSync<any[]>;
|
|
121
147
|
}
|
|
122
148
|
|
|
123
149
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
@@ -195,8 +221,6 @@ declare const expressAdapter: (app: Application, server: Server<AnyRouter>, opti
|
|
|
195
221
|
basePath?: string;
|
|
196
222
|
}) => void;
|
|
197
223
|
|
|
198
|
-
/** biome-ignore-all lint/suspicious/noExplicitAny: any's are actually used correctly */
|
|
199
|
-
|
|
200
224
|
interface BaseRequest {
|
|
201
225
|
headers: Record<string, string>;
|
|
202
226
|
cookies: Record<string, string>;
|
|
@@ -217,8 +241,7 @@ type Request = QueryRequest | MutationRequest;
|
|
|
217
241
|
type ContextProvider = (req: Omit<BaseRequest, "context"> & {
|
|
218
242
|
transport: "HTTP" | "WEBSOCKET";
|
|
219
243
|
}) => Record<string, any>;
|
|
220
|
-
type
|
|
221
|
-
type NextFunction<O, R = Request> = (req: R) => Awaitable<O>;
|
|
244
|
+
type NextFunction<O, R = Request> = (req: R) => PromiseOrSync<O>;
|
|
222
245
|
type Middleware<T = any> = (opts: {
|
|
223
246
|
req: Request;
|
|
224
247
|
next: NextFunction<T>;
|
|
@@ -230,9 +253,6 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
230
253
|
readonly middlewares: Set<Middleware<any>>;
|
|
231
254
|
readonly logger: Logger;
|
|
232
255
|
contextProvider?: ContextProvider;
|
|
233
|
-
/** @deprecated */
|
|
234
|
-
private mutationSubscriptions;
|
|
235
|
-
private collectionSubscriptions;
|
|
236
256
|
private constructor();
|
|
237
257
|
static create<TRouter extends AnyRouter>(opts: {
|
|
238
258
|
router: TRouter;
|
|
@@ -244,6 +264,7 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
244
264
|
}): Server<TRouter>;
|
|
245
265
|
handleQuery(opts: {
|
|
246
266
|
req: QueryRequest;
|
|
267
|
+
subscription?: (mutation: DefaultMutation) => void;
|
|
247
268
|
}): Promise<QueryResult<any>>;
|
|
248
269
|
handleMutation(opts: {
|
|
249
270
|
req: MutationRequest;
|
|
@@ -254,4 +275,4 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
254
275
|
}
|
|
255
276
|
declare const server: typeof Server.create;
|
|
256
277
|
|
|
257
|
-
export { type AnyRoute, type AnyRouter, type Authorization, type BaseRequest, type ContextProvider, type Middleware, type Mutation, type MutationAuthorizationHandler, type
|
|
278
|
+
export { type AnyRoute, type AnyRouter, type Authorization, type BaseRequest, type ContextProvider, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationRequest, type MutationResult, type NextFunction, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, Storage, expressAdapter, routeFactory, router, server };
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a,b,t,w,x,z as z$1,y,v}from'./chunk-3SQDLIFN.js';import G from'node:crypto';import it,{parse}from'qs';import {z}from'zod';import {Kysely,PostgresDialect}from'kysely';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/postgres';var te=a(H=>{Object.defineProperty(H,"__esModule",{value:true});H.parse=Ye;H.serialize=Xe;var Fe=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Ge=/^[\u0021-\u003A\u003C-\u007E]*$/,Ze=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Ke=/^[\u0020-\u003A\u003D-\u007E]*$/,He=Object.prototype.toString,Je=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Ye(i,t){let e=new Je,r=i.length;if(r<2)return e;let n=(t==null?void 0:t.decode)||et,a=0;do{let s=i.indexOf("=",a);if(s===-1)break;let c=i.indexOf(";",a),o=c===-1?r:c;if(s>o){a=i.lastIndexOf(";",s-1)+1;continue}let u=we(i,a,s),y=xe(i,s,u),d=i.slice(u,y);if(e[d]===void 0){let h=we(i,s+1,o),m=xe(i,o,h),l=n(i.slice(h,m));e[d]=l;}a=o+1;}while(a<r);return e}function we(i,t,e){do{let r=i.charCodeAt(t);if(r!==32&&r!==9)return t}while(++t<e);return e}function xe(i,t,e){for(;t>e;){let r=i.charCodeAt(--t);if(r!==32&&r!==9)return t+1}return e}function Xe(i,t,e){let r=(e==null?void 0:e.encode)||encodeURIComponent;if(!Fe.test(i))throw new TypeError(`argument name is invalid: ${i}`);let n=r(t);if(!Ge.test(n))throw new TypeError(`argument val is invalid: ${t}`);let a=i+"="+n;if(!e)return a;if(e.maxAge!==void 0){if(!Number.isInteger(e.maxAge))throw new TypeError(`option maxAge is invalid: ${e.maxAge}`);a+="; Max-Age="+e.maxAge;}if(e.domain){if(!Ze.test(e.domain))throw new TypeError(`option domain is invalid: ${e.domain}`);a+="; Domain="+e.domain;}if(e.path){if(!Ke.test(e.path))throw new TypeError(`option path is invalid: ${e.path}`);a+="; Path="+e.path;}if(e.expires){if(!tt(e.expires)||!Number.isFinite(e.expires.valueOf()))throw new TypeError(`option expires is invalid: ${e.expires}`);a+="; Expires="+e.expires.toUTCString();}if(e.httpOnly&&(a+="; HttpOnly"),e.secure&&(a+="; Secure"),e.partitioned&&(a+="; Partitioned"),e.priority)switch(typeof e.priority=="string"?e.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${e.priority}`)}if(e.sameSite)switch(typeof e.sameSite=="string"?e.sameSite.toLowerCase():e.sameSite){case true:case "strict":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${e.sameSite}`)}return a}function et(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function tt(i){return He.call(i)==="[object Date]"}});var Re="0123456789ABCDEFGHJKMNPQRSTVWXYZ",B=32;var De=16,be=10,Te=0xffffffffffff;var P;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})(P||(P={}));var k=class extends Error{constructor(t,e){super(`${e} (${t})`),this.name="ULIDError",this.code=t;}};function Ue(i){let t=Math.floor(i()*B);return t===B&&(t=B-1),Re.charAt(t)}function Be(i){var r;let t=_e(),e=t&&(t.crypto||t.msCrypto)||(typeof G<"u"?G:null);if(typeof(e==null?void 0:e.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return e.getRandomValues(n),n[0]/255};if(typeof(e==null?void 0:e.randomBytes)=="function")return ()=>e.randomBytes(1).readUInt8()/255;if((r=G)!=null&&r.randomBytes)return ()=>G.randomBytes(1).readUInt8()/255;throw new k(P.PRNGDetectFailure,"Failed to find a reliable PRNG")}function _e(){return Qe()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ve(i,t){let e="";for(;i>0;i--)e=Ue(t)+e;return e}function qe(i,t=be){if(isNaN(i))throw new k(P.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>Te)throw new k(P.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Te}: ${i}`);if(i<0)throw new k(P.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new k(P.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let e,r="";for(let n=t;n>0;n--)e=i%B,r=Re.charAt(e)+r,i=(i-e)/B;return r}function Qe(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Se(i,t){let e=Be(),r=Date.now();return qe(r,be)+Ve(De,e)}var Z=()=>Se().toLowerCase();var W=(...i)=>{let t=i.filter(e=>!!e);return t.length===0?{}:t.length===1?t[0]:{$and:t}};var K=class{storage;queue=new Map;scheduled=false;constructor(t){this.storage=t;}async rawFind({resource:t,commonWhere:e,uniqueWhere:r,...n}){return new Promise((a,s)=>{let c=this.getBatchKey({resource:t,commonWhere:e,...n}),o={resource:t,commonWhere:e,uniqueWhere:r,...n,resolve:a,reject:s};this.queue.has(c)||this.queue.set(c,[]);let u=this.queue.get(c);u&&u.push(o),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(t){let{resource:e,commonWhere:r,...n}=t;return `${e}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let t=Array.from(this.queue.entries());this.queue.clear();for(let[,e]of t)try{await this.executeBatchedRequests(e);}catch(r){e.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(t){var h;if(t.length===0)return;let e=t[0],{resource:r,commonWhere:n,include:a,sort:s}=e,c=t.length===1?e.limit:void 0,o=t.map(m=>m.uniqueWhere).filter(m=>m!==void 0),u=n,y=(h=Object.entries(o[0]??{})[0])==null?void 0:h[0];if(o.length>0){let m=o.map(l=>l[y]).filter(l=>l!=null);m.length>0&&(u=W(n,{[y]:{$in:m}}));}let d=await this.storage.get({resource:r,where:u,include:a,sort:s,limit:c});for(let m of t){let l=d;if(m.uniqueWhere){let[R,f]=Object.entries(m.uniqueWhere)[0];l=d.filter(p=>{var T;return ((T=p.value[R])==null?void 0:T.value)===f});}m.resolve(l);}}};var ve=b(te(),1);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()}),re=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()})),rt=re.superRefine((i,t)=>{i.id&&t.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Me=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),V=Me.extend({procedure:z.string(),payload:z.any().optional()}),q=Me.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:rt});z.union([q,V]);var Ie=_.omit({resource:true}),ne=V.omit({id:true,type:true,resource:true,procedure:true}),ie=q.omit({id:true,type:true,resource:true,procedure:true});z.union([ie,ne]);var ae=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(ae);if(typeof i=="object"&&i.constructor===Object){let t={};for(let[e,r]of Object.entries(i))t[e]=ae(r);return t}return i},Ae=i=>{let t=i.logger;return async e=>{var r;try{let n=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,a={headers:n,cookies:n.cookie?ve.default.parse(n.cookie):{}},s=new URL(e.url),c=s.pathname.split("/"),o=s.searchParams,u=ae(it.parse(o.toString())),y=await((r=i.contextProvider)==null?void 0:r.call(i,{transport:"HTTP",headers:a.headers,cookies:a.cookies,queryParams:u}))??{};if(e.method==="GET"){let d=c[c.length-1],{success:h,data:m,error:l}=Ie.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:l},{status:400});let R=await i.handleQuery({req:{...a,...m,type:"QUERY",resource:d,context:y,queryParams:u}});return !R||!R.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(R.data)}if(e.method==="POST")try{let d=c[c.length-1],h=c[c.length-2],m=e.body?await e.json():{},l;if(d==="insert"||d==="update"){let{success:f,data:p,error:T}=ie.safeParse(m);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:T},{status:400});l=p;}else {let{success:f,data:p,error:T}=ne.safeParse(m);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:T},{status:400});l=p;}let R=await i.handleMutation({req:{...a,type:"MUTATE",resource:h,input:l.payload,context:y,resourceId:l.resourceId,procedure:d==="insert"||d==="update"?d.toUpperCase():d,queryParams:{}}});return Response.json(R)}catch(d){return t.error("Error parsing mutation from the client:",d),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return t.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var je=b(te(),1);var D=z.string(),at=_.extend({id:D,type:z.literal("SUBSCRIBE")}),ot=_.extend({id:D,type:z.literal("QUERY")}),Ee=q.extend({id:D}),st=V.extend({id:D}),ct=z.union([st,Ee]),Le=z.union([at,ot,ct]),ut=z.object({id:D,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),dt=z.object({id:D,type:z.literal("REPLY"),data:z.any()});z.union([ut,dt,Ee]);z.object({resource:z.string(),data:z.array(re)});var Oe=i=>{let t={},e=i.logger;return (r,n)=>{var d;let a=h=>{r.send(JSON.stringify(h));},s=Z(),c=new Set,o={headers:n.headers,cookies:typeof n.headers.cookie=="string"?je.default.parse(n.headers.cookie):{}},u=parse(n.url.split("?")[1]),y=(d=i.contextProvider)==null?void 0:d.call(i,{transport:"WEBSOCKET",headers:o.headers,cookies:o.cookies,queryParams:u});t[s]=r,e.info("Client connected:",s),r.on("message",async h=>{var m;try{e.debug("Message received from the client:",h);let l=Le.parse(JSON.parse(h.toString()));if(l.type==="SUBSCRIBE"){let R=await y??{},f=l.resource,p=i.router.routes[f],T;if((m=p==null?void 0:p.authorization)!=null&&m.read){let x=p.authorization.read({ctx:R});T=typeof x=="object"?x:void 0;}c.add(i.subscribeToMutations(l,x=>{var w;!x.resourceId||!x.payload||!Object.keys(x.payload).length||(w=t[s])==null||w.send(JSON.stringify(x));},T));}else if(l.type==="QUERY"){let{resource:R}=l,f=await i.handleQuery({req:{...o,type:"QUERY",resource:R,context:await y??{},queryParams:u}});if(!f||!f.data)throw new Error("Invalid resource");a({id:l.id,type:"REPLY",data:{resource:R,data:(f.data??[]).map(p=>p.value)}});}else if(l.type==="MUTATE"){let{resource:R}=l;e.debug("Received mutation from client:",l);try{let f=await i.handleMutation({req:{...o,type:"MUTATE",resource:R,input:l.payload,context:{messageId:l.id,...await y??{}},resourceId:l.resourceId,procedure:l.procedure,queryParams:u}});l.procedure&&l.procedure!=="INSERT"&&l.procedure!=="UPDATE"&&a({id:l.id,type:"REPLY",data:f});}catch(f){a({id:l.id,type:"REJECT",resource:R,message:f.message}),e.error("Error parsing mutation from the client:",f);}}}catch(l){e.error("Error handling message from the client:",l);}}),r.on("close",()=>{e.info("Connection closed",s),delete t[s];for(let h of Array.from(c))h();});}};function Ce(i){let t=`${i.protocol}://${i.hostname}${i.url}`,e=new Headers;return Object.entries(i.headers).forEach(([r,n])=>{n&&e.set(r,Array.isArray(n)?n.join(","):n);}),new Request(t,{method:i.method,headers:e,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Ft=(i,t,e)=>{i.ws(`${(e==null?void 0:e.basePath)??""}/ws`,Oe(t)),i.use(`${(e==null?void 0:e.basePath)??""}/`,(r,n)=>{Ae(t)(Ce(r)).then(s=>s.json().then(c=>n.status(s.status).send(c)));});};var oe=class i{routes;constructor(t){this.routes=t.routes;}static create(t){return new i(t)}},Yt=i=>oe.create({...i}),yt=i=>({handler:t=>({inputValidator:i??z.undefined(),handler:t})}),se=class i{resourceSchema;middlewares;customMutations;authorization;constructor(t,e,r){this.resourceSchema=t,this.middlewares=new Set,this.customMutations=e??{},this.authorization=r;}use(...t){for(let e of t)this.middlewares.add(e);return this}withMutations(t){return new i(this.resourceSchema,t({mutation:yt}),this.authorization)}handleQuery=async({req:t,batcher:e})=>await this.wrapInMiddlewares(async r=>{var a,s;let n=(s=(a=this.authorization)==null?void 0:a.read)==null?void 0:s.call(a,{ctx:r.context});if(typeof n=="boolean"&&!n)throw new Error("Not authorized");return {data:await e.rawFind({resource:r.resource,commonWhere:W(r.where,typeof n=="object"?n:void 0),uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort})}})(t);handleMutation=async({req:t,db:e,schema:r})=>await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let a=this.customMutations[n.procedure];if(a){let s=a.inputValidator.parse(n.input);return n.input=s,a.handler({req:n,db:e})}else {if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:e,operation:n.procedure,schema:r});throw new Error(`Unknown procedure: ${n.procedure}`)}})(t);handleSet=async({req:t$1,db:e,operation:r,schema:n})=>{if(!t$1.input)throw new Error("Payload is required");if(!t$1.resourceId)throw new Error("ResourceId is required");let a=await e.rawFindById(t$1.resource,t$1.resourceId);if(r==="INSERT"&&a)throw new Error("Resource already exists");if(r==="UPDATE"&&!a)throw new Error("Resource not found");return e.transaction(async({trx:s})=>{var y,d,h,m,l,R,f;let[c,o]=this.resourceSchema.mergeMutation("set",t$1.input,a);if(!o)throw new Error("Mutation rejected");if(r==="INSERT"){let p=await s.rawInsert(t$1.resource,t$1.resourceId,c,(y=t$1.context)==null?void 0:y.messageId),T=t(p);if(T.id=T.id??t$1.resourceId,(d=this.authorization)!=null&&d.insert){let x$1=this.authorization.insert({ctx:t$1.context,value:T});if(typeof x$1=="boolean"){if(!x$1)throw new Error("Not authorized")}else {let w$1=w(x$1,t$1.resource,n),S=Object.keys(w$1).length>0?await s.rawFindById(t$1.resource,t$1.resourceId,w$1):p,b=t(S);if(b.id=b.id??t$1.resourceId,!x(b,x$1))throw new Error("Not authorized")}}return {data:p,acceptedValues:o}}if((m=(h=this.authorization)==null?void 0:h.update)!=null&&m.preMutation){let p=t(a);p.id=p.id??t$1.resourceId;let T=this.authorization.update.preMutation({ctx:t$1.context,value:p});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let x$1=w(T,t$1.resource,n),w$1=Object.keys(x$1).length>0?await s.rawFindById(t$1.resource,t$1.resourceId,x$1):a,S=t(w$1);if(S.id=S.id??t$1.resourceId,!x(S,T))throw new Error("Not authorized")}}let u=await s.rawUpdate(t$1.resource,t$1.resourceId,c,(l=t$1.context)==null?void 0:l.messageId);if((f=(R=this.authorization)==null?void 0:R.update)!=null&&f.postMutation){let p=t(u);p.id=p.id??t$1.resourceId;let T=this.authorization.update.postMutation({ctx:t$1.context,value:p});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let x$1=w(T,t$1.resource,n),w$1=Object.keys(x$1).length>0?await s.rawFindById(t$1.resource,t$1.resourceId,x$1):u,S=t(w$1);if(S.id=S.id??t$1.resourceId,!x(S,T))throw new Error("Not authorized")}}return {data:u,acceptedValues:o}})};wrapInMiddlewares(t){return e=>Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),t)(e)}},ce=class i{middlewares;constructor(t=[]){this.middlewares=t;}collectionRoute(t,e){return new se(t,void 0,e).use(...this.middlewares)}use(...t){return new i([...this.middlewares,...t])}static create(){return new i}},Xt=ce.create;var Q=class{async insert(t$1,e){let r=new Date().toISOString();return t(await this.rawInsert(t$1.name,e.id,{value:Object.fromEntries(Object.entries(e).map(([n,a])=>[n,{value:a,_meta:{timestamp:r}}]))}))}async update(t$1,e,r){let n=new Date().toISOString(),{id:a,...s}=r;return t(await this.rawUpdate(t$1.name,e,{value:Object.fromEntries(Object.entries(s).map(([c,o])=>[c,{value:o,_meta:{timestamp:n}}]))}))}};function J(i,t,e,r){if(!i)throw new Error("Schema not initialized");let n=i[t];if(!n)throw new Error("Resource not found");let a=r.$or,s=r.$and;return (a?e.or:e.and)(a?r.$or.map(c=>J(i,t,e,c)):s?r.$and.map(c=>J(i,t,e,c)):Object.entries(r).map(([c,o])=>{var u,y;if(n.fields[c])return (o==null?void 0:o.$eq)!==void 0?e(`${t}.${c}`,o.$eq===null?"is":"=",o.$eq):(o==null?void 0:o.$in)!==void 0?e(`${t}.${c}`,"in",o.$in):(o==null?void 0:o.$not)!==void 0?((u=o==null?void 0:o.$not)==null?void 0:u.$in)!==void 0?e(`${t}.${c}`,"not in",o.$not.$in):((y=o==null?void 0:o.$not)==null?void 0:y.$eq)!==void 0?e(`${t}.${c}`,o.$not.$eq===null?"is not":"!=",o.$not.$eq):e(`${t}.${c}`,o.$not===null?"is not":"!=",o.$not):(o==null?void 0:o.$gt)!==void 0?e(`${t}.${c}`,">",o.$gt):(o==null?void 0:o.$gte)!==void 0?e(`${t}.${c}`,">=",o.$gte):(o==null?void 0:o.$lt)!==void 0?e(`${t}.${c}`,"<",o.$lt):(o==null?void 0:o.$lte)!==void 0?e(`${t}.${c}`,"<=",o.$lte):e(`${t}.${c}`,o===null?"is":"=",o);if(n.relations[c]){let d=n.relations[c],h=d.entity.name;return d.type==="many"?e.exists(ue(i,h,e.selectFrom(h).select("id").whereRef(d.foreignColumn,"=",`${t}.id`),o)):J(i,h,e,o)}return null}).filter(Boolean))}function Y(i,t,e,r){let n=i[t];if(!n)throw new Error("Resource not found");if(!r)return e;if(r.$and){for(let a of r.$and)e=Y(i,t,e,a);return e}else if(r.$or){for(let a of r.$or)e=Y(i,t,e,a);return e}for(let[a,s]of Object.entries(r)){if(!n.relations[a])continue;let c=n.relations[a],o=c.entity.name,u=c.type==="one"?"id":c.foreignColumn,y=c.type==="one"?c.relationalColumn:"id";e=e.leftJoin(o,`${o}.${u}`,`${t}.${y}`),s instanceof Object&&!Array.isArray(s)&&s!==null&&(e=Y(i,o,e,s));}return e}function ue(i,t,e,r){return !r||Object.keys(r).length===0?e:(e=Y(i,t,e,r),e.where(n=>J(i,t,n,r)))}function X(i,t,e,r){if(!r)return e;if(!i)throw new Error("Schema not initialized");let n=i[t];if(!n)throw new Error(`Resource not found: ${t}`);for(let a of Object.keys(r)){if(!n.relations[a])throw new Error(`Relation ${a} not found in resource ${t}`);let s=n.relations[a],c=s.entity.name,o=r[a],u=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id",d=s.type==="one"?jsonObjectFrom:jsonArrayFrom,h=typeof o=="object"&&o!==null;e=e.select(m=>{let l=m.selectFrom(c).selectAll(c).whereRef(`${c}.${u}`,"=",`${t}.${y}`).select(R=>jsonObjectFrom(R.selectFrom(`${c}_meta`).selectAll(`${c}_meta`).whereRef(`${c}_meta.id`,"=",`${c}.id`)).as("_meta"));return h&&(l=X(i,c,l,o)),d(l).as(a)});}return e}var ke="42701",de=class i extends Q{db;schema;logger;server;mutationStack=[];constructor(t,e,r,n){super(),this.isKyselyLike(t)?this.db=t:this.db=new Kysely({dialect:new PostgresDialect({pool:t})}),this.schema=e,this.logger=r,this.server=n,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(t,e,r){var a;this.schema=t,this.logger=e,this.server=r;let n=await this.db.introspection.getTables();for(let[s,c]of Object.entries(t)){let o=n.find(d=>d.name===s);o||await this.db.schema.createTable(s).ifNotExists().execute();let u=`${s}_meta`,y=n.find(d=>d.name===u);y||await this.db.schema.createTable(u).ifNotExists().execute();for(let[d,h]of Object.entries(c.fields)){let m=o==null?void 0:o.columns.find(f=>f.name===d),l=h.getStorageFieldType();m?m.dataType!==l.type&&((a=this.logger)==null||a.warn("Column type mismatch:",d,"expected to have type:",l.type,"but has type:",m.dataType)):(await this.db.schema.alterTable(s).addColumn(d,l.type,f=>{let p=f;return l.unique&&(p=p.unique()),l.nullable||(p=p.notNull()),l.references&&(p=p.references(l.references)),l.primary&&(p=p.primaryKey()),l.default!==void 0&&(p=p.defaultTo(l.default)),p}).execute().catch(f=>{var p;if(f.code!==ke)throw (p=this.logger)==null||p.error("Error adding column",d,f),f}),l.index&&await this.db.schema.createIndex(`${s}_${d}_index`).on(s).column(d).execute().catch(()=>{})),(y==null?void 0:y.columns.find(f=>f.name===d))||await this.db.schema.alterTable(u).addColumn(d,"varchar",f=>{let p=f;return l.primary&&(p=p.primaryKey().references(`${s}.${d}`)),p}).execute().catch(f=>{var p;if(f.code!==ke)throw (p=this.logger)==null||p.error("Error adding meta column",d,f),f});}}}async rawFindById(t,e,r){if(!this.schema)throw new Error("Schema not initialized");let n=await this.db.selectFrom(t).where("id","=",e).selectAll(t).select(s=>jsonObjectFrom(s.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));n=X(this.schema,t,n,r);let a=await n.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(t$1,e,r){let n=await this.rawFindById(t$1.name,e,r==null?void 0:r.include);if(n)return t(n)}async get(t){if(!this.schema)throw new Error("Schema not initialized");let{resource:e,where:r,include:n,limit:a,sort:s}=t,c=this.db.selectFrom(e).selectAll(e).select(u=>jsonObjectFrom(u.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));c=ue(this.schema,e,c,r),c=X(this.schema,e,c,n),a!==void 0&&(c=c.limit(a)),s!==void 0&&s.forEach(u=>{c=c.orderBy(u.key,u.direction);});let o=await c.execute();return o.length===0?[]:o.map(u=>this.convertToMaterializedLiveType(u))}async find(t$1,e){return (await this.get({resource:t$1.name,where:e==null?void 0:e.where,include:e==null?void 0:e.include,limit:e==null?void 0:e.limit,sort:e==null?void 0:e.sort})).map(n=>t(n))}async rawInsert(t,e,r,n){var o;let a={},s={};for(let[u,y]of Object.entries(r.value)){let d=(o=y._meta)==null?void 0:o.timestamp;d&&(a[u]=y.value,s[u]=d);}await this.db.insertInto(t).values({...a,id:e}).execute().then(()=>{this.db.insertInto(`${t}_meta`).values({...s,id:e}).execute();});let c=this.buildMutation(t,e,"INSERT",r,n);return c&&this.trackMutation(c,r),r}async rawUpdate(t,e,r,n){var o;let a={},s={};for(let[u,y]of Object.entries(r.value)){let d=(o=y._meta)==null?void 0:o.timestamp;d&&(a[u]=y.value,s[u]=d);}await Promise.all([this.db.updateTable(t).set(a).where("id","=",e).execute(),this.db.insertInto(`${t}_meta`).values({...s,id:e}).onConflict(u=>u.column("id").doUpdateSet(s)).execute()]);let c=this.buildMutation(t,e,"UPDATE",r,n);return c&&this.trackMutation(c,r),r}async transaction(t){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let a=Math.random().toString(36).substring(2,15),s=this.mutationStack,c=[];this.mutationStack=c;let o=await this.db.savepoint(a).execute();try{return await t({trx:this,commit:async()=>{await o.releaseSavepoint(a).execute(),s.push(...c);},rollback:async()=>{await o.rollbackToSavepoint(a).execute(),c.length=0;}}).then(u=>o.isCommitted||o.isRolledBack?u:o.releaseSavepoint(a).execute().then(()=>(s.push(...c),u)))}catch(u){throw await o.rollbackToSavepoint(a).execute().catch(()=>{}),c.length=0,u}finally{this.mutationStack=s;}}let e=[],r=this.mutationStack;this.mutationStack=e;let n=await this.db.startTransaction().execute();try{let a=new i(n,this.schema,this.logger,this.server);return a.mutationStack=e,await t({trx:a,commit:async()=>{await n.commit().execute(),this.notifyMutations(e);},rollback:async()=>{await n.rollback().execute(),e.length=0;}}).then(s=>n.isCommitted||n.isRolledBack?s:n.commit().execute().then(()=>(this.notifyMutations(e),s)))}catch(a){throw await n.rollback().execute(),e.length=0,a}finally{this.mutationStack=r;}}get internalDB(){return this.db}convertToMaterializedLiveType(t){return {value:Object.entries(t).reduce((e,[r,n])=>{var a,s,c;return r==="_meta"||(r==="id"?e[r]={value:n}:Array.isArray(n)?e[r]={value:n.map(o=>this.convertToMaterializedLiveType(o)),_meta:{timestamp:(a=t==null?void 0:t._meta)==null?void 0:a[r]}}:typeof n=="object"&&n!==null&&!(n instanceof Date)?e[r]={...this.convertToMaterializedLiveType(n),_meta:{timestamp:(s=t==null?void 0:t._meta)==null?void 0:s[r]}}:e[r]={value:n,_meta:{timestamp:(c=t==null?void 0:t._meta)==null?void 0:c[r]}}),e},{})}}isKyselyLike(t){if(t instanceof Kysely)return true;if(!t||typeof t!="object")return false;let e=t,r=typeof e.selectFrom=="function",n=typeof e.startTransaction=="function",a=typeof e.savepoint=="function",s=typeof e.isTransaction=="boolean"||typeof e.isTransaction=="function";return r&&n||a&&s}buildMutation(t,e,r,n,a){var c;let s={};for(let[o,u]of Object.entries(n.value)){if(o==="id")continue;let y=(c=u._meta)==null?void 0:c.timestamp;y&&(s[o]={value:u.value,_meta:{timestamp:y}});}return Object.keys(s).length===0?null:{id:a??Z(),type:"MUTATE",resource:t,resourceId:e,procedure:r,payload:s}}trackMutation(t,e){this.db.isTransaction?this.mutationStack.push({mutation:t,entityData:e}):this.notifyMutations([t],e);}notifyMutations(t,e){if(this.server)if(e!==void 0){let r=t;for(let n of r)this.server.notifySubscribers(n,e);}else {let r=t;for(let{mutation:n,entityData:a}of r)this.server.notifySubscribers(n,a);}}};var le=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;mutationSubscriptions=new Set;collectionSubscriptions=new Map;constructor(t){var e;this.router=t.router,this.storage=t.storage,this.schema=t.schema,this.logger=z$1({level:t.logLevel??y.INFO}),(e=t.middlewares)==null||e.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=t.contextProvider;}static create(t){return new i(t)}handleQuery(t){let e=new K(this.storage);return this.wrapInMiddlewares(async r=>{var m,l,R,f,p,T,x;let n=Ne(r,this.schema,{stepId:"query",collectionName:r.resource,included:Object.keys(r.include??{})}),a={headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context},s={};for(let w=0;w<n.length;w++){let S=n[w],b=this.router.routes[S.resource];if(!b)throw new Error("Invalid resource");let A;if(S.getWhere&&S.referenceGetter){let M=S.referenceGetter(s);A=[];for(let I=0;I<M.length;I++)A.push(S.getWhere(M[I]));}else A=[void 0];let L=s[S.prevStepId??""],j=[];if(L)for(let M=0;M<L.length;M++){let I=L[M],z=((m=I==null?void 0:I.result)==null?void 0:m.data)??[];for(let C=0;C<z.length;C++){let ee=z[C],ye=(R=(l=ee==null?void 0:ee.value)==null?void 0:l.id)==null?void 0:R.value;ye&&j.push(ye);}}let $=[];for(let M=0;M<A.length;M++){let I=A[M],z=j[M];$.push((async()=>{let C=await b.handleQuery({req:{type:"QUERY",...S,...a,where:S.where,relationalWhere:I},batcher:e});return {includedBy:z,result:C}})());}let O=await Promise.allSettled($),U=[];for(let M=0;M<O.length;M++){let I=O[M];I.status==="fulfilled"&&U.push(I.value);}s[S.stepId]=U;}let c=new Map,o=0;for(let w in s){let S=s[w],b=n[o];o++;for(let A=0;A<S.length;A++){let L=S[A],j=L.result.data;for(let $=0;$<j.length;$++){let O=j[$],U=(p=(f=O==null?void 0:O.value)==null?void 0:f.id)==null?void 0:p.value;if(!U)continue;let M=`${w}.${U}`,I=[];w!=="query"&&L.includedBy&&(I=[`${b.prevStepId}.${L.includedBy}`]);let z=c.get(M);if(z)for(let C=0;C<I.length;C++)z.includedBy.add(I[C]);else c.set(M,{data:O,includedBy:new Set(I),path:w.split(".").slice(-1)[0],isMany:b.isMany??false,collectionName:b.collectionName,included:b.included});}}}let u=Object.fromEntries(c),y={data:[]},d=Object.keys(u);for(let w=d.length-1;w>=0;w--){let S=d[w],b=u[S],A=b.path;if(A==="query"&&y.data.push(b.data),b.included.length)for(let L=0;L<b.included.length;L++){let j=b.included[L];b.data.value[j]??=((x=(T=this.schema[b.collectionName])==null?void 0:T.relations[j])==null?void 0:x.type)==="many"?{value:[]}:{value:null};}if(b.includedBy.size>0){let L=Array.from(b.includedBy);for(let j=0;j<L.length;j++){let $=L[j],O=u[$];O&&(b.isMany?(O.data.value[A]??={value:[]},O.data.value[A].value.push(b.data)):O.data.value[A]=b.data);}}}return y})(t.req)}async handleMutation(t){let e=await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(t.req);if(e&&t.req.type==="MUTATE"&&e.acceptedValues&&(t.req.procedure==="INSERT"||t.req.procedure==="UPDATE")&&t.req.resourceId){let n=e.acceptedValues??{},a=t.req,s=a.resourceId;Object.keys(n).length&&s&&this.mutationSubscriptions.forEach(c=>{c({id:t.req.context.messageId,type:"MUTATE",resource:a.resource,payload:n,resourceId:s,procedure:a.procedure});});}return e}use(t){return this.middlewares.add(t),this}context(t){return this.contextProvider=t,this}subscribeToMutations(t,e,r){let n=t.resource,a={query:t,authorizationWhere:r},s=v(a),c=this.collectionSubscriptions.get(n);c||(c=new Map,this.collectionSubscriptions.set(n,c));let o=c.get(s);return o?(o.callbacks.add(e),r!==void 0&&(o.authorizationWhere=r)):c.set(s,{callbacks:new Set([e]),...a}),()=>{var y,d;let u=this.collectionSubscriptions.get(n);u&&((y=u.get(s))==null||y.callbacks.delete(e),((d=u.get(s))==null?void 0:d.callbacks.size)===0&&u.delete(s));}}notifySubscribers(t$1,e){let r=t$1.resource,n=this.collectionSubscriptions.get(r);if(n&&e)for(let a of Array.from(n.values())){let s=pe(a.query.where,this.schema[r]),c=W(s,a.authorizationWhere),o=t(e);if(!o)continue;(t$1.resourceId&&typeof o=="object"&&o!==null&&!("id"in o)||t$1.resourceId&&typeof o=="object"&&o!==null&&o.id!==t$1.resourceId)&&(o.id=t$1.resourceId);let u=Object.keys(c).length>0,y=true;u&&(y=x(o,c)),y&&a.callbacks.forEach(d=>{var h;try{d(t$1);}catch(m){(h=this.logger)==null||h.error(`Error in mutation subscription for resource ${r}:`,m);}});}}wrapInMiddlewares(t){return e=>Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),t)(e)}},Rr=le.create;function Ne(i,t,e){let{include:r,where:n,...a}=i,{stepId:s}=e,c=[{...a,...e,where:n}];if(r&&typeof r=="object"&&Object.keys(r).length>0){let o=t[a.resource];if(!o)throw new Error(`Resource ${a.resource} not found`);c.push(...Object.entries(r).flatMap(([u,y])=>{let d=o.relations[u];if(!d)throw new Error(`Relation ${u} not found for resource ${a.resource}`);let h=d.entity.name;return Ne({...a,resource:h,include:y},t,{getWhere:d.type==="one"?m=>({id:m}):m=>({[d.foreignColumn]:m}),referenceGetter:m=>m[s].flatMap(l=>{let R=l.result.data??[];return d.type==="one"?R.map(f=>{var p,T;return (T=(p=f.value)==null?void 0:p[d.relationalColumn])==null?void 0:T.value}).filter(f=>f!==void 0):R.map(f=>{var p,T;return (T=(p=f.value)==null?void 0:p.id)==null?void 0:T.value}).filter(f=>f!==void 0)}),stepId:`${s}.${u}`,prevStepId:s,isMany:d.type==="many",collectionName:h,included:typeof y=="object"?Object.keys(y):[]})}));}return c}function pe(i,t){if(!i||!t||Object.keys(i).length===0)return i;if(i.$and){let r=i.$and.map(n=>pe(n,t)).filter(n=>!!n&&Object.keys(n).length>0);return r.length===0?void 0:r.length===1?r[0]:{$and:r}}if(i.$or){let r=i.$or.map(n=>pe(n,t)).filter(n=>!!n&&Object.keys(n).length>0);return r.length===0?void 0:r.length===1?r[0]:{$or:r}}let e={};for(let[r,n]of Object.entries(i))t.fields[r]&&(e[r]=n);return Object.keys(e).length>0?e:void 0}
|
|
2
|
-
export{
|
|
1
|
+
import {a,b,v,t,w,x,z as z$2,y}from'./chunk-IT5UC7TA.js';import k from'crypto';import Ge,{parse}from'qs';import {z as z$1}from'zod';import {Kysely,PostgresDialect}from'kysely';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/postgres';var Z=a(W=>{Object.defineProperty(W,"__esModule",{value:true});W.parse=Ue;W.serialize=We;var Qe=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ze=/^[\u0021-\u003A\u003C-\u007E]*$/,ke=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,qe=/^[\u0020-\u003A\u003D-\u007E]*$/,De=Object.prototype.toString,Be=(()=>{let a=function(){};return a.prototype=Object.create(null),a})();function Ue(a,e){let t=new Be,n=a.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Fe,i=0;do{let c=a.indexOf("=",i);if(c===-1)break;let o=a.indexOf(";",i),s=o===-1?n:o;if(c>s){i=a.lastIndexOf(";",c-1)+1;continue}let l=ye(a,i,c),y=pe(a,c,l),u=a.slice(l,y);if(t[u]===void 0){let h=ye(a,c+1,s),d=pe(a,s,h),p=r(a.slice(h,d));t[u]=p;}i=s+1;}while(i<n);return t}function ye(a,e,t){do{let n=a.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function pe(a,e,t){for(;e>t;){let n=a.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function We(a,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Qe.test(a))throw new TypeError(`argument name is invalid: ${a}`);let r=n(e);if(!ze.test(r))throw new TypeError(`argument val is invalid: ${e}`);let i=a+"="+r;if(!t)return i;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);i+="; Max-Age="+t.maxAge;}if(t.domain){if(!ke.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);i+="; Domain="+t.domain;}if(t.path){if(!qe.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);i+="; Path="+t.path;}if(t.expires){if(!_e(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);i+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(i+="; HttpOnly"),t.secure&&(i+="; Secure"),t.partitioned&&(i+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":i+="; Priority=Low";break;case "medium":i+="; Priority=Medium";break;case "high":i+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":i+="; SameSite=Strict";break;case "lax":i+="; SameSite=Lax";break;case "none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return i}function Fe(a){if(a.indexOf("%")===-1)return a;try{return decodeURIComponent(a)}catch{return a}}function _e(a){return De.call(a)==="[object Date]"}});var de="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$=32;var Ae=16,le=10,ue=0xffffffffffff;var E;(function(a){a.Base32IncorrectEncoding="B32_ENC_INVALID",a.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",a.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",a.EncodeTimeNegative="ENC_TIME_NEG",a.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",a.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",a.PRNGDetectFailure="PRNG_DETECT",a.ULIDInvalid="ULID_INVALID",a.Unexpected="UNEXPECTED",a.UUIDInvalid="UUID_INVALID";})(E||(E={}));var A=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Oe(a){let e=Math.floor(a()*$);return e===$&&(e=$-1),de.charAt(e)}function Ne(a){var n;let e=Pe(),t=e&&(e.crypto||e.msCrypto)||(typeof k<"u"?k:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=k)!=null&&n.randomBytes)return ()=>k.randomBytes(1).readUInt8()/255;throw new A(E.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Pe(){return Ce()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Le(a,e){let t="";for(;a>0;a--)t=Oe(e)+t;return t}function $e(a,e=le){if(isNaN(a))throw new A(E.EncodeTimeValueMalformed,`Time must be a number: ${a}`);if(a>ue)throw new A(E.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${ue}: ${a}`);if(a<0)throw new A(E.EncodeTimeNegative,`Time must be positive: ${a}`);if(Number.isInteger(a)===false)throw new A(E.EncodeTimeValueMalformed,`Time must be an integer: ${a}`);let t,n="";for(let r=e;r>0;r--)t=a%$,n=de.charAt(t)+n,a=(a-t)/$;return n}function Ce(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function he(a,e){let t=Ne(),n=Date.now();return $e(n,le)+Le(Ae,t)}var D=()=>he().toLowerCase(),q=a=>({then(e,t){try{if(e){let n=e(a);return n instanceof Promise?n:q(n)}return q(a)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:q(r)}throw n}}}),H=a=>a instanceof Promise?a:q(a);var P=(...a)=>{let e=a.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var B=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((i,c)=>{let o=this.getBatchKey({resource:e,commonWhere:t,...r}),s={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:i,reject:c};this.queue.has(o)||this.queue.set(o,[]);let l=this.queue.get(o);l&&l.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:i,sort:c}=t,o=e.length===1?t.limit:void 0,s=e.map(d=>d.uniqueWhere).filter(d=>d!==void 0),l=r,y=(h=Object.entries(s[0]??{})[0])==null?void 0:h[0];if(s.length>0){let d=s.map(p=>p[y]).filter(p=>p!=null);d.length>0&&(l=P(r,{[y]:{$in:d}}));}let u=await this.storage.get({resource:n,where:l,include:i,sort:c,limit:o});for(let d of e){let p=u;if(d.uniqueWhere){let[m,g]=Object.entries(d.uniqueWhere)[0];p=u.filter(f=>{var b;return ((b=f.value[m])==null?void 0:b.value)===g});}d.resolve(p);}}};function G(a){return v({resource:a.query.resource,where:a.query.where,include:a.query.include,stepPath:a.stepPath,isMany:a.isMany,relationName:a.relationName})}var U=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,i]of Object.entries(n.relations))i.type==="one"&&i.relationalColumn&&t.set(String(i.relationalColumn),{relationName:r,targetResource:i.entity.name});return t}ensureObjectNode(e,t,n){let r=this.objectNodes.get(e);return r?n&&r.matchedQueries.add(n):(r={id:e,type:t,matchedQueries:new Set(n?[n]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,r)),r}storeRelation(e,t,n,r){let i=this.objectNodes.get(e),c=this.objectNodes.get(t);if(i&&i.referencesObjects.set(n,t),c&&r){let o=c.referencedByObjects.get(r);o||(o=new Set,c.referencedByObjects.set(r,o)),o.add(e);}}removeRelation(e,t,n,r){let i=this.objectNodes.get(e),c=this.objectNodes.get(t);if(i&&i.referencesObjects.delete(n),c&&r){let o=c.referencedByObjects.get(r);o&&(o.delete(e),o.size===0&&c.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let i=r.relations[n];if(!i)return;let c=this.schema[t];if(c!=null&&c.relations){if(i.type==="many"&&i.foreignColumn){for(let[o,s]of Object.entries(c.relations))if(s.entity.name===e&&s.type==="one"&&s.relationalColumn===i.foreignColumn)return o}if(i.type==="one"&&i.relationalColumn){for(let[o,s]of Object.entries(c.relations))if(s.entity.name===e&&s.type==="many"&&s.foreignColumn===i.relationalColumn)return o}}}updateRelationsFromMutation(e,t,n,r){let i=this.getRelationalColumns(e),c=this.objectNodes.get(t);if(c)for(let[o,{relationName:s,targetResource:l}]of Array.from(i)){if(!(r&&o in r))continue;let u=this.getInverseRelationName(e,l,s),h=c.referencesObjects.get(s),d=n[o];h!==d&&(h&&this.removeRelation(t,h,s,u),d&&(this.ensureObjectNode(d,l),this.storeRelation(t,d,s,u)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new B(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),i={},c=[];for(let o of r){this.logger.debug("[QueryEngine] Subscribing to step",o.stepPath.join("."));let s=G(o),l=i[o.stepPath.at(-2)??""],y=o.stepPath.at(-1)??"",u=this.queryNodes.get(s);if(u)u.subscriptions.add(t);else if(u={hash:s,queryStep:o,relationName:y,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:l,childQueries:new Set},this.queryNodes.set(u.hash,u),l){let h=this.queryNodes.get(l);h&&h.childQueries.add(u.hash);}i[y]=s,c.push(()=>{let h=this.queryNodes.get(s);h&&(h.subscriptions.delete(t),h.subscriptions.size===0&&this.queryNodes.delete(s));});}return ()=>{for(let o of c)o();}}breakdownQuery(e){var g;let{query:t,stepPath:n=[],context:r={},parentResource:i}=e,{include:c}=t,o=n.length===0,s=n.at(-1),l,y,u;if(!o&&i&&s){let f=this.schema[i],b=(g=f==null?void 0:f.relations)==null?void 0:g[s];b&&(u=b.type==="many",b.type==="one"?(l=R=>({id:R}),y=R=>R.map(w=>{var S,x;return (x=(S=w.value)==null?void 0:S[b.relationalColumn])==null?void 0:x.value}).filter(w=>w!==void 0)):(l=R=>({[b.foreignColumn]:R}),y=R=>R.map(w=>{var S,x;return (x=(S=w.value)==null?void 0:S.id)==null?void 0:x.value}).filter(w=>w!==void 0)));}let{include:h,...d}=t,m=[this.router.incrementQueryStep({query:d,stepPath:[...n],getWhere:l,referenceGetter:y,isMany:u,relationName:s},r)];if(c&&typeof c=="object"&&Object.keys(c).length>0){let f=this.schema[t.resource];if(!f)throw new Error(`Resource ${t.resource} not found`);m.push(...Object.entries(c).flatMap(([b,R])=>{let w=f.relations[b];if(!w)throw new Error(`Relation ${b} not found for resource ${t.resource}`);let S=w.entity.name;return this.breakdownQuery({query:{resource:S,include:typeof R=="object"?R:void 0},stepPath:[...n,b],context:r,parentResource:t.resource})}));}return m}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(i=>i.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(i=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",i.length),n[e[0].stepPath.join(".")]=[{data:i}];});for(let i=1;i<e.length;i++){let c=e[i],o=c.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var l,y;let s=n[o];if(!s){n[c.stepPath.join(".")]=[];return}if(c.referenceGetter&&c.getWhere){let u=new Map;for(let p of s)for(let m of p.data){let g=(y=(l=m==null?void 0:m.value)==null?void 0:l.id)==null?void 0:y.value;if(!g)continue;let b=c.referenceGetter([m])[0];if(b){u.has(b)||u.set(b,new Set);let R=u.get(b);R&&R.add(g);}}let h=Array.from(u.keys());if(h.length===0){n[c.stepPath.join(".")]=[];return}let d=[];for(let p of h){let m=c.getWhere(p),g={...c,relationalWhere:m},f=await this.resolveStep(g,t),b=u.get(p);if(b)for(let R of Array.from(b))d.push({includedBy:R,data:f});}this.logger.debug("[QueryEngine] Resolved step",c.stepPath.join("."),"with results count:",d.reduce((p,m)=>p+m.data.length,0)),n[c.stepPath.join(".")]=d;}else {let u=await this.resolveStep(c,t);n[c.stepPath.join(".")]=[{data:u}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var c,o,s,l,y;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let n=new Map;for(let u of e){let h=u.stepPath.join("."),d=t[h]??[],p=Object.keys(u.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${h}"`,{resource:u.query.resource,includedRelations:p,resultGroups:d.length,isMany:u.isMany,relationName:u.relationName});for(let m of d){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${h}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let g of m.data){let f=(o=(c=g==null?void 0:g.value)==null?void 0:c.id)==null?void 0:o.value;if(!f){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${h}"`);continue}let b=h?`${h}.${f}`:f,R=[];if(u.stepPath.length>0&&m.includedBy){let S=u.stepPath.slice(0,-1).join(".");R=[S?`${S}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${b}" has parent keys:`,R,{stepPath:h,parentStepPath:S,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${b}" (no parent)`);let w=n.get(b);if(w){this.logger.debug(`[QueryEngine] assembleResults: Entity "${b}" already exists, adding parent keys:`,R);for(let S of R)w.includedBy.add(S);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${b}"`,{resource:u.query.resource,path:u.stepPath.at(-1)??"",isMany:u.isMany??false,relationName:u.relationName,includedRelations:p,parentKeys:R}),n.set(b,{data:g,includedBy:new Set(R),path:u.stepPath.at(-1)??"",isMany:u.isMany??false,relationName:u.relationName,resourceName:u.query.resource,includedRelations:p});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),i=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let u=r.length-1;u>=0;u--){let[h,d]=r[u],p=this.schema[d.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${h}"`,{resource:d.resourceName,path:d.path,isMany:d.isMany,relationName:d.relationName,includedRelations:d.includedRelations,parentKeys:Array.from(d.includedBy)});for(let m of d.includedRelations){let g=(l=(s=p==null?void 0:p.relations)==null?void 0:s[m])==null?void 0:l.type,f=!!d.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${h}"`,{relationType:g,hasRelation:f,resourceHasRelation:!!((y=p==null?void 0:p.relations)!=null&&y[m])}),d.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${h}"`,d.data.value[m]);else {let b=g==="many"?{value:[]}:{value:null};d.data.value[m]=b,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${h}" with`,b);}}if(d.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${h}" to resultData`),i.push(d.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to ${d.includedBy.size} parent(s)`);for(let m of Array.from(d.includedBy)){let g=n.get(m);if(!g){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${h}"`);continue}let f=d.relationName??d.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to parent "${m}" via relation "${f}"`,{isMany:d.isMany,parentHasRelation:!!g.data.value[f]}),d.isMany?(g.data.value[f]??={value:[]},g.data.value[f].value.push(d.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${h}" to many relation "${f}" on parent "${m}"`,{arrayLength:g.data.value[f].value.length})):(g.data.value[f]=d.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${f}" on parent "${m}" to "${h}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${i.length} root items`),i}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:n,relationalWhere:r}=e,i=n.where&&r?P(n.where,r):r??n.where,c=i?{...n,where:i}:n;return H(this.router.get(c,t)).then(o=>(this.loadStepResults(e,o),o))}loadStepResults(e,t$1){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t$1,null,2));let n=G(e),r=this.queryNodes.get(n),i=e.query.resource;if(!r)return;let c=this.getRelationalColumns(i);for(let o of t$1){let s=t(o),l=s.id;this.ensureObjectNode(l,i,n),r.trackedObjects.add(l);for(let[y,{relationName:u,targetResource:h}]of Array.from(c)){let d=s[y];if(d){this.ensureObjectNode(d,h);let p=this.getInverseRelationName(i,h,u);this.storeRelation(l,d,u,p);}}this.loadNestedRelations(i,l,s),this.logger.debug("[QueryEngine] Loaded nested relations for",l);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[i,c]of Object.entries(r.relations)){let o=n[i];if(!o)continue;let s=c.entity.name,l=this.getInverseRelationName(e,s,i);if(c.type==="one")o&&typeof o=="object"&&o.id&&(this.ensureObjectNode(o.id,s),this.storeRelation(t,o.id,i,l),this.loadNestedRelations(s,o.id,o));else if(c.type==="many"&&Array.isArray(o)){for(let y of o)if(y&&typeof y=="object"&&y.id){this.ensureObjectNode(y.id,s);let u=this.getInverseRelationName(s,e,i);u&&this.storeRelation(y.id,t,u,i),this.loadNestedRelations(s,y.id,y);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let i=this.queryNodes.get(r);if(!i||!i.relationName)continue;let c=this.buildIncludeFromChildQueries(r);n[i.relationName]=Object.keys(c).length>0?c:true;}return n}sendInsertsForTree(e,t,n){var o,s;let r=(s=(o=t==null?void 0:t.value)==null?void 0:o.id)==null?void 0:s.value;if(!r)return;let i={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let l of Array.from(e.subscriptions))try{l(i);}catch(y){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:y,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let l of Array.from(e.childQueries)){let y=this.queryNodes.get(l);if(!y||!y.relationName)continue;let u=y.relationName,h=y.queryStep.query.resource,d=t.value[u];if(!d)continue;let p=d.value;if(Array.isArray(p))for(let m of p)this.sendInsertsForTree(y,m,h);else p&&typeof p=="object"&&this.sendInsertsForTree(y,p,h);}}handleMutation(e,t$1){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=t(t$1);if(!n)return;let r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,r);let i=this.getRelationalColumns(e.resource);for(let[o,{relationName:s,targetResource:l}]of Array.from(i)){let y=n[o];if(y){this.ensureObjectNode(y,l);let u=this.getInverseRelationName(e.resource,l,s);this.storeRelation(e.resourceId,y,s,u);}}let c=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(o=>{for(let s of o){let l=this.queryNodes.get(s);if(l){l.trackedObjects.add(e.resourceId),c&&c.matchedQueries.add(s);for(let y of Array.from(l.subscriptions))try{y(e);}catch(u){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:u,queryHash:l.hash,resource:e.resource,resourceId:e.resourceId,stepPath:l.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let n=t(t$1);if(!n)return;let r=this.objectNodes.get(e.resourceId),i=new Set((r==null?void 0:r.matchedQueries)??[]);r||(r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,r)),this.updateRelationsFromMutation(e.resource,e.resourceId,n,e.payload),this.getMatchingQueries(e,n).then(c=>{let o=new Set(c),s=[],l=[],y=[];for(let h of c)i.has(h)?y.push(h):s.push(h);for(let h of Array.from(i))o.has(h)||l.push(h);for(let h of s){let d=this.queryNodes.get(h);d&&d.trackedObjects.add(e.resourceId);}for(let h of l){let d=this.queryNodes.get(h);d&&d.trackedObjects.delete(e.resourceId);}let u=this.objectNodes.get(e.resourceId);if(u){for(let h of s)u.matchedQueries.add(h);for(let h of l)u.matchedQueries.delete(h);}for(let h of [...l,...y]){let d=this.queryNodes.get(h);if(d)for(let p of Array.from(d.subscriptions))try{p(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:d.hash,resource:e.resource,resourceId:e.resourceId,stepPath:d.queryStep.stepPath.join(".")});}}if(s.length>0)for(let h of s){let d=this.queryNodes.get(h);if(!d)continue;let p=this.buildIncludeFromChildQueries(h);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(p).length>0?p:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(d,m[0],e.resource);});}});return}}getMatchingQueries(e,t$1){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?H([]):Promise.all(n.map(async r=>{let i=r.queryStep.query.where,c=r.queryStep.query.resource,o=e.resourceId,s=this.objectNodes.get(o);if(!s)return {hash:r.hash,matches:false};if(r.relationName){let d=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,p=d==null?void 0:d.queryStep.query.resource,m=p?this.getInverseRelationName(p,c,r.relationName):void 0,g=m?s.referencesObjects.get(m):void 0;if(!g)return {hash:r.hash,matches:false};let f=this.objectNodes.get(g);return !f||!d||!f.matchedQueries.has(d.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!i)return {hash:r.hash,matches:true};let l=w(i,c,this.schema),y=Object.keys(l).length>0;if(!y&&t$1!==void 0)return {hash:r.hash,matches:x(t$1,i)};let u=await this.storage.get({resource:c,where:{id:o},include:y?l:void 0});if(!u||u.length===0)return {hash:r.hash,matches:false};let h=t(u[0]);return h?{hash:r.hash,matches:x(h,i)}:{hash:r.hash,matches:false}})).then(r=>r.filter(i=>i.matches).map(i=>i.hash))}};var ge=b(Z(),1);var L=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),K=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),Ve=K.superRefine((a,e)=>{a.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),fe=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),C=fe.extend({procedure:z$1.string(),payload:z$1.any().optional()}),Q=fe.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:Ve});z$1.union([Q,C]);var me=L.omit({resource:true}),J=C.omit({id:true,type:true,resource:true,procedure:true}),Y=Q.omit({id:true,type:true,resource:true,procedure:true});z$1.union([Y,J]);var X=a=>{if(a==null)return a;if(a==="null")return null;if(Array.isArray(a))return a.map(X);if(typeof a=="object"&&a.constructor===Object){let e={};for(let[t,n]of Object.entries(a))e[t]=X(n);return e}return a},be=a=>{let e=a.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,i={headers:r,cookies:r.cookie?ge.default.parse(r.cookie):{}},c=new URL(t.url),o=c.pathname.split("/"),s=c.searchParams,l=X(Ge.parse(s.toString())),y=await((n=a.contextProvider)==null?void 0:n.call(a,{transport:"HTTP",headers:i.headers,cookies:i.cookies,queryParams:l}))??{};if(t.method==="GET"){let u=o[o.length-1],{success:h,data:d,error:p}=me.safeParse(l);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let m=await a.handleQuery({req:{...i,...d,type:"QUERY",resource:u,context:y,queryParams:l}});return !m||!m.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(m.data)}if(t.method==="POST")try{let u=o[o.length-1],h=o[o.length-2],d=t.body?await t.json():{},p;if(u==="insert"||u==="update"){let{success:g,data:f,error:b}=Y.safeParse(d);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=f;}else {let{success:g,data:f,error:b}=J.safeParse(d);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=f;}let m=await a.handleMutation({req:{...i,type:"MUTATE",resource:h,input:p.payload,context:y,resourceId:p.resourceId,procedure:u==="insert"||u==="update"?u.toUpperCase():u,queryParams:{}}});return Response.json(m)}catch(u){return e.error("Error parsing mutation from the client:",u),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var we=b(Z(),1);var O=z$1.string(),Ze=L.extend({id:O,type:z$1.literal("SUBSCRIBE")}),Ke=L.extend({id:O,type:z$1.literal("UNSUBSCRIBE")}),Je=L.extend({id:O,type:z$1.literal("QUERY")}),Re=Q.extend({id:O}),Ye=C.extend({id:O}),Xe=z$1.union([Ye,Re]),Te=z$1.union([Ze,Je,Xe,Ke]),et=z$1.object({id:O,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),tt=z$1.object({id:O,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([et,tt,Re]);z$1.object({resource:z$1.string(),data:z$1.array(K)});var Se=a=>{let e={},t=a.logger;return (n,r)=>{var u;let i=h=>{n.send(JSON.stringify(h));},c=D(),o=new Map,s={headers:r.headers,cookies:typeof r.headers.cookie=="string"?we.default.parse(r.headers.cookie):{}},l=parse(r.url.split("?")[1]),y=(u=a.contextProvider)==null?void 0:u.call(a,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:l});e[c]=n,t.info("Client connected:",c),n.on("message",async h=>{try{t.debug("Message received from the client:",h);let d=Te.parse(JSON.parse(h.toString()));if(d.type==="SUBSCRIBE"||d.type==="QUERY"){let{type:p,id:m,...g}=d,f=p==="SUBSCRIBE",b=await a.handleQuery({req:{...s,...g,type:"QUERY",context:await y??{},queryParams:l},subscription:f?R=>{var w;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(w=e[c])==null||w.send(JSON.stringify(R));}:void 0});if(!b||!b.data)throw new Error("Invalid resource");f&&b.unsubscribe&&o.set(v(g),b.unsubscribe),i({id:m,type:"REPLY",data:{resource:g.resource,data:(b.data??[]).map(R=>R.value)}});}else if(d.type==="UNSUBSCRIBE"){let{type:p,id:m,...g}=d,f=o.get(v(g));f&&(f(),o.delete(v(g)));}else if(d.type==="MUTATE"){let{resource:p}=d;t.debug("Received mutation from client:",d);try{let m=await a.handleMutation({req:{...s,type:"MUTATE",resource:p,input:d.payload,context:{messageId:d.id,...await y??{}},resourceId:d.resourceId,procedure:d.procedure,queryParams:l}});d.procedure&&d.procedure!=="INSERT"&&d.procedure!=="UPDATE"&&i({id:d.id,type:"REPLY",data:m});}catch(m){i({id:d.id,type:"REJECT",resource:p,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(d){t.error("Error handling message from the client:",d);}}),n.on("close",()=>{t.info("Connection closed",c),delete e[c];for(let h of Array.from(o.values()))h();});}};function Me(a){let e=`${a.protocol}://${a.hostname}${a.url}`,t=new Headers;return Object.entries(a.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:a.method,headers:t,body:a.body&&a.method!=="GET"?JSON.stringify(a.body):void 0})}var Ht=(a,e,t)=>{a.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Se(e)),a.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{be(e)(Me(n)).then(c=>c.json().then(o=>r.status(c.status).send(o)));});};var ee=class a{routes;constructor(e){this.routes=e.routes;}static create(e){return new a(e)}},Yt=a=>ee.create({...a}),it=a=>({handler:e=>({inputValidator:a??z$1.undefined(),handler:e})}),te=class a{resourceSchema;middlewares;customMutations;authorization;constructor(e,t,n){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=n;}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new a(this.resourceSchema,e({mutation:it}),this.authorization)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},i=v(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:i}})(e);handleMutation=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{if(!r.procedure)throw new Error("Procedure is required for mutations");let i=this.customMutations[r.procedure];if(i){let c=i.inputValidator.parse(r.input);return r.input=c,i.handler({req:r,db:t})}else {if(r.procedure==="INSERT"||r.procedure==="UPDATE")return this.handleSet({req:r,db:t,operation:r.procedure,schema:n});throw new Error(`Unknown procedure: ${r.procedure}`)}})(e);getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t$1,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let i=await t$1.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&i)throw new Error("Resource already exists");if(n==="UPDATE"&&!i)throw new Error("Resource not found");return t$1.transaction(async({trx:c})=>{var y,u,h,d,p,m,g;let[o,s]=this.resourceSchema.mergeMutation("set",e.input,i);if(!s)throw new Error("Mutation rejected");if(n==="INSERT"){let f=await c.rawInsert(e.resource,e.resourceId,o,(y=e.context)==null?void 0:y.messageId),b=t(f);if(b.id=b.id??e.resourceId,(u=this.authorization)!=null&&u.insert){let R=this.authorization.insert({ctx:e.context,value:b});if(typeof R=="boolean"){if(!R)throw new Error("Not authorized")}else {let w$1=w(R,e.resource,r),S=Object.keys(w$1).length>0?await c.rawFindById(e.resource,e.resourceId,w$1):f,x$1=t(S);if(x$1.id=x$1.id??e.resourceId,!x(x$1,R))throw new Error("Not authorized")}}return {data:f,acceptedValues:s}}if((d=(h=this.authorization)==null?void 0:h.update)!=null&&d.preMutation){let f=t(i);f.id=f.id??e.resourceId;let b=this.authorization.update.preMutation({ctx:e.context,value:f});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let R=w(b,e.resource,r),w$1=Object.keys(R).length>0?await c.rawFindById(e.resource,e.resourceId,R):i,S=t(w$1);if(S.id=S.id??e.resourceId,!x(S,b))throw new Error("Not authorized")}}let l=await c.rawUpdate(e.resource,e.resourceId,o,(p=e.context)==null?void 0:p.messageId);if((g=(m=this.authorization)==null?void 0:m.update)!=null&&g.postMutation){let f=t(l);f.id=f.id??e.resourceId;let b=this.authorization.update.postMutation({ctx:e.context,value:f});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let R=w(b,e.resource,r),w$1=Object.keys(R).length>0?await c.rawFindById(e.resource,e.resourceId,R):l,S=t(w$1);if(S.id=S.id??e.resourceId,!x(S,b))throw new Error("Not authorized")}}return {data:l,acceptedValues:s}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>i=>r({req:i,next:n}),e)(t)}},re=class a{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new te(e,void 0,t).use(...this.middlewares)}use(...e){return new a([...this.middlewares,...e])}static create(){return new a}},Xt=re.create;var z=class{async insert(e,t$1){let n=new Date().toISOString();return t(await this.rawInsert(e.name,t$1.id,{value:Object.fromEntries(Object.entries(t$1).map(([r,i])=>[r,{value:i,_meta:{timestamp:n}}]))}))}async update(e,t$1,n){let r=new Date().toISOString(),{id:i,...c}=n;return t(await this.rawUpdate(e.name,t$1,{value:Object.fromEntries(Object.entries(c).map(([o,s])=>[o,{value:s,_meta:{timestamp:r}}]))}))}};function F(a,e,t,n){if(!a)throw new Error("Schema not initialized");let r=a[e];if(!r)throw new Error("Resource not found");let i=n.$or,c=n.$and;return (i?t.or:t.and)(i?n.$or.map(o=>F(a,e,t,o)):c?n.$and.map(o=>F(a,e,t,o)):Object.entries(n).map(([o,s])=>{var l,y;if(r.fields[o])return (s==null?void 0:s.$eq)!==void 0?t(`${e}.${o}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?t(`${e}.${o}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((l=s==null?void 0:s.$not)==null?void 0:l.$in)!==void 0?t(`${e}.${o}`,"not in",s.$not.$in):((y=s==null?void 0:s.$not)==null?void 0:y.$eq)!==void 0?t(`${e}.${o}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):t(`${e}.${o}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?t(`${e}.${o}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?t(`${e}.${o}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?t(`${e}.${o}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?t(`${e}.${o}`,"<=",s.$lte):t(`${e}.${o}`,s===null?"is":"=",s);if(r.relations[o]){let u=r.relations[o],h=u.entity.name;return u.type==="many"?t.exists(ne(a,h,t.selectFrom(h).select("id").whereRef(u.foreignColumn,"=",`${e}.id`),s)):F(a,h,t,s)}return null}).filter(Boolean))}function _(a,e,t,n){let r=a[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let i of n.$and)t=_(a,e,t,i);return t}else if(n.$or){for(let i of n.$or)t=_(a,e,t,i);return t}for(let[i,c]of Object.entries(n)){if(!r.relations[i])continue;let o=r.relations[i],s=o.entity.name,l=o.type==="one"?"id":o.foreignColumn,y=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(s,`${s}.${l}`,`${e}.${y}`),c instanceof Object&&!Array.isArray(c)&&c!==null&&(t=_(a,s,t,c));}return t}function ne(a,e,t,n){return !n||Object.keys(n).length===0?t:(t=_(a,e,t,n),t.where(r=>F(a,e,r,n)))}function V(a,e,t,n){if(!n)return t;if(!a)throw new Error("Schema not initialized");let r=a[e];if(!r)throw new Error(`Resource not found: ${e}`);for(let i of Object.keys(n)){if(!r.relations[i])throw new Error(`Relation ${i} not found in resource ${e}`);let c=r.relations[i],o=c.entity.name,s=n[i],l=c.type==="one"?"id":c.foreignColumn,y=c.type==="one"?c.relationalColumn:"id",u=c.type==="one"?jsonObjectFrom:jsonArrayFrom,h=typeof s=="object"&&s!==null;t=t.select(d=>{let p=d.selectFrom(o).selectAll(o).whereRef(`${o}.${l}`,"=",`${e}.${y}`).select(m=>jsonObjectFrom(m.selectFrom(`${o}_meta`).selectAll(`${o}_meta`).whereRef(`${o}_meta.id`,"=",`${o}.id`)).as("_meta"));return h&&(p=V(a,o,p,s)),u(p).as(i)});}return t}var je="42701",ie=class a extends z{db;schema;logger;server;mutationStack=[];constructor(e,t,n,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.schema=t,this.logger=n,this.server=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,n){var i;this.schema=e,this.logger=t,this.server=n;let r=await this.db.introspection.getTables();for(let[c,o]of Object.entries(e)){let s=r.find(u=>u.name===c);s||await this.db.schema.createTable(c).ifNotExists().execute();let l=`${c}_meta`,y=r.find(u=>u.name===l);y||await this.db.schema.createTable(l).ifNotExists().execute();for(let[u,h]of Object.entries(o.fields)){let d=s==null?void 0:s.columns.find(g=>g.name===u),p=h.getStorageFieldType();d?d.dataType!==p.type&&((i=this.logger)==null||i.warn("Column type mismatch:",u,"expected to have type:",p.type,"but has type:",d.dataType)):(await this.db.schema.alterTable(c).addColumn(u,p.type,g=>{let f=g;return p.unique&&(f=f.unique()),p.nullable||(f=f.notNull()),p.references&&(f=f.references(p.references)),p.primary&&(f=f.primaryKey()),p.default!==void 0&&(f=f.defaultTo(p.default)),f}).execute().catch(g=>{var f;if(g.code!==je)throw (f=this.logger)==null||f.error("Error adding column",u,g),g}),p.index&&await this.db.schema.createIndex(`${c}_${u}_index`).on(c).column(u).execute().catch(()=>{})),y!=null&&y.columns.find(g=>g.name===u)||await this.db.schema.alterTable(l).addColumn(u,"varchar",g=>{let f=g;return p.primary&&(f=f.primaryKey().references(`${c}.${u}`)),f}).execute().catch(g=>{var f;if(g.code!==je)throw (f=this.logger)==null||f.error("Error adding meta column",u,g),g});}}}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(c=>jsonObjectFrom(c.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));r=V(this.schema,e,r,n);let i=await r.executeTakeFirst();if(i)return this.convertToMaterializedLiveType(i)}async findOne(e,t$1,n){let r=await this.rawFindById(e.name,t$1,n==null?void 0:n.include);if(r)return t(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:i,sort:c}=e,o=this.db.selectFrom(t).selectAll(t).select(l=>jsonObjectFrom(l.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));o=ne(this.schema,t,o,n),o=V(this.schema,t,o,r),i!==void 0&&(o=o.limit(i)),c!==void 0&&c.forEach(l=>{o=o.orderBy(l.key,l.direction);});let s=await o.execute();return s.length===0?[]:s.map(l=>this.convertToMaterializedLiveType(l))}async find(e,t$1){return (await this.get({resource:e.name,where:t$1==null?void 0:t$1.where,include:t$1==null?void 0:t$1.include,limit:t$1==null?void 0:t$1.limit,sort:t$1==null?void 0:t$1.sort})).map(r=>t(r))}async rawInsert(e,t,n,r){var s;let i={},c={};for(let[l,y]of Object.entries(n.value)){let u=(s=y._meta)==null?void 0:s.timestamp;u&&(i[l]=y.value,c[l]=u);}await this.db.insertInto(e).values({...i,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...c,id:t}).execute();});let o=this.buildMutation(e,t,"INSERT",n,r);return o&&this.trackMutation(o,n),n}async rawUpdate(e,t,n,r){var s;let i={},c={};for(let[l,y]of Object.entries(n.value)){let u=(s=y._meta)==null?void 0:s.timestamp;u&&(i[l]=y.value,c[l]=u);}await Promise.all([this.db.updateTable(e).set(i).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...c,id:t}).onConflict(l=>l.column("id").doUpdateSet(c)).execute()]);let o=this.buildMutation(e,t,"UPDATE",n,r);if(o){let l=await this.rawFindById(e,t);l&&this.trackMutation(o,l);}return n}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let i=Math.random().toString(36).substring(2,15),c=this.mutationStack,o=[];this.mutationStack=o;let s=await this.db.savepoint(i).execute();try{return await e({trx:this,commit:async()=>{await s.releaseSavepoint(i).execute(),c.push(...o);},rollback:async()=>{await s.rollbackToSavepoint(i).execute(),o.length=0;}}).then(l=>s.isCommitted||s.isRolledBack?l:s.releaseSavepoint(i).execute().then(()=>(c.push(...o),l)))}catch(l){throw await s.rollbackToSavepoint(i).execute().catch(()=>{}),o.length=0,l}finally{this.mutationStack=c;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let i=new a(r,this.schema,this.logger,this.server);return i.mutationStack=t,await e({trx:i,commit:async()=>{await r.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(c=>r.isCommitted||r.isRolledBack?c:r.commit().execute().then(()=>(this.notifyMutations(t),c)))}catch(i){throw await r.rollback().execute(),t.length=0,i}finally{this.mutationStack=n;}}get internalDB(){return this.db}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[n,r])=>{var i,c,o;return n==="_meta"||(n==="id"?t[n]={value:r}:Array.isArray(r)?t[n]={value:r.map(s=>this.convertToMaterializedLiveType(s)),_meta:{timestamp:(i=e==null?void 0:e._meta)==null?void 0:i[n]}}:typeof r=="object"&&r!==null&&!(r instanceof Date)?t[n]={...this.convertToMaterializedLiveType(r),_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[n]}}:t[n]={value:r,_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[n]}}),t},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",r=typeof t.startTransaction=="function",i=typeof t.savepoint=="function",c=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||i&&c}buildMutation(e,t,n,r,i){var o;let c={};for(let[s,l]of Object.entries(r.value)){if(s==="id")continue;let y=(o=l._meta)==null?void 0:o.timestamp;y&&(c[s]={value:l.value,_meta:{timestamp:y}});}return Object.keys(c).length===0?null:{id:i??D(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:c}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let n=e;for(let r of n)this.server.notifySubscribers(r,t);}else {let n=e;for(let{mutation:r,entityData:i}of n)this.server.notifySubscribers(r,i);}}};var se=class a{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=z$2({level:e.logLevel??y.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new U({router:{get:async(n,r)=>{var u;let{headers:i,cookies:c,queryParams:o,context:s}=(r==null?void 0:r.context)??{};if(!(r!=null&&r.batcher))throw new Error("Batcher is required");let l={...n,type:"QUERY",headers:i,cookies:c,queryParams:o,context:s},y=await((u=this.router.routes[n.resource])==null?void 0:u.handleQuery({req:l,batcher:r.batcher}));return (y==null?void 0:y.data)??[]},incrementQueryStep:(n,r={})=>{var o;let i=(o=this.router.routes[n.query.resource])==null?void 0:o.getAuthorizationClause({...n.query,type:"QUERY",headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context});if(typeof i=="boolean"&&!i)throw new Error("Not authorized");let c=P(n.query.where,typeof i=="object"?i:void 0);return {...n,query:{...n.query,where:c}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new a(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:i,context:c,...o}=t,s={headers:n,cookies:r,queryParams:i,context:c},l=e.subscription?this.queryEngine.subscribe(o,u=>{var h;(h=e.subscription)==null||h.call(e,u);},s):void 0;return {data:await this.queryEngine.get(o,{context:s}),unsubscribe:l}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}notifySubscribers(e,t){this.queryEngine.handleMutation(e,t);}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>i=>r({req:i,next:n}),e)(t)}},br=se.create;
|
|
2
|
+
export{te as Route,re as RouteFactory,ee as Router,ie as SQLStorage,se as Server,z as Storage,Ht as expressAdapter,Xt as routeFactory,Yt as router,br as server};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@live-state/sync",
|
|
3
|
-
"version": "0.0.6-canary-
|
|
3
|
+
"version": "0.0.6-canary-12",
|
|
4
4
|
"private": false,
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -35,12 +35,13 @@
|
|
|
35
35
|
"@vitest/coverage-v8": "3.2.4",
|
|
36
36
|
"cookie": "^1.0.2",
|
|
37
37
|
"express": "^4.21.2",
|
|
38
|
+
"express-ws": "^5.0.2",
|
|
38
39
|
"jsdom": "^26.1.0",
|
|
39
40
|
"pg": "^8.15.6",
|
|
40
|
-
"express-ws": "^5.0.2",
|
|
41
41
|
"react": "18.0.0",
|
|
42
42
|
"react-dom": "^18.2.0",
|
|
43
|
-
"tsup": "^8.
|
|
43
|
+
"tsup": "^8.5.1",
|
|
44
|
+
"tsx": "^4.19.2",
|
|
44
45
|
"typescript": "5.5.4",
|
|
45
46
|
"ulid": "^3.0.0",
|
|
46
47
|
"vitest": "^3.2.4",
|
|
@@ -95,6 +96,7 @@
|
|
|
95
96
|
"lint": "biome lint",
|
|
96
97
|
"typecheck": "tsc --noEmit --project . && tsc --noEmit --project src/client",
|
|
97
98
|
"test": "vitest run",
|
|
98
|
-
"test:watch": "vitest"
|
|
99
|
+
"test:watch": "vitest",
|
|
100
|
+
"benchmark": "tsx benchmark/benchmark.ts"
|
|
99
101
|
}
|
|
100
102
|
}
|
package/dist/chunk-3SQDLIFN.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {xxHash32}from'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 V=(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 $=(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}},q=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)}},N=p.create,D=p.createId,W=p.createReference,L=class t extends y{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},P=L.create,h=class t extends y{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},k=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)}},G=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)}},H=(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,B=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 Z=t=>xxHash32(JSON.stringify(t)).toString(32),C=(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=C(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}},ee=t=>new R(t);export{V as a,$ as b,o as c,m as d,y as e,v as f,q as g,p as h,N as i,D as j,W as k,L as l,P as m,h as n,k as o,g as p,G as q,f as r,H as s,x as t,B as u,Z as v,C as w,c as x,T as y,ee as z};
|
package/dist/chunk-RCXJM33Z.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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};
|