@live-state/sync 1.0.0-canary-1 → 1.0.0-canary-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { B as BootstrapStatusChangeEvent, F as Client, A as ClientBootstrapStatus, E as ClientEvents, C as ClientOptions, a as ClientRouterConstraint, l as ClientState, p as ClientStorageLoadedEvent, o as ConnectionStateChangeEvent, q as DataLoadReplyEvent, D as DataLoadRequestedEvent, M as MessageReceivedEvent, s as MutationReceivedEvent, t as MutationRejectedEvent, r as MutationSentEvent, e as OptimisticHandlerContext, y as OptimisticMutationAppliedEvent, z as OptimisticMutationUndoneEvent, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, Q as QueryExecutedEvent, w as QuerySubscriptionTriggeredEvent, x as StoreStateUpdatedEvent, S as SubscriptionCreatedEvent, v as SubscriptionRemovedEvent, G as createClient, d as defineOptimisticMutations, m as useClientState, u as useLiveQuery, n as useLoadData } from './index-DjBla1td.js';
1
+ export { B as BootstrapStatusChangeEvent, F as Client, A as ClientBootstrapStatus, E as ClientEvents, C as ClientOptions, a as ClientRouterConstraint, l as ClientState, p as ClientStorageLoadedEvent, o as ConnectionStateChangeEvent, q as DataLoadReplyEvent, D as DataLoadRequestedEvent, M as MessageReceivedEvent, s as MutationReceivedEvent, t as MutationRejectedEvent, r as MutationSentEvent, e as OptimisticHandlerContext, y as OptimisticMutationAppliedEvent, z as OptimisticMutationUndoneEvent, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, Q as QueryExecutedEvent, w as QuerySubscriptionTriggeredEvent, x as StoreStateUpdatedEvent, S as SubscriptionCreatedEvent, v as SubscriptionRemovedEvent, G as createClient, d as defineOptimisticMutations, m as useClientState, u as useLiveQuery, n as useLoadData } from './index-DOU7wys1.js';
2
2
  import '@standard-schema/spec';
3
3
  import 'zod';
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import {c,a,d,b}from'./chunk-YPTDCIAN.js';import {a as a$1}from'./chunk-RSSRYEM3.js';export{b as defineOptimisticMutations}from'./chunk-RSSRYEM3.js';import {useSyncExternalStore,useMemo,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z as z$1}from'zod';import {stringify}from'qs';import Ge from'fast-deep-equal';import {openDB}from'idb';var T=o=>xxHash32(JSON.stringify(o)).toString(32);var R=(o,e,t=false)=>Object.entries(e).every(([i,n])=>{if(i==="$and")return n.every(s=>R(o,s,t));if(i==="$or")return n.some(s=>R(o,s,t));let r=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let a=o[i];return a===void 0?false:t?!n.$in.includes(a):n.$in.includes(a)}if(n.$not!==void 0&&!t)return R(o,{[i]:n.$not},true);if(n.$gt!==void 0){let a=o[i];return typeof a!="number"?false:t?a<=n.$gt:a>n.$gt}if(n.$gte!==void 0){let a=o[i];return typeof a!="number"?false:t?a<n.$gte:a>=n.$gte}if(n.$lt!==void 0){let a=o[i];return typeof a!="number"?false:t?a>=n.$lt:a<n.$lt}if(n.$lte!==void 0){let a=o[i];return typeof a!="number"?false:t?a>n.$lte:a<=n.$lte}let s=o[i];return !s||typeof s!="object"&&!Array.isArray(s)?false:Array.isArray(s)?t?!s.some(a=>R(a,n,false)):s.some(a=>R(a,n,false)):R(s,n,t)}return t?o[i]!==r:o[i]===r}),j=o=>{if(typeof o!="object"||o===null)return false;let e=o;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},C={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},J=class{level;prefix;constructor(e={}){this.level=e.level??C.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=C.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=C.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=C.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=C.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=C.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},de=o=>new J(o);var Y=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=T(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let n={subscribe:r=>{let s=this.subscriptions.get(i);return s.callbacks.add(r),s.unsubscribe||(s.unsubscribe=()=>{},s.unsubscribe=e.subscribe(()=>{s.callbacks.forEach(a=>{a();});})),()=>{var a;(a=this.subscriptions.get(i))==null||a.callbacks.delete(r),setTimeout(()=>{var u;let l=this.subscriptions.get(i);l&&l.callbacks.size===0&&((u=l.unsubscribe)==null||u.call(l),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,n),this.subscriptions.get(i).subscribe}},Ce=new Y,Xe=o=>useSyncExternalStore(Ce.getOrStoreSubscription(o),o.get),Ze=o=>{let{subscribe:e,getSnapshot:t}=useMemo(()=>{let i={bootstrapStatus:o.bootstrapStatus,connected:o.ws.connected()},n=()=>{let r={bootstrapStatus:o.bootstrapStatus,connected:o.ws.connected()};(r.bootstrapStatus!==i.bootstrapStatus||r.connected!==i.connected)&&(i=r);};return {subscribe:r=>o.addEventListener(s=>{(s.type==="BOOTSTRAP_STATUS_CHANGE"||s.type==="CONNECTION_STATE_CHANGE")&&(n(),r());}),getSnapshot:()=>i}},[o]);return useSyncExternalStore(e,t,t)},et=(o,e)=>{useEffect(()=>{let t=o.load(e.buildQueryRequest());return ()=>{t();}},[e,o.load]);};var k=class o{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,i,n,r,s,a,l){this._collection=e,this._client=t,this._where=i??{},this._include=n??{},this._limit=r,this._single=s,this._sort=a,this._shouldAwait=l,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new o(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new o(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new o(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 o(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let i=[...this._sort??[],{key:e,direction:t}];return new o(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(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,i){return new o(e,t,void 0,void 0,void 0,void 0,void 0,i??false)}};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(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()});var X=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),xe=X.superRefine((o,e)=>{o.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Le=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),ye=z$1.object({timestamp:z$1.string().optional(),originMutationId:z$1.string().optional()}).optional(),he=Le.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:ye}),Z=z$1.object({id:z$1.string().optional(),type:z$1.literal("SYNC"),resource:z$1.string(),resourceId:z$1.string(),op:z$1.enum(["INSERT","UPDATE","DELETE"]),payload:xe,meta:ye}),ee=(o,e)=>{o.op==="DELETE"&&Object.keys(o.payload).length>0&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"DELETE delta payload must be empty"});};Z.superRefine(ee);var me=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var x=z$1.string(),te=me,Ee=z$1.object({id:x,type:z$1.literal("SUBSCRIBE")}).and(te),Ie=z$1.object({id:x,type:z$1.literal("UNSUBSCRIBE")}).and(te),we=z$1.object({id:x,type:z$1.literal("QUERY")}).and(te),Ae=z$1.object({id:x,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),Oe=he.extend({id:x}),je=Oe;z$1.union([Ee,we,Ae,je,Ie]);var _e=z$1.object({id:x,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),De=z$1.object({id:x,type:z$1.literal("REPLY"),data:z$1.any()}),Ve=Z.extend({id:x}).superRefine(ee),fe=z$1.union([_e,De,Ve]),Te=z$1.object({resource:z$1.string(),data:z$1.array(X)});var N=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(n=>{n(t);});}};var ie=o=>typeof o=="object"&&o!==null&&"value"in o&&!Array.isArray(o),O=o=>o?Array.isArray(o.value)?o.value.map(t=>ie(t)?O(t):t):typeof o.value!="object"||o.value===null||o.value instanceof Date?o.value:Object.fromEntries(Object.entries(o.value).map(([t,i])=>Array.isArray(i)?[t,i.map(n=>ie(n)?O(n):n)]:ie(i)?[t,O(i)]:[t,i])):void 0;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 n={id:e,type:t,referencedBy:new Map(i.map(r=>[r,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,n),n}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),n=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!n)throw new Error(`Target node with id ${t} does not exist`);i.references.set(n.type,t);let r=n.referencedBy.get(i.type);r&&r instanceof Set?r.add(e):n.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let n=i.references.get(t);if(!n)return;i.references.delete(t);let r=this.nodes.get(n);if(!r)return;let s=r.referencedBy.get(i.type);s&&(s instanceof Set?s.delete(e):r.referencedBy.delete(i.type),this.notifySubscribers(n)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,n])=>{(n instanceof Set?Array.from(n.values()):[n]).forEach(s=>{let a=this.nodes.get(s);!a||!a.references.get(i)||(a.references.delete(i),this.notifySubscribers(s));});}),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 n;try{i(e);}catch(r){(n=this.logger)==null||n.error(`Error in node subscription for node ${e}:`,r);}});}getAllNodes(){return Array.from(this.nodes.values())}};var ne="__meta",B="databases",$=class{db;async init(e,t){var u,d;if(typeof window>"u")return;let n=((u=(await window.indexedDB.databases()).find(c=>c.name===t))==null?void 0:u.version)??1,r=await T(e),s=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,p])=>[c,await T(p)]))),a=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(B)||c.createObjectStore(B);}}),l=(d=await this.getAll(a,B))==null?void 0:d[t];(l==null?void 0:l.schemaHash)!==r&&n++,this.db=await openDB(t,n,{async upgrade(c){[...Object.keys(e),ne].forEach(p=>{(l==null?void 0:l.objectHashes[p])!==s[p]&&c.objectStoreNames.contains(p)&&c.deleteObjectStore(p),c.objectStoreNames.contains(p)||c.createObjectStore(p);}),await a.put(B,{schemaHash:r,objectHashes:s},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var n;return (n=this.db)==null?void 0:n.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(ne,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(ne,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,n]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((r,s)=>[n[s],r]))}};var G=class{constructor(e,t,i,n,r,s){this.schema=e;this.logger=i,this.optimisticObjGraph=new W(i),this.kvStorage=new $,this.onQuerySubscriptionTriggered=s,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{Promise.all([this.kvStorage.getMeta("mutationStack"),this.kvStorage.getMeta("customMutationStack"),this.kvStorage.getMeta("customMutationIndex")]).then(([a,l,u])=>{a&&Object.keys(a).length>0&&(this.optimisticMutationStack=a),l&&l.length>0&&(this.customMutationStack=l),u&&Object.keys(u).length>0&&(this.customMutationIndex=u),n==null||n(this.optimisticMutationStack,this.customMutationStack,this.customMutationIndex);}).then(()=>{Object.entries(this.schema).forEach(([a])=>{this.kvStorage.get(a).then(l=>{if(!l||Object.keys(l).length===0){r==null||r(a,0);return}let u=Object.entries(l).map(([d,c])=>({...c,id:{value:d}}));r==null||r(a,u.length),this.loadConsolidatedState(a,u);});});}).catch(a=>{i.debug("Storage initialization failed (may not be available in this environment):",a);});});}rawObjPool={};optimisticMutationStack={};customMutationStack=[];optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;customMutationIndex={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e,t,i=false){var l;let n=t??T(e);if(this.querySnapshots[n]&&!i){let u=this.querySnapshots[n];if(u)return u}let r,s=(l=e.where)==null?void 0:l.id;s===void 0?r=Object.keys(this.optimisticRawObjPool[e.resource]??{}):typeof s=="string"?r=[s]:typeof s=="object"&&s!==null?"$in"in s&&Array.isArray(s.$in)?r=s.$in:"$eq"in s&&typeof s.$eq=="string"?r=[s.$eq]:r=Object.keys(this.optimisticRawObjPool[e.resource]??{}):r=Object.keys(this.optimisticRawObjPool[e.resource]??{});let a=r.flatMap(u=>{let d=O(this.materializeOneWithInclude(u,e.include));return d?[d]:[]});if(e.sort&&e.sort.length>0){let u=(d,c)=>{for(let p of e.sort){let m=d[p.key],f=c[p.key];if(m<f)return p.direction==="asc"?-1:1;if(m>f)return p.direction==="asc"?1:-1}return 0};a.sort(u);}if(e.where||e.limit){let u=e.where?d=>R(d,e.where):()=>true;a=d(a,u,e.limit);}return !i&&this.collectionSubscriptions.has(n)&&(this.querySnapshots[n]=a),a}subscribe(e,t){var r;let i=T(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 s,a;(s=this.collectionSubscriptions.get(i))==null||s.callbacks.delete(t),((a=this.collectionSubscriptions.get(i))==null?void 0:a.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var l,u,d,c,p,m,f,g;let n=this.schema[e];if(this.logger.debug("Adding mutation",t),!n)throw new Error("Schema not found");if(t.op==="DELETE"){this.removeFromPool(e,t.resourceId);return}let r=(l=this.optimisticRawObjPool[e])==null?void 0:l[t.resourceId],s=false;if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((d=(u=this.optimisticMutationStack)==null?void 0:u[e])==null?void 0:d.filter(re=>re.id!==t.id))??[];let E=(c=t.meta)==null?void 0:c.originMutationId;if(this.logger.debug("Broadcast mutation received",{mutationId:t.id,resource:e,resourceId:t.resourceId,op:t.op,originMutationId:E??"(none)",customMutationIndexKeys:Object.keys(this.customMutationIndex),optimisticStackSize:((p=this.optimisticMutationStack[e])==null?void 0:p.length)??0}),E&&this.customMutationIndex[E]){let oe=this.customMutationIndex[E].filter(S=>S.resource===e),H=false;for(let S of oe){let I=(m=this.optimisticMutationStack[e])==null?void 0:m.find(V=>V.id===S.mutationId);if(I&&I.resourceId===t.resourceId&&I.op===t.op){this.logger.debug("Removing optimistic mutation (resourceId match)",{optimisticMutationId:S.mutationId,resourceId:t.resourceId}),this.undoMutation(e,S.mutationId),s=true,H=true;break}}if(!H)for(let S of oe){let I=(f=this.optimisticMutationStack[e])==null?void 0:f.find(V=>V.id===S.mutationId&&V.op===t.op);if(I){this.logger.debug("Removing optimistic mutation (resource+procedure fallback)",{optimisticMutationId:S.mutationId,optimisticResourceId:I.resourceId,broadcastResourceId:t.resourceId}),this.undoMutation(e,S.mutationId),s=true,H=true;break}}}this.rawObjPool[e]??={};let _={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=_;let D=_.value;delete D.id,this.kvStorage.set(e,t.resourceId,D);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack);let a=s?(g=this.optimisticRawObjPool[e])==null?void 0:g[t.resourceId]:r;this.updateRawObjPool(e,t.resourceId,t.payload,a);}undoMutation(e,t){var s,a;if(!this.optimisticMutationStack[e])return;let i=(s=this.optimisticMutationStack[e])==null?void 0:s.findIndex(l=>l.id===t);if(i===-1)return;let n=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",n);let r=(a=this.optimisticRawObjPool[e])==null?void 0:a[n.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,n.resourceId,Object.fromEntries(Object.entries(n.payload).map(([l])=>[l,{value:null,_meta:{}}])),r);}addCustomMutationMessage(e){this.customMutationStack.push(e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}registerCustomMutation(e,t){this.customMutationIndex[e]=t,this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex);}confirmCustomMutation(e){var i;let t=this.customMutationIndex[e];if(this.logger.debug("confirmCustomMutation called",{messageId:e,hasIndex:!!t,mutations:t??[]}),!!t){for(let{resource:n,mutationId:r}of t){let s=!!((i=this.optimisticMutationStack[n])!=null&&i.find(a=>a.id===r));this.logger.debug("confirmCustomMutation: undoing mutation",{resource:n,mutationId:r,stillInStack:s}),this.undoMutation(n,r);}delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(n=>n.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}}undoCustomMutation(e){var n;let t=this.customMutationIndex[e];if(!t)return [];let i=[];for(let{resource:r,mutationId:s}of t){let a=(n=this.optimisticMutationStack[r])==null?void 0:n.find(l=>l.id===s);this.undoMutation(r,s),a&&i.push({resource:r,mutationId:s,resourceId:a.resourceId});}return delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(r=>r.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack),i}getCustomMutationMutationIds(){let e=new Set;for(let t of Object.values(this.customMutationIndex))for(let{mutationId:i}of t)e.add(i);return e}loadConsolidatedState(e,t){t.forEach(i=>{var a;let n=(a=i.id)==null?void 0:a.value;if(!n)return;let{cleanedPayload:r,nestedMutations:s}=this.extractNestedRelations(e,i);s.forEach(l=>{this.addMutation(l.resource,l);}),this.addMutation(e,{id:n,type:"SYNC",resource:e,resourceId:n,op:"INSERT",payload:r});});}extractNestedRelations(e,t){let i=this.schema[e],n={...t},r=[];return i!=null&&i.relations?(Object.entries(t).forEach(([s,a])=>{var c;let l=i.relations[s];if(!l)return;let u=l.entity.name,d=a==null?void 0:a.value;if(l.type==="one"){if(d&&typeof d=="object"&&!Array.isArray(d)&&((c=d.id)!=null&&c.value)){let p=d.id.value,m={...d},{cleanedPayload:f,nestedMutations:g}=this.extractNestedRelations(u,m);r.push(...g),r.push({id:p,type:"SYNC",resource:u,resourceId:p,op:"INSERT",payload:f}),delete n[s];}}else l.type==="many"&&Array.isArray(d)&&(d.forEach(p=>{var m,f;if(p&&typeof p=="object"&&!Array.isArray(p)&&((f=(m=p.value)==null?void 0:m.id)!=null&&f.value)){let g=p.value.id.value,E={...p.value},{cleanedPayload:_,nestedMutations:D}=this.extractNestedRelations(u,E);r.push(...D),r.push({id:g,type:"SYNC",resource:u,resourceId:g,op:"INSERT",payload:_});}}),delete n[s]);}),{cleanedPayload:n,nestedMutations:r}):{cleanedPayload:n,nestedMutations:r}}removeFromPool(e,t){var i,n;this.schema[e]&&((i=this.rawObjPool[e])==null||delete i[t],(n=this.optimisticRawObjPool[e])==null||delete n[t],this.kvStorage.delete(e,t),this.optimisticObjGraph.removeNode(t),this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t));}updateRawObjPool(e,t,i,n){var a;if(!this.schema[e])return;let r=(a=this.rawObjPool[e])==null?void 0:a[t],s=(this.optimisticMutationStack[e]??[]).reduce((l,u)=>u.resourceId!==t?l:this.schema[e].mergeMutation("set",u.payload,l)[0],r);if(this.optimisticRawObjPool[e]??={},s?this.optimisticRawObjPool[e][t]={value:{...s.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!s)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(l=>l.type==="many"?[l.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let l=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([u,d])=>d.type==="one"?[[d.relationalColumn,u]]:[]));Object.entries(i).forEach(([u,d])=>{let c=this.schema[e].relations[l[u]];if(!l[u])return;let p=n==null?void 0:n.value[u],[,m]=c.mergeMutation("set",d,p);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let f=c.entity.name;this.optimisticObjGraph.createNode(m.value,f,Object.values(this.schema[f].relations).flatMap(g=>g.type==="many"?[g.entity.name]:[]));}p!=null&&p.value&&this.optimisticObjGraph.removeLink(t,c.entity.name),this.optimisticObjGraph.createLink(t,m.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var l;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let n=i.type,r=(l=this.optimisticRawObjPool[n])==null?void 0:l[e];if(!r)return;let[s,a]=Object.entries(t).reduce((u,[d,c])=>{let p=this.schema[n].relations[d];return p&&(p.type==="one"?u[0].push([d,p.entity.name,c??true]):p.type==="many"&&u[1].push([d,p.entity.name,c??true])),u},[[],[]]);return {value:{...r.value,...Object.fromEntries(s.map(([u,d,c])=>[u,this.materializeOneWithInclude(i.references.get(d),j(c)?c.include??{}:typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(a.map(([u,d,c])=>{let p=i.referencedBy.get(d),m=p instanceof Set;return [u,m?{value:Array.from(p.values()).map(f=>this.materializeOneWithInclude(f,j(c)?c.include??{}:typeof c=="object"&&c!==null?c:{}))}:this.materializeOneWithInclude(p,j(c)?c.include??{}:typeof c=="object"&&c!==null?c:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,n;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let r=T(t.query),s=this.querySnapshots[r],a=this.get(t.query,void 0,true);if(Ge(a,s))return;this.querySnapshots[r]=a,(n=this.onQuerySubscriptionTriggered)==null||n.call(this,t.query),t.callbacks.forEach(l=>{l(a);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([n,r])=>{var l;let s=(l=this.schema[t])==null?void 0:l.relations[n];if(!s)return;let a=s.entity.name;if(i.push(a),typeof r=="object"&&r!==null){let u=j(r)?r.include??{}:r;i.push(...this.flattenIncludes(u,a));}}),Array.from(new Set(i))}};var ve={pending:0,local:1,remote:2},z=class{constructor(e,t){this.client=e;this.query=t;}buildQueryRequest(){return this.query}then(e,t){return this.client.genericQuery(this.query.resource,this.query.procedure,this.query.input).then(e,t)}},se=class{url;ws;store;logger;optimisticMutations;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};_bootstrapStatus="pending";storageLoadedCount=0;expectedStorageLoads;constructor(e){var t,i,n,r;this.url=e.url,this.logger=de({level:e.logLevel??C.INFO}),this.optimisticMutations=e.optimisticMutations,this.expectedStorageLoads=e.storage===false?0:Object.keys(e.schema).length,this.store=new G(e.schema,e.storage,this.logger,()=>{this.replayCustomMutationStack();},(s,a)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:s,itemCount:a}),this.storageLoadedCount+=1,this.expectedStorageLoads>0&&this.storageLoadedCount>=this.expectedStorageLoads&&this.setBootstrapStatus("local");},s=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:s});}),this.ws=new N({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((n=e.connection)==null?void 0:n.reconnectTimeout)??5e3,reconnectLimit:(r=e.connection)==null?void 0:r.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",s=>{this.handleServerMessage(s.data);}),this.ws.addEventListener("connectionChange",s=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:s.open}),s.open&&(Array.from(this.remoteSubscriptions.values()).forEach(({query:a$1})=>{this.sendWsMessage({id:a(),type:"SUBSCRIBE",...a$1});}),this.replayCustomMutationStack());});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i,n,r;try{this.logger.debug("Message received from the server:",e);let s=fe.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",s),this.emitEvent({type:"MESSAGE_RECEIVED",message:s}),s.type==="SYNC"){let{resource:a,id:l,resourceId:u,op:d}=s;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:l,resource:a,resourceId:u,procedure:d??"UNKNOWN"});try{this.store.addMutation(a,s);}catch(c){this.logger.error("Error merging sync delta from the server:",c);}}else if(s.type==="REJECT"){if(this.replyHandlers[s.id]){clearTimeout(this.replyHandlers[s.id].timeoutHandle),this.emitUndoEvents(this.store.undoCustomMutation(s.id));let u=s.message??"Mutation rejected";(i=(t=this.replyHandlers[s.id]).reject)==null||i.call(t,new Error(u)),delete this.replyHandlers[s.id];}let a=((n=this.store.optimisticMutationStack[s.resource])==null?void 0:n.length)??0,l=(r=this.store.optimisticMutationStack[s.resource])==null?void 0:r.find(u=>u.id===s.id);this.store.undoMutation(s.resource,s.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:s.id,resource:s.resource}),l&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s.id,resource:s.resource,resourceId:l.resourceId,pendingMutations:a-1});}else if(s.type==="REPLY"){let{id:a,data:l}=s;if(this.replyHandlers[a]){clearTimeout(this.replyHandlers[a].timeoutHandle),this.replyHandlers[a].handler(l);return}let u=Te.parse(l);this.emitEvent({type:"DATA_LOAD_REPLY",resource:u.resource,itemCount:u.data.length}),this.store.loadConsolidatedState(u.resource,u.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:u.resource,itemCount:u.data.length}),this.setBootstrapStatus("remote");}}catch(s){this.logger.error("Error parsing message from the server:",s);}}load(e){let t=a(),i=T(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let n=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),n&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let r=this.remoteSubscriptions.get(i);r.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:a(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}genericMutate(e,t,i){var a$2,l;let n=(a$2=this.ws)==null?void 0:a$2.connected(),r=(l=this.optimisticMutations)==null?void 0:l.getHandler(e,t);if(!n&&!r)throw new Error("WebSocket not connected");let s={id:a(),type:"MUTATE",resource:e,procedure:t,payload:i,meta:{timestamp:new Date().toISOString()}};if(r)try{let{proxy:u,getOperations:d}=a$1(this.store,this.store.schema);r({input:i,storage:u});let c=d(),p=this.applyOptimisticOperations(c);this.store.registerCustomMutation(s.id,p),this.emitEvent({type:"MUTATION_SENT",mutationId:s.id,resource:e,resourceId:"",procedure:t,optimistic:!0});}catch(u){throw this.logger.error("Error executing optimistic handler:",u),this.emitUndoEvents(this.store.undoCustomMutation(s.id)),u}else this.emitEvent({type:"MUTATION_SENT",mutationId:s.id,resource:e,resourceId:"",procedure:t,optimistic:false});return n?(this.sendWsMessage(s),new Promise((u,d)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],this.emitUndoEvents(this.store.undoCustomMutation(s.id)),d(new Error("Reply timeout"));},5e3),handler:c=>{delete this.replyHandlers[s.id],this.store.confirmCustomMutation(s.id),u(c);},reject:d};})):(this.store.addCustomMutationMessage(s),Promise.resolve(void 0))}applyOptimisticOperations(e){var i;let t=[];try{for(let n of e){let r=a(),s=new Date().toISOString(),a$1={id:r,type:"SYNC",resource:n.resource,resourceId:n.id,op:n.type==="insert"?"INSERT":"UPDATE",payload:this.store.schema[n.resource].encodeMutation("set",n.data,s)},l=(((i=this.store.optimisticMutationStack[n.resource])==null?void 0:i.length)??0)+1;this.store.addMutation(n.resource,a$1,!0),t.push({resource:n.resource,mutationId:r}),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:r,resource:n.resource,resourceId:n.id,procedure:n.type==="insert"?"INSERT":"UPDATE",pendingMutations:l});}return t}catch(n){for(let{resource:r,mutationId:s}of t)this.store.undoMutation(r,s);throw n}}emitUndoEvents(e){var t;for(let{resource:i,mutationId:n,resourceId:r}of e){let s=((t=this.store.optimisticMutationStack[i])==null?void 0:t.length)??0;this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:n,resource:i,resourceId:r,pendingMutations:s});}}genericQuery(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let n={id:a(),type:"CUSTOM_QUERY",resource:e,procedure:t,input:i};return this.sendWsMessage(n),new Promise((r,s)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],s(new Error("Reply timeout"));},5e3),handler:a=>{delete this.replyHandlers[n.id],r(a);},reject:s};})}get bootstrapStatus(){return this._bootstrapStatus}setBootstrapStatus(e){ve[e]<=ve[this._bootstrapStatus]||(this._bootstrapStatus=e,this.emitEvent({type:"BOOTSTRAP_STATUS_CHANGE",bootstrapStatus:e}));}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}replayCustomMutationStack(){var e;if((e=this.ws)!=null&&e.connected())for(let t of this.store.customMutationStack)this.sendWsMessage(t),!this.replyHandlers[t.id]&&(this.replyHandlers[t.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[t.id],this.emitUndoEvents(this.store.undoCustomMutation(t.id));},5e3),handler:()=>{delete this.replyHandlers[t.id],this.store.confirmCustomMutation(t.id);}});}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},ei=o=>{let e=new se(o),t=(i,n)=>new Proxy(n,{get(r,s,a){if(s in r)return Reflect.get(r,s,a);if(typeof s=="string")return l=>new z(e,{resource:i,procedure:s,input:l})}});return {client:{ws:e.ws,get bootstrapStatus(){return e.bootstrapStatus},load:i=>e.load(i),addEventListener:i=>e.addEventListener(i)},store:{query:new Proxy({},{get(i,n){if(typeof n=="string")return Object.hasOwn(o.schema,n)?t(n,k._init(o.schema[n],e)):new Proxy({},{get(r,s){if(typeof s=="string")return a=>new z(e,{resource:n,procedure:s,input:a})}})},has(i,n){return typeof n=="string"}}),mutate:c(()=>{},{apply:(i,n,r)=>{if(n.length<2)return;if(n.length>2)throw new Error("Trying to access an invalid path");let[s,a]=n;return e.genericMutate(s,a,r[0])}})}}};export{ei as createClient,Ze as useClientState,Xe as useLiveQuery,et as useLoadData};
1
+ import {c,a,d,b}from'./chunk-YPTDCIAN.js';import {a as a$1}from'./chunk-RSSRYEM3.js';export{b as defineOptimisticMutations}from'./chunk-RSSRYEM3.js';import {useSyncExternalStore,useMemo,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z as z$1}from'zod';import {stringify}from'qs';import Ge from'fast-deep-equal';import {openDB}from'idb';var T=o=>xxHash32(JSON.stringify(o)).toString(32);var R=(o,e,t=false)=>Object.entries(e).every(([i,n])=>{if(i==="$and")return n.every(s=>R(o,s,t));if(i==="$or")return n.some(s=>R(o,s,t));let r=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let a=o[i];return a===void 0?false:t?!n.$in.includes(a):n.$in.includes(a)}if(n.$not!==void 0&&!t)return R(o,{[i]:n.$not},true);if(n.$gt!==void 0){let a=o[i];return typeof a!="number"?false:t?a<=n.$gt:a>n.$gt}if(n.$gte!==void 0){let a=o[i];return typeof a!="number"?false:t?a<n.$gte:a>=n.$gte}if(n.$lt!==void 0){let a=o[i];return typeof a!="number"?false:t?a>=n.$lt:a<n.$lt}if(n.$lte!==void 0){let a=o[i];return typeof a!="number"?false:t?a>n.$lte:a<=n.$lte}let s=o[i];return !s||typeof s!="object"&&!Array.isArray(s)?false:Array.isArray(s)?t?!s.some(a=>R(a,n,false)):s.some(a=>R(a,n,false)):R(s,n,t)}return t?o[i]!==r:o[i]===r}),j=o=>{if(typeof o!="object"||o===null)return false;let e=o;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},C={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},J=class{level;prefix;constructor(e={}){this.level=e.level??C.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=C.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=C.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=C.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=C.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=C.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},de=o=>new J(o);var Y=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=T(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let n={subscribe:r=>{let s=this.subscriptions.get(i);return s.callbacks.add(r),s.unsubscribe||(s.unsubscribe=()=>{},s.unsubscribe=e.subscribe(()=>{s.callbacks.forEach(a=>{a();});})),()=>{var a;(a=this.subscriptions.get(i))==null||a.callbacks.delete(r),setTimeout(()=>{var u;let l=this.subscriptions.get(i);l&&l.callbacks.size===0&&((u=l.unsubscribe)==null||u.call(l),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,n),this.subscriptions.get(i).subscribe}},Ce=new Y,Xe=o=>useSyncExternalStore(Ce.getOrStoreSubscription(o),o.get),Ze=o=>{let{subscribe:e,getSnapshot:t}=useMemo(()=>{let i={bootstrapStatus:o.bootstrapStatus,connected:o.ws.connected()},n=()=>{let r={bootstrapStatus:o.bootstrapStatus,connected:o.ws.connected()};(r.bootstrapStatus!==i.bootstrapStatus||r.connected!==i.connected)&&(i=r);};return {subscribe:r=>o.addEventListener(s=>{(s.type==="BOOTSTRAP_STATUS_CHANGE"||s.type==="CONNECTION_STATE_CHANGE")&&(n(),r());}),getSnapshot:()=>i}},[o]);return useSyncExternalStore(e,t,t)},et=(o,e)=>{useEffect(()=>{let t=o.load(e.buildQueryRequest());return ()=>{t();}},[e,o.load]);};var k=class o{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,i,n,r,s,a,l){this._collection=e,this._client=t,this._where=i??{},this._include=n??{},this._limit=r,this._single=s,this._sort=a,this._shouldAwait=l,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new o(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new o(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new o(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 o(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let i=[...this._sort??[],{key:e,direction:t}];return new o(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(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,i){return new o(e,t,void 0,void 0,void 0,void 0,void 0,i??false)}};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(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()});var X=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),xe=X.superRefine((o,e)=>{o.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Le=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),ye=z$1.object({timestamp:z$1.string().optional(),originMutationId:z$1.string().optional()}).optional(),he=Le.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:ye}),Z=z$1.object({id:z$1.string().optional(),type:z$1.literal("SYNC"),resource:z$1.string(),resourceId:z$1.string(),op:z$1.enum(["INSERT","UPDATE","DELETE"]),payload:xe,meta:ye}),ee=(o,e)=>{o.op==="DELETE"&&Object.keys(o.payload).length>0&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"DELETE delta payload must be empty"});};Z.superRefine(ee);var me=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var x=z$1.string(),te=me,Ee=z$1.object({id:x,type:z$1.literal("SUBSCRIBE")}).and(te),Ie=z$1.object({id:x,type:z$1.literal("UNSUBSCRIBE")}).and(te),we=z$1.object({id:x,type:z$1.literal("QUERY")}).and(te),Ae=z$1.object({id:x,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),Oe=he.extend({id:x}),je=Oe;z$1.union([Ee,we,Ae,je,Ie]);var _e=z$1.object({id:x,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),De=z$1.object({id:x,type:z$1.literal("REPLY"),data:z$1.any()}),Ve=Z.extend({id:x}).superRefine(ee),fe=z$1.union([_e,De,Ve]),Te=z$1.object({resource:z$1.string(),data:z$1.array(X)});var N=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(n=>{n(t);});}};var ie=o=>typeof o=="object"&&o!==null&&"value"in o&&!Array.isArray(o),O=o=>o?Array.isArray(o.value)?o.value.map(t=>ie(t)?O(t):t):typeof o.value!="object"||o.value===null||o.value instanceof Date?o.value:Object.fromEntries(Object.entries(o.value).map(([t,i])=>Array.isArray(i)?[t,i.map(n=>ie(n)?O(n):n)]:ie(i)?[t,O(i)]:[t,i])):void 0;var B=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 n={id:e,type:t,referencedBy:new Map(i.map(r=>[r,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,n),n}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),n=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!n)throw new Error(`Target node with id ${t} does not exist`);i.references.set(n.type,t);let r=n.referencedBy.get(i.type);r&&r instanceof Set?r.add(e):n.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let n=i.references.get(t);if(!n)return;i.references.delete(t);let r=this.nodes.get(n);if(!r)return;let s=r.referencedBy.get(i.type);s&&(s instanceof Set?s.delete(e):r.referencedBy.delete(i.type),this.notifySubscribers(n)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,n])=>{(n instanceof Set?Array.from(n.values()):[n]).forEach(s=>{let a=this.nodes.get(s);!a||!a.references.get(i)||(a.references.delete(i),this.notifySubscribers(s));});}),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 n;try{i(e);}catch(r){(n=this.logger)==null||n.error(`Error in node subscription for node ${e}:`,r);}});}getAllNodes(){return Array.from(this.nodes.values())}};var ne="__meta",W="databases",$=class{db;async init(e,t){var u,d;if(typeof window>"u")return;let n=((u=(await window.indexedDB.databases()).find(c=>c.name===t))==null?void 0:u.version)??1,r=await T(e),s=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,p])=>[c,await T(p)]))),a=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(W)||c.createObjectStore(W);}}),l=(d=await this.getAll(a,W))==null?void 0:d[t];(l==null?void 0:l.schemaHash)!==r&&n++,this.db=await openDB(t,n,{async upgrade(c){[...Object.keys(e),ne].forEach(p=>{(l==null?void 0:l.objectHashes[p])!==s[p]&&c.objectStoreNames.contains(p)&&c.deleteObjectStore(p),c.objectStoreNames.contains(p)||c.createObjectStore(p);}),await a.put(W,{schemaHash:r,objectHashes:s},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var n;return (n=this.db)==null?void 0:n.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(ne,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(ne,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,n]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((r,s)=>[n[s],r]))}};var G=class{constructor(e,t,i,n,r,s){this.schema=e;this.logger=i,this.optimisticObjGraph=new B(i),this.kvStorage=new $,this.onQuerySubscriptionTriggered=s,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{Promise.all([this.kvStorage.getMeta("mutationStack"),this.kvStorage.getMeta("customMutationStack"),this.kvStorage.getMeta("customMutationIndex")]).then(([a,l,u])=>{a&&Object.keys(a).length>0&&(this.optimisticMutationStack=a),l&&l.length>0&&(this.customMutationStack=l),u&&Object.keys(u).length>0&&(this.customMutationIndex=u),n==null||n(this.optimisticMutationStack,this.customMutationStack,this.customMutationIndex);}).then(()=>{Object.entries(this.schema).forEach(([a])=>{this.kvStorage.get(a).then(l=>{if(!l||Object.keys(l).length===0){r==null||r(a,0);return}let u=Object.entries(l).map(([d,c])=>({...c,id:{value:d}}));r==null||r(a,u.length),this.loadConsolidatedState(a,u);});});}).catch(a=>{i.debug("Storage initialization failed (may not be available in this environment):",a);});});}rawObjPool={};optimisticMutationStack={};customMutationStack=[];optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;customMutationIndex={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e,t,i=false){var l;let n=t??T(e);if(this.querySnapshots[n]&&!i){let u=this.querySnapshots[n];if(u)return u}let r,s=(l=e.where)==null?void 0:l.id;s===void 0?r=Object.keys(this.optimisticRawObjPool[e.resource]??{}):typeof s=="string"?r=[s]:typeof s=="object"&&s!==null?"$in"in s&&Array.isArray(s.$in)?r=s.$in:"$eq"in s&&typeof s.$eq=="string"?r=[s.$eq]:r=Object.keys(this.optimisticRawObjPool[e.resource]??{}):r=Object.keys(this.optimisticRawObjPool[e.resource]??{});let a=r.flatMap(u=>{let d=O(this.materializeOneWithInclude(u,e.include));return d?[d]:[]});if(e.sort&&e.sort.length>0){let u=(d,c)=>{for(let p of e.sort){let m=d[p.key],f=c[p.key];if(m<f)return p.direction==="asc"?-1:1;if(m>f)return p.direction==="asc"?1:-1}return 0};a.sort(u);}if(e.where||e.limit){let u=e.where?d=>R(d,e.where):()=>true;a=d(a,u,e.limit);}return !i&&this.collectionSubscriptions.has(n)&&(this.querySnapshots[n]=a),a}subscribe(e,t){var r;let i=T(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 s,a;(s=this.collectionSubscriptions.get(i))==null||s.callbacks.delete(t),((a=this.collectionSubscriptions.get(i))==null?void 0:a.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var l,u,d,c,p,m,f,g;let n=this.schema[e];if(this.logger.debug("Adding mutation",t),!n)throw new Error("Schema not found");if(t.op==="DELETE"){this.removeFromPool(e,t.resourceId);return}let r=(l=this.optimisticRawObjPool[e])==null?void 0:l[t.resourceId],s=false;if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((d=(u=this.optimisticMutationStack)==null?void 0:u[e])==null?void 0:d.filter(re=>re.id!==t.id))??[];let E=(c=t.meta)==null?void 0:c.originMutationId;if(this.logger.debug("Broadcast mutation received",{mutationId:t.id,resource:e,resourceId:t.resourceId,op:t.op,originMutationId:E??"(none)",customMutationIndexKeys:Object.keys(this.customMutationIndex),optimisticStackSize:((p=this.optimisticMutationStack[e])==null?void 0:p.length)??0}),E&&this.customMutationIndex[E]){let oe=this.customMutationIndex[E].filter(S=>S.resource===e),H=false;for(let S of oe){let I=(m=this.optimisticMutationStack[e])==null?void 0:m.find(V=>V.id===S.mutationId);if(I&&I.resourceId===t.resourceId&&I.op===t.op){this.logger.debug("Removing optimistic mutation (resourceId match)",{optimisticMutationId:S.mutationId,resourceId:t.resourceId}),this.undoMutation(e,S.mutationId),s=true,H=true;break}}if(!H)for(let S of oe){let I=(f=this.optimisticMutationStack[e])==null?void 0:f.find(V=>V.id===S.mutationId&&V.op===t.op);if(I){this.logger.debug("Removing optimistic mutation (resource+procedure fallback)",{optimisticMutationId:S.mutationId,optimisticResourceId:I.resourceId,broadcastResourceId:t.resourceId}),this.undoMutation(e,S.mutationId),s=true,H=true;break}}}this.rawObjPool[e]??={};let _={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=_;let D=_.value;delete D.id,this.kvStorage.set(e,t.resourceId,D);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack);let a=s?(g=this.optimisticRawObjPool[e])==null?void 0:g[t.resourceId]:r;this.updateRawObjPool(e,t.resourceId,t.payload,a);}undoMutation(e,t){var s,a;if(!this.optimisticMutationStack[e])return;let i=(s=this.optimisticMutationStack[e])==null?void 0:s.findIndex(l=>l.id===t);if(i===-1)return;let n=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",n);let r=(a=this.optimisticRawObjPool[e])==null?void 0:a[n.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,n.resourceId,Object.fromEntries(Object.entries(n.payload).map(([l])=>[l,{value:null,_meta:{}}])),r);}addCustomMutationMessage(e){this.customMutationStack.push(e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}registerCustomMutation(e,t){this.customMutationIndex[e]=t,this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex);}confirmCustomMutation(e){var i;let t=this.customMutationIndex[e];if(this.logger.debug("confirmCustomMutation called",{messageId:e,hasIndex:!!t,mutations:t??[]}),!!t){for(let{resource:n,mutationId:r}of t){let s=!!((i=this.optimisticMutationStack[n])!=null&&i.find(a=>a.id===r));this.logger.debug("confirmCustomMutation: undoing mutation",{resource:n,mutationId:r,stillInStack:s}),this.undoMutation(n,r);}delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(n=>n.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}}undoCustomMutation(e){var n;let t=this.customMutationIndex[e];if(!t)return [];let i=[];for(let{resource:r,mutationId:s}of t){let a=(n=this.optimisticMutationStack[r])==null?void 0:n.find(l=>l.id===s);this.undoMutation(r,s),a&&i.push({resource:r,mutationId:s,resourceId:a.resourceId});}return delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(r=>r.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack),i}getCustomMutationMutationIds(){let e=new Set;for(let t of Object.values(this.customMutationIndex))for(let{mutationId:i}of t)e.add(i);return e}loadConsolidatedState(e,t){t.forEach(i=>{var a;let n=(a=i.id)==null?void 0:a.value;if(!n)return;let{cleanedPayload:r,nestedMutations:s}=this.extractNestedRelations(e,i);s.forEach(l=>{this.addMutation(l.resource,l);}),this.addMutation(e,{id:n,type:"SYNC",resource:e,resourceId:n,op:"INSERT",payload:r});});}extractNestedRelations(e,t){let i=this.schema[e],n={...t},r=[];return i!=null&&i.relations?(Object.entries(t).forEach(([s,a])=>{var c;let l=i.relations[s];if(!l)return;let u=l.entity.name,d=a==null?void 0:a.value;if(l.type==="one"){if(d&&typeof d=="object"&&!Array.isArray(d)&&((c=d.id)!=null&&c.value)){let p=d.id.value,m={...d},{cleanedPayload:f,nestedMutations:g}=this.extractNestedRelations(u,m);r.push(...g),r.push({id:p,type:"SYNC",resource:u,resourceId:p,op:"INSERT",payload:f}),delete n[s];}}else l.type==="many"&&Array.isArray(d)&&(d.forEach(p=>{var m,f;if(p&&typeof p=="object"&&!Array.isArray(p)&&((f=(m=p.value)==null?void 0:m.id)!=null&&f.value)){let g=p.value.id.value,E={...p.value},{cleanedPayload:_,nestedMutations:D}=this.extractNestedRelations(u,E);r.push(...D),r.push({id:g,type:"SYNC",resource:u,resourceId:g,op:"INSERT",payload:_});}}),delete n[s]);}),{cleanedPayload:n,nestedMutations:r}):{cleanedPayload:n,nestedMutations:r}}removeFromPool(e,t){var i,n;this.schema[e]&&((i=this.rawObjPool[e])==null||delete i[t],(n=this.optimisticRawObjPool[e])==null||delete n[t],this.kvStorage.delete(e,t),this.optimisticObjGraph.removeNode(t),this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t));}updateRawObjPool(e,t,i,n){var a;if(!this.schema[e])return;let r=(a=this.rawObjPool[e])==null?void 0:a[t],s=(this.optimisticMutationStack[e]??[]).reduce((l,u)=>u.resourceId!==t?l:this.schema[e].mergeMutation("set",u.payload,l)[0],r);if(this.optimisticRawObjPool[e]??={},s?this.optimisticRawObjPool[e][t]={value:{...s.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!s)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(l=>l.type==="many"?[l.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let l=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([u,d])=>d.type==="one"?[[d.relationalColumn,u]]:[]));Object.entries(i).forEach(([u,d])=>{let c=this.schema[e].relations[l[u]];if(!l[u])return;let p=n==null?void 0:n.value[u],[,m]=c.mergeMutation("set",d,p);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let f=c.entity.name;this.optimisticObjGraph.createNode(m.value,f,Object.values(this.schema[f].relations).flatMap(g=>g.type==="many"?[g.entity.name]:[]));}p!=null&&p.value&&this.optimisticObjGraph.removeLink(t,c.entity.name),this.optimisticObjGraph.createLink(t,m.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var l;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let n=i.type,r=(l=this.optimisticRawObjPool[n])==null?void 0:l[e];if(!r)return;let[s,a]=Object.entries(t).reduce((u,[d,c])=>{let p=this.schema[n].relations[d];return p&&(p.type==="one"?u[0].push([d,p.entity.name,c??true]):p.type==="many"&&u[1].push([d,p.entity.name,c??true])),u},[[],[]]);return {value:{...r.value,...Object.fromEntries(s.map(([u,d,c])=>[u,this.materializeOneWithInclude(i.references.get(d),j(c)?c.include??{}:typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(a.map(([u,d,c])=>{let p=i.referencedBy.get(d),m=p instanceof Set;return [u,m?{value:Array.from(p.values()).map(f=>this.materializeOneWithInclude(f,j(c)?c.include??{}:typeof c=="object"&&c!==null?c:{}))}:this.materializeOneWithInclude(p,j(c)?c.include??{}:typeof c=="object"&&c!==null?c:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,n;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let r=T(t.query),s=this.querySnapshots[r],a=this.get(t.query,void 0,true);if(Ge(a,s))return;this.querySnapshots[r]=a,(n=this.onQuerySubscriptionTriggered)==null||n.call(this,t.query),t.callbacks.forEach(l=>{l(a);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([n,r])=>{var l;let s=(l=this.schema[t])==null?void 0:l.relations[n];if(!s)return;let a=s.entity.name;if(i.push(a),typeof r=="object"&&r!==null){let u=j(r)?r.include??{}:r;i.push(...this.flattenIncludes(u,a));}}),Array.from(new Set(i))}};var ve={pending:0,local:1,remote:2},z=class{constructor(e,t){this.client=e;this.query=t;}buildQueryRequest(){return this.query}then(e,t){return this.client.genericQuery(this.query.resource,this.query.procedure,this.query.input).then(e,t)}},se=class{url;ws;store;logger;optimisticMutations;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};_bootstrapStatus="pending";storageLoadedCount=0;expectedStorageLoads;constructor(e){var t,i,n,r;this.url=e.url,this.logger=de({level:e.logLevel??C.INFO}),this.optimisticMutations=e.optimisticMutations,this.expectedStorageLoads=e.storage===false?0:Object.keys(e.schema).length,this.store=new G(e.schema,e.storage,this.logger,()=>{this.replayCustomMutationStack();},(s,a)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:s,itemCount:a}),this.storageLoadedCount+=1,this.expectedStorageLoads>0&&this.storageLoadedCount>=this.expectedStorageLoads&&this.setBootstrapStatus("local");},s=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:s});}),this.ws=new N({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((n=e.connection)==null?void 0:n.reconnectTimeout)??5e3,reconnectLimit:(r=e.connection)==null?void 0:r.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",s=>{this.handleServerMessage(s.data);}),this.ws.addEventListener("connectionChange",s=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:s.open}),s.open&&(Array.from(this.remoteSubscriptions.values()).forEach(({query:a$1})=>{this.sendWsMessage({id:a(),type:"SUBSCRIBE",...a$1});}),this.replayCustomMutationStack());});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i,n,r;try{this.logger.debug("Message received from the server:",e);let s=fe.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",s),this.emitEvent({type:"MESSAGE_RECEIVED",message:s}),s.type==="SYNC"){let{resource:a,id:l,resourceId:u,op:d}=s;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:l,resource:a,resourceId:u,procedure:d??"UNKNOWN"});try{this.store.addMutation(a,s);}catch(c){this.logger.error("Error merging sync delta from the server:",c);}}else if(s.type==="REJECT"){if(this.replyHandlers[s.id]){clearTimeout(this.replyHandlers[s.id].timeoutHandle),this.emitUndoEvents(this.store.undoCustomMutation(s.id));let u=s.message??"Mutation rejected";(i=(t=this.replyHandlers[s.id]).reject)==null||i.call(t,new Error(u)),delete this.replyHandlers[s.id];}let a=((n=this.store.optimisticMutationStack[s.resource])==null?void 0:n.length)??0,l=(r=this.store.optimisticMutationStack[s.resource])==null?void 0:r.find(u=>u.id===s.id);this.store.undoMutation(s.resource,s.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:s.id,resource:s.resource}),l&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s.id,resource:s.resource,resourceId:l.resourceId,pendingMutations:a-1});}else if(s.type==="REPLY"){let{id:a,data:l}=s;if(this.replyHandlers[a]){clearTimeout(this.replyHandlers[a].timeoutHandle),this.replyHandlers[a].handler(l);return}let u=Te.parse(l);this.emitEvent({type:"DATA_LOAD_REPLY",resource:u.resource,itemCount:u.data.length}),this.store.loadConsolidatedState(u.resource,u.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:u.resource,itemCount:u.data.length}),this.setBootstrapStatus("remote");}}catch(s){this.logger.error("Error parsing message from the server:",s);}}load(e){let t=a(),i=T(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let n=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),n&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let r=this.remoteSubscriptions.get(i);r.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:a(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}genericMutate(e,t,i){var a$2,l;let n=(a$2=this.ws)==null?void 0:a$2.connected(),r=(l=this.optimisticMutations)==null?void 0:l.getHandler(e,t);if(!n&&!r)throw new Error("WebSocket not connected");let s={id:a(),type:"MUTATE",resource:e,procedure:t,payload:i,meta:{timestamp:new Date().toISOString()}};if(r)try{let{proxy:u,getOperations:d}=a$1(this.store,this.store.schema);r({input:i,storage:u});let c=d(),p=this.applyOptimisticOperations(c);this.store.registerCustomMutation(s.id,p),this.emitEvent({type:"MUTATION_SENT",mutationId:s.id,resource:e,resourceId:"",procedure:t,optimistic:!0});}catch(u){throw this.logger.error("Error executing optimistic handler:",u),this.emitUndoEvents(this.store.undoCustomMutation(s.id)),u}else this.emitEvent({type:"MUTATION_SENT",mutationId:s.id,resource:e,resourceId:"",procedure:t,optimistic:false});return n?(this.sendWsMessage(s),new Promise((u,d)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],this.emitUndoEvents(this.store.undoCustomMutation(s.id)),d(new Error("Reply timeout"));},5e3),handler:c=>{delete this.replyHandlers[s.id],this.store.confirmCustomMutation(s.id),u(c);},reject:d};})):(this.store.addCustomMutationMessage(s),Promise.resolve(void 0))}applyOptimisticOperations(e){var i;let t=[];try{for(let n of e){let r=a(),s=new Date().toISOString(),a$1={id:r,type:"SYNC",resource:n.resource,resourceId:n.id,op:n.type==="insert"?"INSERT":"UPDATE",payload:this.store.schema[n.resource].encodeMutation("set",n.data,s)},l=(((i=this.store.optimisticMutationStack[n.resource])==null?void 0:i.length)??0)+1;this.store.addMutation(n.resource,a$1,!0),t.push({resource:n.resource,mutationId:r}),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:r,resource:n.resource,resourceId:n.id,procedure:n.type==="insert"?"INSERT":"UPDATE",pendingMutations:l});}return t}catch(n){for(let{resource:r,mutationId:s}of t)this.store.undoMutation(r,s);throw n}}emitUndoEvents(e){var t;for(let{resource:i,mutationId:n,resourceId:r}of e){let s=((t=this.store.optimisticMutationStack[i])==null?void 0:t.length)??0;this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:n,resource:i,resourceId:r,pendingMutations:s});}}genericQuery(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let n={id:a(),type:"CUSTOM_QUERY",resource:e,procedure:t,input:i};return this.sendWsMessage(n),new Promise((r,s)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],s(new Error("Reply timeout"));},5e3),handler:a=>{delete this.replyHandlers[n.id],r(a);},reject:s};})}get bootstrapStatus(){return this._bootstrapStatus}setBootstrapStatus(e){ve[e]<=ve[this._bootstrapStatus]||(this._bootstrapStatus=e,this.emitEvent({type:"BOOTSTRAP_STATUS_CHANGE",bootstrapStatus:e}));}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}replayCustomMutationStack(){var e;if((e=this.ws)!=null&&e.connected())for(let t of this.store.customMutationStack)this.sendWsMessage(t),!this.replyHandlers[t.id]&&(this.replyHandlers[t.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[t.id],this.emitUndoEvents(this.store.undoCustomMutation(t.id));},5e3),handler:()=>{delete this.replyHandlers[t.id],this.store.confirmCustomMutation(t.id);}});}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},ei=o=>{let e=new se(o),t=(i,n)=>new Proxy(n,{get(r,s,a){if(s in r)return Reflect.get(r,s,a);if(typeof s=="string")return l=>new z(e,{resource:i,procedure:s,input:l})}});return {client:{ws:e.ws,get bootstrapStatus(){return e.bootstrapStatus},load:i=>e.load(i),addEventListener:i=>e.addEventListener(i)},store:{query:new Proxy({},{get(i,n){if(typeof n=="string")return Object.hasOwn(o.schema,n)?t(n,k._init(o.schema[n],e)):new Proxy({},{get(r,s){if(typeof s=="string")return a=>new z(e,{resource:n,procedure:s,input:a})}})},has(i,n){return typeof n=="string"}}),mutate:c(()=>{},{apply:(i,n,r)=>{if(n.length<2)return;if(n.length>2)throw new Error("Trying to access an invalid path");let[s,a]=n;return e.genericMutate(s,a,r[0])}})}}};export{ei as createClient,Ze as useClientState,Xe as useLiveQuery,et as useLoadData};
@@ -1,4 +1,4 @@
1
- import { C as ClientOptions, a as ClientRouterConstraint, b as Client } from './index-DjBla1td.js';
1
+ import { C as ClientOptions, a as ClientRouterConstraint, b as Client } from './index-DOU7wys1.js';
2
2
  import '@standard-schema/spec';
3
3
  import 'zod';
4
4
 
@@ -502,7 +502,26 @@ type CustomQueryRequest = z.infer<typeof customQuerySchema>;
502
502
  /** biome-ignore-all lint/complexity/noBannedTypes: <explanation> */
503
503
 
504
504
  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>>[];
505
+ /**
506
+ * Type-only brand recording a {@link QueryBuilder}'s inferable parameters.
507
+ *
508
+ * `CustomQueryResult` (client entry point) has to recognise a query-builder
509
+ * value returned from a route handler whose type flows through the *server*
510
+ * entry point. The two entry points are emitted as separate `.d.ts` graphs, so
511
+ * each gets its own `declare class QueryBuilder`; because the class has
512
+ * `private` members, TypeScript compares those declarations *nominally* and any
513
+ * `extends QueryBuilder<...>` check across the boundary fails. Narrowing on this
514
+ * structural brand instead makes the check independent of class identity — and
515
+ * therefore also of duplicate installed package versions.
516
+ */
517
+ interface QueryBuilderBrand<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection>, TSingle extends boolean> {
518
+ collection: TCollection;
519
+ include: TInclude;
520
+ single: TSingle;
521
+ }
505
522
  declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection> = {}, TSingle extends boolean = false, TShouldAwait extends boolean = false> {
523
+ /** Never assigned at runtime; exists only to carry {@link QueryBuilderBrand}. */
524
+ readonly __queryBuilderBrand: QueryBuilderBrand<TCollection, TInclude, TSingle>;
506
525
  private _collection;
507
526
  private _client;
508
527
  private _where;
@@ -559,7 +578,25 @@ type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
559
578
  type CustomQueryLoadable<TOutput> = PromiseLike<TOutput> & {
560
579
  buildQueryRequest: () => CustomQueryRequest;
561
580
  };
562
- type CustomQueryResult<TOutput, TShouldAwait extends boolean = false> = UnwrapPromise<TOutput> extends QueryBuilder<infer TCollection, infer TInclude, infer TSingle, any> ? TShouldAwait extends true ? TSingle extends true ? Promise<Simplify<InferLiveObject<TCollection, TInclude>> | undefined> : Promise<Simplify<InferLiveObject<TCollection, TInclude>>[]> : TSingle extends true ? CustomQueryLoadable<Simplify<InferLiveObject<TCollection, TInclude>> | undefined> : CustomQueryLoadable<Simplify<InferLiveObject<TCollection, TInclude>>[]> : Promisify<UnwrapPromise<TOutput>>;
581
+ /**
582
+ * Narrow a custom-query handler return type to its loadable client shape.
583
+ *
584
+ * The match keys off {@link QueryBuilderBrand} — a structural, type-only brand —
585
+ * rather than `extends QueryBuilder<...>`. `QueryBuilder` carries `private`
586
+ * members, so its class identity is nominal and the server- and client-bundle
587
+ * `.d.ts` graphs emit two incompatible declarations; a class-based check fails
588
+ * for published consumers who import the router from `@live-state/sync/server`
589
+ * and the client from `@live-state/sync/client`. The brand is compared by shape,
590
+ * so it survives that split (and duplicate installed versions).
591
+ */
592
+ type CustomQueryResult<TOutput, TShouldAwait extends boolean = false> = UnwrapPromise<TOutput> extends {
593
+ readonly __queryBuilderBrand: {
594
+ collection: infer TCollection extends LiveObjectAny;
595
+ include: infer TInclude;
596
+ single: infer TSingle;
597
+ };
598
+ } ? // `TInclude` is inferred unconstrained; intersecting with its declared
599
+ TInclude & IncludeClause<TCollection> extends infer TInc extends IncludeClause<TCollection> ? TShouldAwait extends true ? TSingle extends true ? Promise<Simplify<InferLiveObject<TCollection, TInc>> | undefined> : Promise<Simplify<InferLiveObject<TCollection, TInc>>[]> : TSingle extends true ? CustomQueryLoadable<Simplify<InferLiveObject<TCollection, TInc>> | undefined> : CustomQueryLoadable<Simplify<InferLiveObject<TCollection, TInc>>[]> : never : Promisify<UnwrapPromise<TOutput>>;
563
600
  type CustomQueryFunction<TInput, TOutput, TShouldAwait extends boolean = false> = [TInput] extends [never] | [undefined] ? () => CustomQueryResult<TOutput, TShouldAwait> : (input: TInput) => CustomQueryResult<TOutput, TShouldAwait>;
564
601
  /**
565
602
  * Simplified, client-safe view of a route. Routes are now procedure-only
@@ -1,3 +1,3 @@
1
- export { e as OptimisticHandlerContext, h as OptimisticInsertOperation, j as OptimisticMutationHandler, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, i as OptimisticUpdateOperation, k as createOptimisticStorageProxy, d as defineOptimisticMutations } from './index-DjBla1td.js';
1
+ export { e as OptimisticHandlerContext, h as OptimisticInsertOperation, j as OptimisticMutationHandler, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, i as OptimisticUpdateOperation, k as createOptimisticStorageProxy, d as defineOptimisticMutations } from './index-DOU7wys1.js';
2
2
  import '@standard-schema/spec';
3
3
  import 'zod';
package/dist/server.cjs CHANGED
@@ -1,12 +1,12 @@
1
- 'use strict';var jsXxhash=require('js-xxhash'),le=require('crypto'),Zt=require('qs'),zod=require('zod'),kysely=require('kysely'),mysql=require('kysely/helpers/mysql'),postgres=require('kysely/helpers/postgres'),sqlite=require('kysely/helpers/sqlite');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var le__default=/*#__PURE__*/_interopDefault(le);var Zt__default=/*#__PURE__*/_interopDefault(Zt);var ut=Object.create;var _e=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var mt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ht=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yt(e))!ft.call(i,r)&&r!==t&&_e(i,r,{get:()=>e[r],enumerable:!(n=dt(e,r))||n.enumerable});return i};var Qe=(i,e,t)=>(t=i!=null?ut(pt(i)):{},ht(_e(t,"default",{value:i,enumerable:true}),i));var we=mt(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.parse=Wt;pe.serialize=Ut;var _t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Qt=/^[\u0021-\u003A\u003C-\u007E]*$/,$t=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,qt=/^[\u0020-\u003A\u003D-\u007E]*$/,Kt=Object.prototype.toString,Bt=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Wt(i,e){let t=new Bt,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Ht,o=0;do{let c=i.indexOf("=",o);if(c===-1)break;let s=i.indexOf(";",o),a=s===-1?n:s;if(c>a){o=i.lastIndexOf(";",c-1)+1;continue}let l=Ue(i,o,c),u=He(i,c,l),d=i.slice(l,u);if(t[d]===void 0){let p=Ue(i,c+1,a),y=He(i,a,p),f=r(i.slice(p,y));t[d]=f;}o=a+1;}while(o<n);return t}function Ue(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function He(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Ut(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!_t.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Qt.test(r))throw new TypeError(`argument val is invalid: ${e}`);let o=i+"="+r;if(!t)return o;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);o+="; Max-Age="+t.maxAge;}if(t.domain){if(!$t.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);o+="; Domain="+t.domain;}if(t.path){if(!qt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);o+="; Path="+t.path;}if(t.expires){if(!zt(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);o+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(o+="; HttpOnly"),t.secure&&(o+="; Secure"),t.partitioned&&(o+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":o+="; Priority=Low";break;case "medium":o+="; Priority=Medium";break;case "high":o+="; 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":o+="; SameSite=Strict";break;case "lax":o+="; SameSite=Lax";break;case "none":o+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return o}function Ht(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function zt(i){return Kt.call(i)==="[object Date]"}});var ge=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),S=i=>i?Array.isArray(i.value)?i.value.map(t=>ge(t)?S(t):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=>ge(r)?S(r):r)]:ge(n)?[t,S(n)]:[t,n])):void 0;var U=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),Re=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let o=c=>{c.$and?c.$and.forEach(o):c.$or?c.$or.forEach(o):Object.entries(c).forEach(([s,a])=>{var l;if((l=r.relations)!=null&&l[s]&&(n[s]=true,typeof a=="object"&&a!==null&&!Array.isArray(a))){let u=Re(a,r.relations[s].entity.name,t);Object.keys(u).length>0&&(n[s]={include:u});}});};return o(i),n},V=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(c=>V(i,c,t));if(n==="$or")return r.some(c=>V(i,c,t));let o=(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 s=i[n];return s===void 0?false:t?!r.$in.includes(s):r.$in.includes(s)}if(r.$not!==void 0&&!t)return V(i,{[n]:r.$not},true);if(r.$gt!==void 0){let s=i[n];return typeof s!="number"?false:t?s<=r.$gt:s>r.$gt}if(r.$gte!==void 0){let s=i[n];return typeof s!="number"?false:t?s<r.$gte:s>=r.$gte}if(r.$lt!==void 0){let s=i[n];return typeof s!="number"?false:t?s>=r.$lt:s<r.$lt}if(r.$lte!==void 0){let s=i[n];return typeof s!="number"?false:t?s>r.$lte:s<=r.$lte}let c=i[n];return !c||typeof c!="object"&&!Array.isArray(c)?false:Array.isArray(c)?t?!c.some(s=>V(s,r,false)):c.some(s=>V(s,r,false)):V(c,r,t)}return t?i[n]!==o:i[n]===o}),H=i=>{if(typeof i!="object"||i===null)return false;let e=i;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},D={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},xe=class{level;prefix;constructor(e={}){this.level=e.level??D.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=D.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=D.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=D.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=D.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=D.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},$e=i=>new xe(i);var Ke="0123456789ABCDEFGHJKMNPQRSTVWXYZ",J=32;var Mt=16,Be=10,qe=0xffffffffffff;var $;(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";})($||($={}));var q=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function At(i){let e=Math.floor(i()*J);return e===J&&(e=J-1),Ke.charAt(e)}function Ot(i){var n;let e=jt(),t=e&&(e.crypto||e.msCrypto)||(typeof le__default.default<"u"?le__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=le__default.default)!=null&&n.randomBytes)return ()=>le__default.default.randomBytes(1).readUInt8()/255;throw new q($.PRNGDetectFailure,"Failed to find a reliable PRNG")}function jt(){return Nt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Et(i,e){let t="";for(;i>0;i--)t=At(e)+t;return t}function Pt(i,e=Be){if(isNaN(i))throw new q($.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>qe)throw new q($.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${qe}: ${i}`);if(i<0)throw new q($.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new q($.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%J,n=Ke.charAt(t)+n,i=(i-t)/J;return n}function Nt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function We(i,e){let t=Ot(),n=Date.now();return Pt(n,Be)+Et(Mt,t)}var de=()=>We().toLowerCase(),ue=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ue(n)}return ue(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ue(r)}throw n}}}),K=i=>i instanceof Promise?i:ue(i);function Se(i){return U({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}function Vt(i,e){let t=i==null,n=e==null;if(t&&n)return 0;if(t)return -1;if(n)return 1;if(typeof i=="number"&&typeof e=="number")return i-e;if(typeof i=="boolean"&&typeof e=="boolean")return Number(i)-Number(e);let r=String(i),o=String(e);return r<o?-1:r>o?1:0}var G=class{limit;directions;entries=[];index=new Map;constructor(e){if(!Number.isInteger(e.limit)||e.limit<0)throw new Error("WindowIndex limit must be a non-negative integer");this.limit=e.limit,this.directions=(e.orderBy??[]).map(t=>t.direction);}get size(){return this.entries.length}get isFull(){return this.entries.length>=this.limit}compare(e,t){for(let n=0;n<this.directions.length;n++){let r=Vt(e.sortKey[n],t.sortKey[n]);if(r!==0)return this.directions[n]==="desc"?-r:r}return e.id<t.id?-1:e.id>t.id?1:0}lowerBound(e){let t=0,n=this.entries.length;for(;t<n;){let r=t+n>>>1;this.compare(this.entries[r],e)<0?t=r+1:n=r;}return t}insert(e){if(this.limit===0)return {inserted:false};if(this.index.has(e.id))throw new Error(`WindowIndex already contains id "${e.id}"`);let t=this.lowerBound(e);if(this.isFull&&t>=this.limit)return {inserted:false};if(this.entries.splice(t,0,e),this.index.set(e.id,e),this.entries.length>this.limit){let n=this.entries.pop();if(n)return this.index.delete(n.id),{inserted:true,evicted:n}}return {inserted:true}}remove(e){let t=this.index.get(e);if(!t)return;let n=this.lowerBound(t);return this.entries.splice(n,1),this.index.delete(e),t}has(e){return this.index.has(e)}position(e){let t=this.index.get(e);if(t)return this.lowerBound(t)}boundary(){return this.entries[this.entries.length-1]}needsBackfill(){return this.entries.length<this.limit}get backfillCount(){return Math.max(0,this.limit-this.entries.length)}snapshot(){return this.entries.map(e=>({id:e.id,sortKey:[...e.sortKey]}))}ids(){return this.entries.map(e=>e.id)}};var ye=class{storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){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,o]of Object.entries(n.relations))o.type==="one"&&o.relationalColumn&&t.set(String(o.relationalColumn),{relationName:r,targetResource:o.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 o=this.objectNodes.get(e),c=this.objectNodes.get(t);if(o&&o.referencesObjects.set(n,t),c&&r){let s=c.referencedByObjects.get(r);s||(s=new Set,c.referencedByObjects.set(r,s)),s.add(e);}}removeRelation(e,t,n,r){let o=this.objectNodes.get(e),c=this.objectNodes.get(t);if(o&&o.referencesObjects.delete(n),c&&r){let s=c.referencedByObjects.get(r);s&&(s.delete(e),s.size===0&&c.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let o=r.relations[n];if(!o)return;let c=this.schema[t];if(c!=null&&c.relations){if(o.type==="many"&&o.foreignColumn){for(let[s,a]of Object.entries(c.relations))if(a.entity.name===e&&a.type==="one"&&a.relationalColumn===o.foreignColumn)return s}if(o.type==="one"&&o.relationalColumn){for(let[s,a]of Object.entries(c.relations))if(a.entity.name===e&&a.type==="many"&&a.foreignColumn===o.relationalColumn)return s}}}updateRelationsFromMutation(e,t,n,r){let o=this.getRelationalColumns(e),c=this.objectNodes.get(t);if(c)for(let[s,{relationName:a,targetResource:l}]of Array.from(o)){if(!(r&&s in r))continue;let d=this.getInverseRelationName(e,l,a),p=c.referencesObjects.get(a),y=n[s];p!==y&&(p&&this.removeRelation(t,p,a,d),y&&(this.ensureObjectNode(y,l),this.storeRelation(t,y,a,d)));}}get(e,t){let n=this.addedSortRelations(e.resource,e.sort,e.include),r={...e.include??{}};for(let c of n)r[c]=true;let o={...e,...e.limit!==void 0?{sort:[...e.sort??[],{key:"id",direction:"asc"}]}:{},...Object.keys(r).length>0?{include:this.prepareResolveInclude(r,e.resource)}:{}};return K(this.storage.get(o)).then(c=>(this.ingest(e,c),this.stripResolveRelations(c,e.resource,e.include,e.sort),c))}addedSortRelations(e,t,n){var o,c;let r=[];for(let s of t??[]){let a=s.key.indexOf(".");if(a===-1)continue;let l=s.key.slice(0,a);(c=(o=this.schema[e])==null?void 0:o.relations)!=null&&c[l]&&(n&&l in n||r.includes(l)||r.push(l));}return r}stripResolveRelations(e,t,n,r){var c,s,a;let o=this.addedSortRelations(t,r,n);if(o.length>0)for(let l of e){let u=l==null?void 0:l.value;if(u)for(let d of o)delete u[d];}if(n)for(let[l,u]of Object.entries(n)){let d=(s=(c=this.schema[t])==null?void 0:c.relations)==null?void 0:s[l],p=d==null?void 0:d.entity.name;if(!p)continue;let y=H(u)?u:null,f=y?y.include:u&&typeof u=="object"?u:void 0,m=y==null?void 0:y.orderBy;for(let h of e){let T=(a=h==null?void 0:h.value)==null?void 0:a[l];if(!T)continue;let R=d.type==="many"?Array.isArray(T.value)?T.value:[]:[T];this.stripResolveRelations(R,p,f,m);}}}relationalSortDeps(e){var r,o;let t=[],n=e.sort??[];for(let c=0;c<n.length;c++){let s=n[c].key.indexOf(".");if(s===-1)continue;let a=n[c].key.slice(0,s),l=n[c].key.slice(s+1),u=(o=(r=this.schema[e.resource])==null?void 0:r.relations)==null?void 0:o[a];u&&t.push({index:c,relationName:a,field:l,targetResource:u.entity.name});}return t}sortRelationInclude(e){let t=this.relationalSortDeps(e.queryStep.query);if(t.length===0)return;let n={};for(let r of t)n[r.relationName]=true;return n}relationalSortFkColumns(e){let t=new Set,n=this.relationalSortDeps(e.queryStep.query);if(n.length===0)return t;let r=this.getRelationalColumns(e.queryStep.query.resource);for(let[o,{relationName:c}]of Array.from(r))n.some(s=>s.relationName===c)&&t.add(o);return t}ownWriteTouchesSortRelationFk(e,t){if(!t)return false;for(let n of Array.from(this.relationalSortFkColumns(e)))if(n in t)return true;return false}async resolveSortRelations(e,t,n){let r=this.sortRelationInclude(e);if(!r)return n;let o=await K(this.storage.get({resource:e.queryStep.query.resource,where:{id:t},include:r})),c=o[0]?S(o[0]):void 0;if(!c||typeof c!="object")return n;for(let s of Object.keys(r))s in c||(c[s]=void 0);return c}stripPayloadRelations(e,t){if(t)for(let n of Object.keys(t))delete e[n];return e}prepareResolveInclude(e,t){var r,o,c;let n={};for(let[s,a]of Object.entries(e)){let l=(c=(o=(r=this.schema[t])==null?void 0:r.relations)==null?void 0:o[s])==null?void 0:c.entity.name;if(H(a)){let u=a.limit!==void 0,d={...a.include??{}};if(u&&l)for(let y of this.addedSortRelations(l,a.orderBy,a.include))d[y]=true;let p=l&&Object.keys(d).length>0?this.prepareResolveInclude(d,l):a.include;n[s]={...a,...p!==void 0?{include:p}:{},...u?{orderBy:[...a.orderBy??[],{key:"id",direction:"asc"}]}:{}};}else a&&typeof a=="object"&&l?n[s]=this.prepareResolveInclude(a,l):n[s]=a;}return n}ingest(e,t){for(let n of this.buildSteps({query:e})){let r=n.stepPath.length===0?t:this.extractByPath(t,e.resource,n.stepPath);this.trackObjects(n,r);}}extractByPath(e,t,n){var c,s,a;let r=e,o=t;for(let l of n){let u=(s=(c=this.schema[o])==null?void 0:c.relations)==null?void 0:s[l],d=(u==null?void 0:u.type)==="many",p=[];for(let y of r){let f=(a=y==null?void 0:y.value)==null?void 0:a[l];if(f)if(d){if(Array.isArray(f.value))for(let m of f.value)m&&p.push(m);}else f.value!=null&&p.push(f);}r=p,u&&(o=u.entity.name);}return r}subscribe(e,t,n={}){let r=this.buildSteps({query:e}),o={},c=[];for(let s of r){this.logger.debug("[QueryEngine] Subscribing to step",s.stepPath.join("."));let a=Se(s),l=o[s.stepPath.at(-2)??""],u=s.stepPath.at(-1)??"",d=this.queryNodes.get(a);if(d)d.subscriptions.add(t);else {let p=s.stepPath.length===0&&s.query.limit!==void 0;if(d={hash:a,queryStep:s,relationName:u,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:l,childQueries:new Set,windowIndex:p?new G({limit:s.query.limit,orderBy:this.orderByFor(s.query)}):void 0},this.queryNodes.set(d.hash,d),l){let y=this.queryNodes.get(l);y&&y.childQueries.add(d.hash);}}o[u]=a,c.push(()=>{let p=this.queryNodes.get(a);p&&(p.subscriptions.delete(t),p.subscriptions.size===0&&this.queryNodes.delete(a));});}return ()=>{for(let s of c)s();}}buildSteps(e){var y,f;let{query:t,stepPath:n=[],parentResource:r}=e,{include:o}=t,c=n.length===0,s=n.at(-1),a;if(!c&&r&&s){let m=(f=(y=this.schema[r])==null?void 0:y.relations)==null?void 0:f[s];m&&(a=m.type==="many");}let{include:l,...u}=t,p=[{query:u,stepPath:[...n],includedRelations:o&&typeof o=="object"?Object.keys(o):[],isMany:a,relationName:s}];if(o&&typeof o=="object"&&Object.keys(o).length>0){let m=this.schema[t.resource];if(!m)throw new Error(`Resource ${t.resource} not found`);p.push(...Object.entries(o).flatMap(([h,T])=>{let R=m.relations[h];if(!R)throw new Error(`Relation ${h} not found for resource ${t.resource}`);let w=R.entity.name,x=H(T)?T:null;return this.buildSteps({query:{resource:w,include:x?x.include:typeof T=="object"?T:void 0,where:x==null?void 0:x.where,limit:x==null?void 0:x.limit,sort:x==null?void 0:x.orderBy},stepPath:[...n,h],parentResource:t.resource})}));}return p}trackObjects(e,t){var a;this.logger.debug("[QueryEngine] Tracking step objects",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=Se(e),r=this.queryNodes.get(n),o=e.query.resource;if(!r)return;let c=this.getRelationalColumns(o);for(let l of t){let u=S(l),d=u.id;this.ensureObjectNode(d,o,n),r.trackedObjects.add(d);for(let[p,{relationName:y,targetResource:f}]of Array.from(c)){let m=u[p];if(m){this.ensureObjectNode(m,f);let h=this.getInverseRelationName(o,f,y);this.storeRelation(d,m,y,h);}}this.loadNestedRelations(o,d,u),this.logger.debug("[QueryEngine] Loaded nested relations for",d);}if(r.windowIndex&&!r.windowInitialized){for(let l of t){let u=S(l);!(u!=null&&u.id)||r.windowIndex.has(u.id)||r.windowIndex.insert({id:u.id,sortKey:this.sortKeyFor(r,u)});}r.windowInitialized=true;}let s=this.includeForeignColumn(r);if(s){r.seededParents??=new Set;for(let l of t){let u=S(l),d=u==null?void 0:u.id,p=u==null?void 0:u[s];if(!d||p==null||r.seededParents.has(p))continue;let y=this.ensureParentWindow(r,p);y.has(d)||y.insert({id:d,sortKey:this.sortKeyFor(r,u)});}for(let l of t){let u=(a=S(l))==null?void 0:a[s];u!=null&&r.seededParents.add(u);}}}orderByFor(e){return (e.sort??[]).map(t=>({key:t.key,direction:t.direction}))}sortKeyFor(e,t,n){return (e.queryStep.query.sort??[]).map((r,o)=>{let c=r.key.indexOf(".");if(c===-1)return t==null?void 0:t[r.key];let s=r.key.slice(0,c),a=r.key.slice(c+1),l=t==null?void 0:t[s];if(l&&typeof l=="object"&&a in l)return l[a];if(!(t&&typeof t=="object"&&s in t))return n==null?void 0:n[o]})}storageSortFor(e){return [...e.queryStep.query.sort??[],{key:"id",direction:"asc"}]}includeForeignColumn(e){var o,c;if(e.queryStep.stepPath.length===0||e.queryStep.query.limit===void 0||!e.relationName||!e.parentQuery)return;let t=this.queryNodes.get(e.parentQuery),n=t==null?void 0:t.queryStep.query.resource;if(!n)return;let r=(c=(o=this.schema[n])==null?void 0:o.relations)==null?void 0:c[e.relationName];if(!((r==null?void 0:r.type)!=="many"||!r.foreignColumn))return String(r.foreignColumn)}isWindowedIncludeNode(e){return this.includeForeignColumn(e)!==void 0}ensureParentWindow(e,t){e.windowIndexes||(e.windowIndexes=new Map);let n=e.windowIndexes.get(t);return n||(n=new G({limit:e.queryStep.query.limit,orderBy:this.orderByFor(e.queryStep.query)}),e.windowIndexes.set(t,n)),n}parentWindowHolding(e,t){if(e.windowIndexes){for(let[n,r]of Array.from(e.windowIndexes))if(r.has(t))return {parentId:n,wi:r}}}emitToSubscribers(e,t,n){for(let r of Array.from(e.subscriptions))try{r(t);}catch(o){this.logger.error(`[QueryEngine] Error in subscription during ${n}`,{error:o,queryHash:e.hash,resource:t.resource,resourceId:t.resourceId});}}emitScopeOut(e,t,n){var r;e.trackedObjects.delete(t),(r=this.objectNodes.get(t))==null||r.matchedQueries.delete(e.hash),this.emitToSubscribers(e,{type:"SYNC",op:"DELETE",resource:e.queryStep.query.resource,resourceId:t,payload:{},meta:n},"scope-out DELETE");}handleWindowedInsert(e,t,n,r){var c;let o=t.insert({id:n.resourceId,sortKey:this.sortKeyFor(e,r)});o.inserted&&(e.trackedObjects.add(n.resourceId),(c=this.objectNodes.get(n.resourceId))==null||c.matchedQueries.add(e.hash),this.emitToSubscribers(e,n,"windowed scope-in INSERT"),o.evicted&&this.emitScopeOut(e,o.evicted.id,n.meta));}async handleWindowedUpdate(e,t,n,r,o){let c=e.windowIndex;if(!c)return;let s=t.resourceId,a=c.has(s);if(o&&(!a||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,s,r)),o){if(a){await this.refreshInWindow(e,c,t,r);return}this.scopeInViaUpdate(e,c,t,n,r);return}a&&(c.remove(s),this.emitScopeOut(e,s,t.meta),await this.backfillWindow(e,c,t.meta));}async refreshInWindow(e,t,n,r,o){var l,u;let c=n.resourceId,s=(l=t.remove(c))==null?void 0:l.sortKey,a=this.sortKeyFor(e,r,s);if(t.insert({id:c,sortKey:a}),t.isFull&&((u=t.boundary())==null?void 0:u.id)===c&&!this.sortKeysEqual(s,a)){await this.reconcileDemotion(e,t,c,a,n,o);return}this.emitToSubscribers(e,n,"windowed UPDATE");}scopeInViaUpdate(e,t,n,r,o){var a;let c=n.resourceId,s=t.insert({id:c,sortKey:this.sortKeyFor(e,o)});s.inserted&&(e.trackedObjects.add(c),(a=this.objectNodes.get(c))==null||a.matchedQueries.add(e.hash),this.emitToSubscribers(e,this.fullInsertDelta(e,n,r),"windowed scope-in INSERT"),s.evicted&&this.emitScopeOut(e,s.evicted.id,n.meta));}async handleWindowedIncludeUpdate(e,t,n,r,o){let c=this.includeForeignColumn(e);if(!c)return;let s=t.resourceId,a=o?r[c]:void 0,l=this.parentWindowHolding(e,s),u=l==null?void 0:l.parentId,d=u!==void 0&&u===a;if((a!==void 0&&!d||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,s,r)),d){await this.refreshInWindow(e,l.wi,t,r,{column:c,parentId:u});return}if(l&&(l.wi.remove(s),this.emitScopeOut(e,s,t.meta),await this.backfillWindow(e,l.wi,t.meta,{column:c,parentId:l.parentId})),a!==void 0){let p=this.ensureParentWindow(e,a);p.has(s)||this.scopeInViaUpdate(e,p,t,n,r);}}async handleRelationalSortFanout(e,t){if(!e.payload)return;let n=this.objectNodes.get(e.resourceId);for(let r of Array.from(this.queryNodes.values())){let o=this.relationalSortDeps(r.queryStep.query);if(o.length===0)continue;let c=!!r.windowIndex,s=this.isWindowedIncludeNode(r);if(!c&&!s)continue;let a=false;for(let l of o){if(l.targetResource!==e.resource||!(l.field in e.payload))continue;a=true;let u=t==null?void 0:t[l.field],d=this.getInverseRelationName(r.queryStep.query.resource,e.resource,l.relationName),p=n&&d?n.referencedByObjects.get(d):void 0;if(!(!p||p.size===0))for(let y of Array.from(p))if(c){let f=r.windowIndex;if(!f.has(y))continue;this.repositionForRelationalChange(f,y,l.index,u);}else {let f=this.parentWindowHolding(r,y);if(!f)continue;this.repositionForRelationalChange(f.wi,y,l.index,u);}}if(a){if(c)r.windowInitialized&&await this.reconcilePromotions(r,r.windowIndex,e);else if(r.windowIndexes){let l=this.includeForeignColumn(r);for(let[u,d]of Array.from(r.windowIndexes))await this.reconcilePromotions(r,d,e,{column:l,parentId:u});}}}}repositionForRelationalChange(e,t,n,r){let o=e.remove(t);if(!o)return;let c=[...o.sortKey];c[n]=r,e.insert({id:t,sortKey:c});}async reconcilePromotions(e,t,n,r){let o=e.queryStep.query.limit;if(o===void 0)return;let c=e.queryStep.query.resource,s=this.sortRelationInclude(e),a=e.queryStep.query.where;r&&(a=this.combineWhere(a,{[r.column]:r.parentId}));let u=(await K(this.storage.get({resource:c,where:a,sort:this.storageSortFor(e),limit:o,include:s}))).map(p=>({row:p,value:S(p)})).filter(p=>{var y;return !!((y=p.value)!=null&&y.id)}),d=new Set(u.map(p=>p.value.id));for(let p of t.ids())d.has(p)||(t.remove(p),this.emitScopeOut(e,p,n.meta));for(let{row:p,value:y}of u){let f=this.sortKeyFor(e,y);if(t.has(y.id)){t.remove(y.id),t.insert({id:y.id,sortKey:f});continue}let m=t.insert({id:y.id,sortKey:f});if(!m.inserted)continue;e.trackedObjects.add(y.id),this.ensureObjectNode(y.id,c,e.hash).matchedQueries.add(e.hash),this.registerObjectRelations(c,y.id,y);let h=this.stripPayloadRelations({...(p==null?void 0:p.value)??{}},s);delete h.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:c,resourceId:y.id,payload:h,meta:n.meta},"windowed relational promotion INSERT"),m.evicted&&this.emitScopeOut(e,m.evicted.id,n.meta);}}registerObjectRelations(e,t,n){let r=this.getRelationalColumns(e);for(let[o,{relationName:c,targetResource:s}]of Array.from(r)){let a=n==null?void 0:n[o];if(!a)continue;this.ensureObjectNode(a,s);let l=this.getInverseRelationName(e,s,c);this.storeRelation(t,a,c,l);}}sortKeysEqual(e,t){if(!e||e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return false;return true}async reconcileDemotion(e,t,n,r,o,c){t.remove(n);let s=e.queryStep.query.resource,a=this.windowReadWhere(e,t,c),l=this.sortRelationInclude(e),u=await K(this.storage.get({resource:s,where:a,sort:this.storageSortFor(e),limit:2,include:l})),d,p;for(let f of u){let m=S(f);if(!(!(m!=null&&m.id)||m.id===n||t.has(m.id))){d=m,p=f;break}}if(!d){t.insert({id:n,sortKey:r}),this.emitToSubscribers(e,o,"windowed UPDATE");return}if(t.insert({id:d.id,sortKey:this.sortKeyFor(e,d)}),t.insert({id:n,sortKey:r}).inserted){this.emitToSubscribers(e,o,"windowed UPDATE");return}e.trackedObjects.add(d.id),this.ensureObjectNode(d.id,s,e.hash).matchedQueries.add(e.hash);let y=this.stripPayloadRelations({...(p==null?void 0:p.value)??{}},l);delete y.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:s,resourceId:d.id,payload:y,meta:o.meta},"windowed demotion backfill INSERT"),this.emitScopeOut(e,n,o.meta);}fullInsertDelta(e,t,n){let r={...(n==null?void 0:n.value)??{}};return delete r.id,{type:"SYNC",op:"INSERT",resource:e.queryStep.query.resource,resourceId:t.resourceId,payload:r,meta:t.meta}}async backfillWindow(e,t,n,r){let o=t.backfillCount;if(o<=0)return;let c=e.queryStep.query.resource,s=this.windowReadWhere(e,t,r),a=this.sortRelationInclude(e),l=await K(this.storage.get({resource:c,where:s,sort:this.storageSortFor(e),limit:o,include:a}));for(let u of l){let d=S(u);if(!(d!=null&&d.id)||t.has(d.id))continue;t.insert({id:d.id,sortKey:this.sortKeyFor(e,d)}),e.trackedObjects.add(d.id),this.ensureObjectNode(d.id,c,e.hash).matchedQueries.add(e.hash);let p=this.stripPayloadRelations({...(u==null?void 0:u.value)??{}},a);delete p.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:c,resourceId:d.id,payload:p,meta:n},"windowed backfill INSERT");}}buildCursorWhere(e,t){if(!t)return;let n=[...e.queryStep.query.sort??[],{key:"id",direction:"asc"}],r=[...t.sortKey,t.id],o=[];for(let c=0;c<n.length;c++){let s=[];for(let l=0;l<c;l++)s.push(this.cursorCond(n[l].key,r[l]));let a=n[c].direction==="desc"?"$lt":"$gt";s.push(this.cursorCond(n[c].key,{[a]:r[c]})),o.push(s.length===1?s[0]:{$and:s});}return o.length===1?o[0]:{$or:o}}cursorCond(e,t){let n=e.indexOf(".");return n===-1?{[e]:t}:{[e.slice(0,n)]:{[e.slice(n+1)]:t}}}windowReadWhere(e,t,n){let r=e.queryStep.query.where;return n&&(r=this.combineWhere(r,{[n.column]:n.parentId})),this.combineWhere(r,this.buildCursorWhere(e,t.boundary()))}combineWhere(e,t){return t?!e||Object.keys(e).length===0?t:{$and:[e,t]}:e}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[o,c]of Object.entries(r.relations)){let s=n[o];if(!s)continue;let a=c.entity.name,l=this.getInverseRelationName(e,a,o);if(c.type==="one")s&&typeof s=="object"&&s.id&&(this.ensureObjectNode(s.id,a),this.storeRelation(t,s.id,o,l),this.loadNestedRelations(a,s.id,s));else if(c.type==="many"&&Array.isArray(s)){for(let u of s)if(u&&typeof u=="object"&&u.id){this.ensureObjectNode(u.id,a);let d=this.getInverseRelationName(a,e,o);d&&this.storeRelation(u.id,t,d,o),this.loadNestedRelations(a,u.id,u);}}}}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 o=this.queryNodes.get(r);if(!o||!o.relationName)continue;let c=this.buildIncludeFromChildQueries(r);n[o.relationName]=Object.keys(c).length>0?c:true;}return n}sendInsertsForTree(e,t,n,r){var a,l;let o=(l=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:l.value;if(!o)return;let c={op:"INSERT",resource:n,resourceId:o,type:"SYNC",payload:t.value,meta:r};for(let u of Array.from(e.subscriptions))try{u(c);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:o,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(o),this.ensureObjectNode(o,n,e.hash).matchedQueries.add(e.hash);for(let u of Array.from(e.childQueries)){let d=this.queryNodes.get(u);if(!d||!d.relationName)continue;let p=d.relationName,y=d.queryStep.query.resource,f=t.value[p];if(!f)continue;let m=f.value;if(Array.isArray(m))for(let h of m)this.sendInsertsForTree(d,h,y,r);else m&&typeof m=="object"&&this.sendInsertsForTree(d,m,y,r);}}handleMutation(e,t){if(e.op==="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 o=this.getRelationalColumns(e.resource);for(let[s,{relationName:a,targetResource:l}]of Array.from(o)){let u=n[s];if(u){this.ensureObjectNode(u,l);let d=this.getInverseRelationName(e.resource,l,a);this.storeRelation(e.resourceId,u,a,d);}}let c=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(async s=>{try{for(let a of s){let l=this.queryNodes.get(a);if(!l)continue;if(l.windowIndex){let d=await this.resolveSortRelations(l,e.resourceId,n);this.handleWindowedInsert(l,l.windowIndex,e,d);continue}let u=this.includeForeignColumn(l);if(u){let d=n[u];if(d!=null){let p=await this.resolveSortRelations(l,e.resourceId,n);this.handleWindowedInsert(l,this.ensureParentWindow(l,d),e,p);}continue}l.trackedObjects.add(e.resourceId),c&&c.matchedQueries.add(a);for(let d of Array.from(l.subscriptions))try{d(e);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:p,queryHash:l.hash,resource:e.resource,resourceId:e.resourceId,stepPath:l.queryStep.stepPath.join(".")});}}}catch(a){this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:a,resource:e.resource,resourceId:e.resourceId});}},s=>{this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:s,resource:e.resource,resourceId:e.resourceId});});return}if(e.op==="UPDATE"){let n=S(t);if(!n)return;let r=this.objectNodes.get(e.resourceId),o=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.handleRelationalSortFanout(e,n).catch(c=>{this.logger.error("[QueryEngine] Error during relational sort fan-out",{error:c,resource:e.resource,resourceId:e.resourceId});}),this.getMatchingQueries(e,n).then(async c=>{let s=new Set(c),a=new Set;for(let y of Array.from(this.queryNodes.values()))y.queryStep.query.resource===e.resource&&(y.windowIndex?(a.add(y.hash),await this.handleWindowedUpdate(y,e,t,n,s.has(y.hash))):this.isWindowedIncludeNode(y)&&(a.add(y.hash),await this.handleWindowedIncludeUpdate(y,e,t,n,s.has(y.hash))));let l=[],u=[],d=[];for(let y of c)a.has(y)||(o.has(y)?d.push(y):l.push(y));for(let y of Array.from(o))a.has(y)||s.has(y)||u.push(y);for(let y of l){let f=this.queryNodes.get(y);f&&f.trackedObjects.add(e.resourceId);}for(let y of u){let f=this.queryNodes.get(y);f&&f.trackedObjects.delete(e.resourceId);}let p=this.objectNodes.get(e.resourceId);if(p){for(let y of l)p.matchedQueries.add(y);for(let y of u)p.matchedQueries.delete(y);}for(let y of [...u,...d]){let f=this.queryNodes.get(y);if(f)for(let m of Array.from(f.subscriptions))try{m(e);}catch(h){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:h,queryHash:f.hash,resource:e.resource,resourceId:e.resourceId,stepPath:f.queryStep.stepPath.join(".")});}}if(l.length>0)for(let y of l){let f=this.queryNodes.get(y);if(!f)continue;let m=this.buildIncludeFromChildQueries(y);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(m).length>0?m:void 0}).then(h=>{!h||h.length===0||this.sendInsertsForTree(f,h[0],e.resource,e.meta);});}});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?K([]):Promise.all(n.map(async r=>{let o=r.queryStep.query.where,c=r.queryStep.query.resource,s=e.resourceId,a=this.objectNodes.get(s);if(!a)return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=y==null?void 0:y.queryStep.query.resource,m=f?this.getInverseRelationName(f,c,r.relationName):void 0,h=m?a.referencesObjects.get(m):void 0;if(!h)return {hash:r.hash,matches:false};let T=this.objectNodes.get(h);if(!T||!y||!T.matchedQueries.has(y.hash))return {hash:r.hash,matches:false}}if(!o)return {hash:r.hash,matches:true};let l=Re(o,c,this.schema),u=Object.keys(l).length>0;if(!u&&t!==void 0)return {hash:r.hash,matches:V(t,o)};let d=await this.storage.get({resource:c,where:{id:s},include:u?l:void 0});if(!d||d.length===0)return {hash:r.hash,matches:false};let p=S(d[0]);return p?{hash:r.hash,matches:V(p,o)}:{hash:r.hash,matches:false}})).then(r=>r.filter(o=>o.matches).map(o=>o.hash))}};var mr=i=>i,kt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],Dt=i=>i.length===1?i[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let o of i){let c=await o({...e,value:n,rawValue:t});c&&(t=c,n=S(t),n.id=e.value.id,r=true);}return r?t:void 0}),Ft=i=>i.length===1?i[0]:(async e=>{for(let t of i)await t(e);}),ve=i=>{let e=i.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of kt){let r=e.map(o=>o[n]).filter(o=>o!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=Ft(r):t[n]=Dt(r));}return t},hr=(...i)=>{let e={},t=new Set;for(let n of i)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=i.map(c=>c[n]),o=ve(r);o&&(e[n]=o);}return e};var Ze=Qe(we());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(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()});var be=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()})),Jt=be.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Gt=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),ze=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),Z=Gt.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:ze}),Ie=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("SYNC"),resource:zod.z.string(),resourceId:zod.z.string(),op:zod.z.enum(["INSERT","UPDATE","DELETE"]),payload:Jt,meta:ze}),Ce=(i,e)=>{i.op==="DELETE"&&Object.keys(i.payload).length>0&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"DELETE delta payload must be empty"});};Ie.superRefine(Ce);var Je=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var Ge=Z.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:Z.shape.meta});var Le=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(Le);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=Le(n);return e}return i},Ye=i=>{let e=i.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,o={headers:r,cookies:r.cookie?Ze.default.parse(r.cookie):{}},c=new URL(t.url),s=c.pathname.split("/"),a=c.searchParams,l=Le(Zt__default.default.parse(a.toString())),u=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:o.headers,cookies:o.cookies,queryParams:l}))??{};if(t.method==="POST")try{let d=s[s.length-1],p=s[s.length-2];if(p==="query"){if(s.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let x=s[s.length-3],C=t.body?await t.json():{};if(!x||x.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let O=await i.handleCustomQuery({req:{...o,type:"CUSTOM_QUERY",resource:x,procedure:d,input:C.input,context:u,queryParams:l}});return Response.json(O)}let y=p,f=t.body?await t.json():{},{success:m,data:h,error:T}=Ge.safeParse(f);if(!m)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:T},{status:400});let R=h,w=await i.handleMutation({req:{...o,type:"MUTATE",resource:y,input:R.payload,context:u,resourceId:R.resourceId,procedure:d,queryParams:{},meta:R.meta}});return Response.json(w)}catch(d){return e.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(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var et=Qe(we());var F=zod.z.string(),Me=Je,Yt=zod.z.object({id:F,type:zod.z.literal("SUBSCRIBE")}).and(Me),Xt=zod.z.object({id:F,type:zod.z.literal("UNSUBSCRIBE")}).and(Me),en=zod.z.object({id:F,type:zod.z.literal("QUERY")}).and(Me),tn=zod.z.object({id:F,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),nn=Z.extend({id:F}),rn=nn,Xe=zod.z.union([Yt,en,tn,rn,Xt]),sn=zod.z.object({id:F,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),on=zod.z.object({id:F,type:zod.z.literal("REPLY"),data:zod.z.any()}),an=Ie.extend({id:F}).superRefine(Ce);zod.z.union([sn,on,an]);zod.z.object({resource:zod.z.string(),data:zod.z.array(be)});var tt=i=>{let e={},t=i.logger;return (n,r)=>{var d;let o=p=>{n.send(JSON.stringify(p));},c=de(),s=new Map,a={headers:r.headers,cookies:typeof r.headers.cookie=="string"?et.default.parse(r.headers.cookie):{}},l=Zt.parse(r.url.split("?")[1]),u=(d=i.contextProvider)==null?void 0:d.call(i,{transport:"WEBSOCKET",headers:a.headers,cookies:a.cookies,queryParams:l});e[c]=n,t.info("Client connected:",c),n.on("message",async p=>{try{t.debug("Message received from the client:",p);let y=Xe.parse(JSON.parse(p.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:f,id:m,...h}=y,T=f==="SUBSCRIBE";try{let R=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h.resource,procedure:h.procedure,input:h.input,context:await u??{},queryParams:l},subscription:T?w=>{var x;!w.resourceId||!w.payload||!Object.keys(w.payload).length||(x=e[c])==null||x.send(JSON.stringify(w));}:void 0});if(T){if(!R||!R.data||!R.query)throw new Error("Cannot subscribe to a one-shot query: the procedure must return a query builder (a Tracked Query), not a computed value");R.unsubscribe&&s.set(U(h),R.unsubscribe),o({id:m,type:"REPLY",data:{resource:R.query.resource,data:(R.data??[]).map(w=>w.value)}});}else o({id:m,type:"REPLY",data:R});}catch(R){o({id:m,type:"REJECT",resource:h.resource,message:R.message}),t.error("Error handling query from the client:",R);}}else if(y.type==="UNSUBSCRIBE"){let{type:f,id:m,...h}=y,T=s.get(U(h));T&&(T(),s.delete(U(h)));}else if(y.type==="CUSTOM_QUERY"){let{resource:f,procedure:m,input:h,id:T}=y;t.debug("Received custom query from client:",y);try{let R=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:f,procedure:m,input:h,context:await u??{},queryParams:l}});o({id:T,type:"REPLY",data:R});}catch(R){o({id:T,type:"REJECT",resource:f,message:R.message}),t.error("Error handling custom query from the client:",R);}}else if(y.type==="MUTATE"){let{resource:f}=y;t.debug("Received mutation from client:",y);try{let m=await i.handleMutation({req:{...a,type:"MUTATE",resource:f,input:y.payload,context:{messageId:y.id,...await u??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:l,meta:y.meta}});o({id:y.id,type:"REPLY",data:m});}catch(m){o({id:y.id,type:"REJECT",resource:f,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",c),delete e[c];for(let p of Array.from(s.values()))p();});}};function nt(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 qr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,tt(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{Ye(e)(nt(n)).then(c=>c.json().then(s=>r.status(c.status).send(s)));});};var Y=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,o,c,s,a){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=o,this._single=c,this._sort=s,this._shouldAwait=a,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new i(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new i(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new i(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 i(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new i(this._collection,this._client,this._where,this._include,this._limit,this._single,n,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(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,n){return new i(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var ln=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Ae=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>ln(n)?S(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function X(i,e,t){let n=new Ae(i),r=c=>{let s=Y._init(c,n,true);return Object.assign(Object.create(s),{insert:async l=>{let u=i._getTimestamp(),d=await i.rawInsert(c.name,l.id,{value:Object.fromEntries(Object.entries(l).map(([p,y])=>[p,{value:y,_meta:{timestamp:u}}]))},void 0,t);return S(d.data)},update:async(l,u)=>{let d=i._getTimestamp(),{id:p,...y}=u,f=await i.rawUpdate(c.name,l,{value:Object.fromEntries(Object.entries(y).map(([T,R])=>[T,{value:R,_meta:{timestamp:d}}]))},void 0,t),m=S(f.data),h={};for(let T of Object.keys(y))T in m&&(h[T]=m[T]);return h}})},o={get(c,s){if(s==="findOne")return i.findOne.bind(i);if(s==="find")return i.find.bind(i);if(s==="insert")return (a,l)=>{let u=i._getTimestamp();return i.rawInsert(a.name,l.id,{value:Object.fromEntries(Object.entries(l).map(([d,p])=>[d,{value:p,_meta:{timestamp:u}}]))},void 0,t).then(d=>S(d.data))};if(s==="update")return (a,l,u)=>{let d=i._getTimestamp(),{id:p,...y}=u;return i.rawUpdate(a.name,l,{value:Object.fromEntries(Object.entries(y).map(([f,m])=>[f,{value:m,_meta:{timestamp:d}}]))},void 0,t).then(f=>{let m=S(f.data),h={};for(let T of Object.keys(y))T in m&&(h[T]=m[T]);return h})};if(s==="transaction")return async a=>i.transaction(async({trx:l,commit:u,rollback:d})=>{let p=X(l,e,t);return a({trx:p,commit:u,rollback:d})});if(s in e){let a=e[s];return r(a)}}};return new Proxy({},o)}var Oe=class i{routes;schema;constructor(e){this.routes=e.routes,this.schema=e.schema;}static create(e){return new i(e)}},Gr=i=>Oe.create(i),un=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),dn=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),je=class{middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:n})=>{var c;let r=((c=e.meta)==null?void 0:c.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let a=this.customMutations[s.procedure];if(a){let l=a.inputValidator["~standard"].validate(s.input),u=l instanceof Promise?await l:l;if(u.issues){let p=u.issues.map(y=>{var m;let f=(m=y.path)==null?void 0:m.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return f?`${f}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}s.input=u.value;let d=X(o,n,s.context);return a.handler({req:s,db:d})}throw new Error(`Unknown procedure: ${s.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{let o=this.customQueries[r.procedure];if(!o)throw new Error(`Unknown query procedure: ${r.procedure}`);let c=o.inputValidator["~standard"].validate(r.input),s=c instanceof Promise?await c:c;if(s.issues){let l=s.issues.map(u=>{var p;let d=(p=u.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${u.message}`:u.message}).join(", ");throw new Error(`Validation failed: ${l}`)}r.input=s.value;let a=X(t,n,r.context);return o.handler({req:r,db:a})})(e);wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}};function Zr(i){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>i({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var Ee=class i{middlewares;constructor(e=[]){this.middlewares=e;}withProcedures(e){let t=e({mutation:dn,query:un}),n={},r={};for(let[o,c]of Object.entries(t))c._type==="mutation"?n[o]=c:r[o]=c;return new je(n,r).use(...this.middlewares)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new i([...this.middlewares,...t])}static create(){return new i}},Yr=Ee.create;var ee=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([o,c])=>[o,{value:c,_meta:{timestamp:n}}]))});return S(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:o,...c}=n,s=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(c).map(([u,d])=>[u,{value:d,_meta:{timestamp:r}}]))}),a=S(s.data),l={};for(let u of Object.keys(c))u in a&&(l[u]=a[u]);return l}};var gn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function k(i){var r,o,c;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((c=(o=t.constructor)==null?void 0:o.name)==null?void 0:c.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function it(i){let e=k(i);return gn[e]}var xn="42701";function te(i){var t;if(i.code===xn)return true;let e=((t=i.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function Ne(i,e){let{type:t,enumValues:n,enumName:r}=i;if(n&&n.length>0)return e==="postgres"&&r?r:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function Rn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let o of Object.values(e))for(let c of Object.values(o.fields)){let s=c.getStorageFieldType();s.enumValues&&s.enumName&&r.set(s.enumName,{name:s.enumName,values:s.enumValues});}for(let o of Array.from(r.values())){let{name:c,values:s}=o;try{let a=s.map(l=>`'${l}'`).join(", ");await kysely.sql`
1
+ 'use strict';var jsXxhash=require('js-xxhash'),de=require('crypto'),tn=require('qs'),zod=require('zod'),kysely=require('kysely'),mysql=require('kysely/helpers/mysql'),postgres=require('kysely/helpers/postgres'),sqlite=require('kysely/helpers/sqlite');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var de__default=/*#__PURE__*/_interopDefault(de);var tn__default=/*#__PURE__*/_interopDefault(tn);var ft=Object.create;var Ke=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty;var xt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var St=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ht(e))!gt.call(i,r)&&r!==t&&Ke(i,r,{get:()=>e[r],enumerable:!(n=mt(e,r))||n.enumerable});return i};var Be=(i,e,t)=>(t=i!=null?ft(Tt(i)):{},St(Ke(t,"default",{value:i,enumerable:true}),i));var Le=xt(Te=>{Object.defineProperty(Te,"__esModule",{value:true});Te.parse=Jt;Te.serialize=Gt;var Kt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Bt=/^[\u0021-\u003A\u003C-\u007E]*$/,Wt=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Ut=/^[\u0020-\u003A\u003D-\u007E]*$/,Ht=Object.prototype.toString,zt=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Jt(i,e){let t=new zt,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Zt,s=0;do{let c=i.indexOf("=",s);if(c===-1)break;let o=i.indexOf(";",s),a=o===-1?n:o;if(c>a){s=i.lastIndexOf(";",c-1)+1;continue}let l=Ge(i,s,c),d=Ze(i,c,l),u=i.slice(l,d);if(t[u]===void 0){let y=Ge(i,c+1,a),p=Ze(i,a,y),f=r(i.slice(y,p));t[u]=f;}s=a+1;}while(s<n);return t}function Ge(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function Ze(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Gt(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Kt.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Bt.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(!Wt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain;}if(t.path){if(!Ut.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path;}if(t.expires){if(!Yt(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 Zt(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Yt(i){return Ht.call(i)==="[object Date]"}});var ve=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),R=i=>i?Array.isArray(i.value)?i.value.map(t=>ve(t)?R(t):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=>ve(r)?R(r):r)]:ve(n)?[t,R(n)]:[t,n])):void 0;var H=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),be=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let s=c=>{c.$and?c.$and.forEach(s):c.$or?c.$or.forEach(s):Object.entries(c).forEach(([o,a])=>{var l;if((l=r.relations)!=null&&l[o]&&(n[o]=true,typeof a=="object"&&a!==null&&!Array.isArray(a))){let d=be(a,r.relations[o].entity.name,t);Object.keys(d).length>0&&(n[o]={include:d});}});};return s(i),n},D=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(c=>D(i,c,t));if(n==="$or")return r.some(c=>D(i,c,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 o=i[n];return o===void 0?false:t?!r.$in.includes(o):r.$in.includes(o)}if(r.$not!==void 0&&!t)return D(i,{[n]:r.$not},true);if(r.$gt!==void 0){let o=i[n];return typeof o!="number"?false:t?o<=r.$gt:o>r.$gt}if(r.$gte!==void 0){let o=i[n];return typeof o!="number"?false:t?o<r.$gte:o>=r.$gte}if(r.$lt!==void 0){let o=i[n];return typeof o!="number"?false:t?o>=r.$lt:o<r.$lt}if(r.$lte!==void 0){let o=i[n];return typeof o!="number"?false:t?o>r.$lte:o<=r.$lte}let c=i[n];return !c||typeof c!="object"&&!Array.isArray(c)?false:Array.isArray(c)?t?!c.some(o=>D(o,r,false)):c.some(o=>D(o,r,false)):D(c,r,t)}return t?i[n]!==s:i[n]===s}),z=i=>{if(typeof i!="object"||i===null)return false;let e=i;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},F={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},we=class{level;prefix;constructor(e={}){this.level=e.level??F.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=F.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=F.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=F.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=F.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=F.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},We=i=>new we(i);var He="0123456789ABCDEFGHJKMNPQRSTVWXYZ",G=32;var jt=16,ze=10,Ue=0xffffffffffff;var $;(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";})($||($={}));var Q=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Pt(i){let e=Math.floor(i()*G);return e===G&&(e=G-1),He.charAt(e)}function Vt(i){var n;let e=Dt(),t=e&&(e.crypto||e.msCrypto)||(typeof de__default.default<"u"?de__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=de__default.default)!=null&&n.randomBytes)return ()=>de__default.default.randomBytes(1).readUInt8()/255;throw new Q($.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Dt(){return Nt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function kt(i,e){let t="";for(;i>0;i--)t=Pt(e)+t;return t}function Ft(i,e=ze){if(isNaN(i))throw new Q($.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>Ue)throw new Q($.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Ue}: ${i}`);if(i<0)throw new Q($.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new Q($.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%G,n=He.charAt(t)+n,i=(i-t)/G;return n}function Nt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Je(i,e){let t=Vt(),n=Date.now();return Ft(n,ze)+kt(jt,t)}var pe=()=>Je().toLowerCase(),ye=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ye(n)}return ye(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ye(r)}throw n}}}),K=i=>i instanceof Promise?i:ye(i);function Z(i,e){let t=new Map,n=i[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}function B(i,e,t,n){let r=i[e];if(!(r!=null&&r.relations))return;let s=r.relations[n];if(!s)return;let c=i[t];if(c!=null&&c.relations){if(s.type==="many"&&s.foreignColumn){for(let[o,a]of Object.entries(c.relations))if(a.entity.name===e&&a.type==="one"&&a.relationalColumn===s.foreignColumn)return o}if(s.type==="one"&&s.relationalColumn){for(let[o,a]of Object.entries(c.relations))if(a.entity.name===e&&a.type==="many"&&a.foreignColumn===s.relationalColumn)return o}}}var fe=new Set,me=class{schema;nodes=new Map;constructor(e){this.schema=e;}ensureNode(e){let t=this.nodes.get(e);return t||(t={matchedQueries:new Set,references:new Map,referencedBy:new Map},this.nodes.set(e,t)),t}link(e,t,n,r){if(this.ensureNode(e).references.set(n,t),!r)return;let s=this.ensureNode(t),c=s.referencedBy.get(r);c||(c=new Set,s.referencedBy.set(r,c)),c.add(e);}unlink(e,t,n,r){var c,o,a;if((c=this.nodes.get(e))==null||c.references.delete(n),!r)return;let s=(o=this.nodes.get(t))==null?void 0:o.referencedBy.get(r);s&&(s.delete(e),s.size===0&&((a=this.nodes.get(t))==null||a.referencedBy.delete(r)));}ingest(e,t){let n=t==null?void 0:t.id;if(n){this.ensureNode(n);for(let[r,{relationName:s,targetResource:c}]of Array.from(Z(this.schema,e))){let o=t[r];o&&this.link(n,o,s,B(this.schema,e,c,s));}this.ingestNested(e,n,t);}}ingestNested(e,t,n){var s;let r=(s=this.schema[e])==null?void 0:s.relations;if(r)for(let[c,o]of Object.entries(r)){let a=n[c];if(!a)continue;let l=o.entity.name;if(o.type==="one")typeof a=="object"&&a.id&&(this.link(t,a.id,c,B(this.schema,e,l,c)),this.ingestNested(l,a.id,a));else if(o.type==="many"&&Array.isArray(a)){let d=B(this.schema,l,e,c);for(let u of a)u&&typeof u=="object"&&u.id&&(this.ensureNode(u.id),d&&this.link(u.id,t,d,c),this.ingestNested(l,u.id,u));}}}applyWrite(e,t,n,r){var s;this.ensureNode(t);for(let[c,{relationName:o,targetResource:a}]of Array.from(Z(this.schema,e))){if(r&&!(c in r))continue;let l=B(this.schema,e,a,o),d=(s=this.nodes.get(t))==null?void 0:s.references.get(o),u=n==null?void 0:n[c];d!==u&&(d&&this.unlink(t,d,o,l),u&&this.link(t,u,o,l));}}setMatched(e,t){this.ensureNode(e).matchedQueries.add(t);}clearMatched(e,t){var n;(n=this.nodes.get(e))==null||n.matchedQueries.delete(t);}matches(e,t){var n;return ((n=this.nodes.get(e))==null?void 0:n.matchedQueries.has(t))??false}matchedQueriesOf(e){var t;return ((t=this.nodes.get(e))==null?void 0:t.matchedQueries)??fe}reference(e,t,n){var c,o,a;let r=(o=(c=this.schema[t])==null?void 0:c.relations)==null?void 0:o[n];if(!r)return;let s=B(this.schema,t,r.entity.name,n);if(s)return (a=this.nodes.get(e))==null?void 0:a.references.get(s)}referencedBy(e,t,n){var c,o,a;let r=(o=(c=this.schema[t])==null?void 0:c.relations)==null?void 0:o[n];if(!r)return fe;let s=B(this.schema,t,r.entity.name,n);return s?((a=this.nodes.get(e))==null?void 0:a.referencedBy.get(s))??fe:fe}has(e){return this.nodes.has(e)}};function Ie(i){return H({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}function _t(i,e){let t=i==null,n=e==null;if(t&&n)return 0;if(t)return -1;if(n)return 1;if(typeof i=="number"&&typeof e=="number")return i-e;if(typeof i=="boolean"&&typeof e=="boolean")return Number(i)-Number(e);let r=String(i),s=String(e);return r<s?-1:r>s?1:0}var Y=class{limit;directions;entries=[];index=new Map;constructor(e){if(!Number.isInteger(e.limit)||e.limit<0)throw new Error("WindowIndex limit must be a non-negative integer");this.limit=e.limit,this.directions=(e.orderBy??[]).map(t=>t.direction);}get size(){return this.entries.length}get isFull(){return this.entries.length>=this.limit}compare(e,t){for(let n=0;n<this.directions.length;n++){let r=_t(e.sortKey[n],t.sortKey[n]);if(r!==0)return this.directions[n]==="desc"?-r:r}return e.id<t.id?-1:e.id>t.id?1:0}lowerBound(e){let t=0,n=this.entries.length;for(;t<n;){let r=t+n>>>1;this.compare(this.entries[r],e)<0?t=r+1:n=r;}return t}insert(e){if(this.limit===0)return {inserted:false};if(this.index.has(e.id))throw new Error(`WindowIndex already contains id "${e.id}"`);let t=this.lowerBound(e);if(this.isFull&&t>=this.limit)return {inserted:false};if(this.entries.splice(t,0,e),this.index.set(e.id,e),this.entries.length>this.limit){let n=this.entries.pop();if(n)return this.index.delete(n.id),{inserted:true,evicted:n}}return {inserted:true}}remove(e){let t=this.index.get(e);if(!t)return;let n=this.lowerBound(t);return this.entries.splice(n,1),this.index.delete(e),t}has(e){return this.index.has(e)}position(e){let t=this.index.get(e);if(t)return this.lowerBound(t)}boundary(){return this.entries[this.entries.length-1]}needsBackfill(){return this.entries.length<this.limit}get backfillCount(){return Math.max(0,this.limit-this.entries.length)}snapshot(){return this.entries.map(e=>({id:e.id,sortKey:[...e.sortKey]}))}ids(){return this.entries.map(e=>e.id)}};var he=class{storage;schema;logger;queryNodes=new Map;graph;constructor(e){this.storage=e.storage,this.schema=e.schema,this.logger=e.logger,this.graph=new me(e.schema);}get(e,t){let n=this.addedSortRelations(e.resource,e.sort,e.include),r={...e.include??{}};for(let c of n)r[c]=true;let s={...e,...e.limit!==void 0?{sort:[...e.sort??[],{key:"id",direction:"asc"}]}:{},...Object.keys(r).length>0?{include:this.prepareResolveInclude(r,e.resource)}:{}};return K(this.storage.get(s)).then(c=>(this.ingest(e,c),this.stripResolveRelations(c,e.resource,e.include,e.sort),c))}addedSortRelations(e,t,n){var s,c;let r=[];for(let o of t??[]){let a=o.key.indexOf(".");if(a===-1)continue;let l=o.key.slice(0,a);(c=(s=this.schema[e])==null?void 0:s.relations)!=null&&c[l]&&(n&&l in n||r.includes(l)||r.push(l));}return r}stripResolveRelations(e,t,n,r){var c,o,a;let s=this.addedSortRelations(t,r,n);if(s.length>0)for(let l of e){let d=l==null?void 0:l.value;if(d)for(let u of s)delete d[u];}if(n)for(let[l,d]of Object.entries(n)){let u=(o=(c=this.schema[t])==null?void 0:c.relations)==null?void 0:o[l],y=u==null?void 0:u.entity.name;if(!y)continue;let p=z(d)?d:null,f=p?p.include:d&&typeof d=="object"?d:void 0,m=p==null?void 0:p.orderBy;for(let h of e){let T=(a=h==null?void 0:h.value)==null?void 0:a[l];if(!T)continue;let S=u.type==="many"?Array.isArray(T.value)?T.value:[]:[T];this.stripResolveRelations(S,y,f,m);}}}relationalSortDeps(e){var r,s;let t=[],n=e.sort??[];for(let c=0;c<n.length;c++){let o=n[c].key.indexOf(".");if(o===-1)continue;let a=n[c].key.slice(0,o),l=n[c].key.slice(o+1),d=(s=(r=this.schema[e.resource])==null?void 0:r.relations)==null?void 0:s[a];d&&t.push({index:c,relationName:a,field:l,targetResource:d.entity.name});}return t}sortRelationInclude(e){let t=this.relationalSortDeps(e.queryStep.query);if(t.length===0)return;let n={};for(let r of t)n[r.relationName]=true;return n}relationalSortFkColumns(e){let t=new Set,n=this.relationalSortDeps(e.queryStep.query);if(n.length===0)return t;let r=Z(this.schema,e.queryStep.query.resource);for(let[s,{relationName:c}]of Array.from(r))n.some(o=>o.relationName===c)&&t.add(s);return t}ownWriteTouchesSortRelationFk(e,t){if(!t)return false;for(let n of Array.from(this.relationalSortFkColumns(e)))if(n in t)return true;return false}async resolveSortRelations(e,t,n){let r=this.sortRelationInclude(e);if(!r)return n;let s=await K(this.storage.get({resource:e.queryStep.query.resource,where:{id:t},include:r})),c=s[0]?R(s[0]):void 0;if(!c||typeof c!="object")return n;for(let o of Object.keys(r))o in c||(c[o]=void 0);return c}stripPayloadRelations(e,t){if(t)for(let n of Object.keys(t))delete e[n];return e}prepareResolveInclude(e,t){var r,s,c;let n={};for(let[o,a]of Object.entries(e)){let l=(c=(s=(r=this.schema[t])==null?void 0:r.relations)==null?void 0:s[o])==null?void 0:c.entity.name;if(z(a)){let d=a.limit!==void 0,u={...a.include??{}};if(d&&l)for(let p of this.addedSortRelations(l,a.orderBy,a.include))u[p]=true;let y=l&&Object.keys(u).length>0?this.prepareResolveInclude(u,l):a.include;n[o]={...a,...y!==void 0?{include:y}:{},...d?{orderBy:[...a.orderBy??[],{key:"id",direction:"asc"}]}:{}};}else a&&typeof a=="object"&&l?n[o]=this.prepareResolveInclude(a,l):n[o]=a;}return n}ingest(e,t){for(let n of this.buildSteps({query:e})){let r=n.stepPath.length===0?t:this.extractByPath(t,e.resource,n.stepPath);this.trackObjects(n,r);}}extractByPath(e,t,n){var c,o,a;let r=e,s=t;for(let l of n){let d=(o=(c=this.schema[s])==null?void 0:c.relations)==null?void 0:o[l],u=(d==null?void 0:d.type)==="many",y=[];for(let p of r){let f=(a=p==null?void 0:p.value)==null?void 0:a[l];if(f)if(u){if(Array.isArray(f.value))for(let m of f.value)m&&y.push(m);}else f.value!=null&&y.push(f);}r=y,d&&(s=d.entity.name);}return r}subscribe(e,t,n={}){let r=this.buildSteps({query:e}),s={},c=[];for(let o of r){this.logger.debug("[QueryEngine] Subscribing to step",o.stepPath.join("."));let a=Ie(o),l=s[o.stepPath.at(-2)??""],d=o.stepPath.at(-1)??"",u=this.queryNodes.get(a);if(u)u.subscriptions.add(t);else {let y=o.stepPath.length===0&&o.query.limit!==void 0;if(u={hash:a,queryStep:o,relationName:d,subscriptions:new Set([t]),parentQuery:l,childQueries:new Set,windowIndex:y?new Y({limit:o.query.limit,orderBy:this.orderByFor(o.query)}):void 0},this.queryNodes.set(u.hash,u),l){let p=this.queryNodes.get(l);p&&p.childQueries.add(u.hash);}}s[d]=a,c.push(()=>{let y=this.queryNodes.get(a);y&&(y.subscriptions.delete(t),y.subscriptions.size===0&&this.queryNodes.delete(a));});}return ()=>{for(let o of c)o();}}buildSteps(e){var p,f;let{query:t,stepPath:n=[],parentResource:r}=e,{include:s}=t,c=n.length===0,o=n.at(-1),a;if(!c&&r&&o){let m=(f=(p=this.schema[r])==null?void 0:p.relations)==null?void 0:f[o];m&&(a=m.type==="many");}let{include:l,...d}=t,y=[{query:d,stepPath:[...n],includedRelations:s&&typeof s=="object"?Object.keys(s):[],isMany:a,relationName:o}];if(s&&typeof s=="object"&&Object.keys(s).length>0){let m=this.schema[t.resource];if(!m)throw new Error(`Resource ${t.resource} not found`);y.push(...Object.entries(s).flatMap(([h,T])=>{let S=m.relations[h];if(!S)throw new Error(`Relation ${h} not found for resource ${t.resource}`);let w=S.entity.name,x=z(T)?T:null;return this.buildSteps({query:{resource:w,include:x?x.include:typeof T=="object"?T:void 0,where:x==null?void 0:x.where,limit:x==null?void 0:x.limit,sort:x==null?void 0:x.orderBy},stepPath:[...n,h],parentResource:t.resource})}));}return y}trackObjects(e,t){var o;this.logger.debug("[QueryEngine] Tracking step objects",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;for(let a of t){let l=R(a);this.graph.ingest(s,l),this.graph.setMatched(l.id,n),this.logger.debug("[QueryEngine] Loaded nested relations for",l.id);}if(r.windowIndex&&!r.windowInitialized){for(let a of t){let l=R(a);!(l!=null&&l.id)||r.windowIndex.has(l.id)||r.windowIndex.insert({id:l.id,sortKey:this.sortKeyFor(r,l)});}r.windowInitialized=true;}let c=this.includeForeignColumn(r);if(c){r.seededParents??=new Set;for(let a of t){let l=R(a),d=l==null?void 0:l.id,u=l==null?void 0:l[c];if(!d||u==null||r.seededParents.has(u))continue;let y=this.ensureParentWindow(r,u);y.has(d)||y.insert({id:d,sortKey:this.sortKeyFor(r,l)});}for(let a of t){let l=(o=R(a))==null?void 0:o[c];l!=null&&r.seededParents.add(l);}}}orderByFor(e){return (e.sort??[]).map(t=>({key:t.key,direction:t.direction}))}sortKeyFor(e,t,n){return (e.queryStep.query.sort??[]).map((r,s)=>{let c=r.key.indexOf(".");if(c===-1)return t==null?void 0:t[r.key];let o=r.key.slice(0,c),a=r.key.slice(c+1),l=t==null?void 0:t[o];if(l&&typeof l=="object"&&a in l)return l[a];if(!(t&&typeof t=="object"&&o in t))return n==null?void 0:n[s]})}storageSortFor(e){return [...e.queryStep.query.sort??[],{key:"id",direction:"asc"}]}includeForeignColumn(e){var s,c;if(e.queryStep.stepPath.length===0||e.queryStep.query.limit===void 0||!e.relationName||!e.parentQuery)return;let t=this.queryNodes.get(e.parentQuery),n=t==null?void 0:t.queryStep.query.resource;if(!n)return;let r=(c=(s=this.schema[n])==null?void 0:s.relations)==null?void 0:c[e.relationName];if(!((r==null?void 0:r.type)!=="many"||!r.foreignColumn))return String(r.foreignColumn)}isWindowedIncludeNode(e){return this.includeForeignColumn(e)!==void 0}ensureParentWindow(e,t){e.windowIndexes||(e.windowIndexes=new Map);let n=e.windowIndexes.get(t);return n||(n=new Y({limit:e.queryStep.query.limit,orderBy:this.orderByFor(e.queryStep.query)}),e.windowIndexes.set(t,n)),n}parentWindowHolding(e,t){if(e.windowIndexes){for(let[n,r]of Array.from(e.windowIndexes))if(r.has(t))return {parentId:n,wi:r}}}emitToSubscribers(e,t,n){for(let r of Array.from(e.subscriptions))try{r(t);}catch(s){this.logger.error(`[QueryEngine] Error in subscription during ${n}`,{error:s,queryHash:e.hash,resource:t.resource,resourceId:t.resourceId});}}emitScopeOut(e,t,n){this.graph.clearMatched(t,e.hash),this.emitToSubscribers(e,{type:"SYNC",op:"DELETE",resource:e.queryStep.query.resource,resourceId:t,payload:{},meta:n},"scope-out DELETE");}handleWindowedInsert(e,t,n,r){let s=t.insert({id:n.resourceId,sortKey:this.sortKeyFor(e,r)});s.inserted&&(this.graph.setMatched(n.resourceId,e.hash),this.emitToSubscribers(e,n,"windowed scope-in INSERT"),s.evicted&&this.emitScopeOut(e,s.evicted.id,n.meta));}async handleWindowedUpdate(e,t,n,r,s){let c=e.windowIndex;if(!c)return;let o=t.resourceId,a=c.has(o);if(s&&(!a||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,o,r)),s){if(a){await this.refreshInWindow(e,c,t,r);return}this.scopeInViaUpdate(e,c,t,n,r);return}a&&(c.remove(o),this.emitScopeOut(e,o,t.meta),await this.backfillWindow(e,c,t.meta));}async refreshInWindow(e,t,n,r,s){var l,d;let c=n.resourceId,o=(l=t.remove(c))==null?void 0:l.sortKey,a=this.sortKeyFor(e,r,o);if(t.insert({id:c,sortKey:a}),t.isFull&&((d=t.boundary())==null?void 0:d.id)===c&&!this.sortKeysEqual(o,a)){await this.reconcileDemotion(e,t,c,a,n,s);return}this.emitToSubscribers(e,n,"windowed UPDATE");}scopeInViaUpdate(e,t,n,r,s){let c=n.resourceId,o=t.insert({id:c,sortKey:this.sortKeyFor(e,s)});o.inserted&&(this.graph.setMatched(c,e.hash),this.emitToSubscribers(e,this.fullInsertDelta(e,n,r),"windowed scope-in INSERT"),o.evicted&&this.emitScopeOut(e,o.evicted.id,n.meta));}async handleWindowedIncludeUpdate(e,t,n,r,s){let c=this.includeForeignColumn(e);if(!c)return;let o=t.resourceId,a=s?r[c]:void 0,l=this.parentWindowHolding(e,o),d=l==null?void 0:l.parentId,u=d!==void 0&&d===a;if((a!==void 0&&!u||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,o,r)),u){await this.refreshInWindow(e,l.wi,t,r,{column:c,parentId:d});return}if(l&&(l.wi.remove(o),this.emitScopeOut(e,o,t.meta),await this.backfillWindow(e,l.wi,t.meta,{column:c,parentId:l.parentId})),a!==void 0){let y=this.ensureParentWindow(e,a);y.has(o)||this.scopeInViaUpdate(e,y,t,n,r);}}async handleRelationalSortFanout(e,t){if(e.payload)for(let n of Array.from(this.queryNodes.values())){let r=this.relationalSortDeps(n.queryStep.query);if(r.length===0)continue;let s=!!n.windowIndex,c=this.isWindowedIncludeNode(n);if(!s&&!c)continue;let o=false;for(let a of r){if(a.targetResource!==e.resource||!(a.field in e.payload))continue;o=true;let l=t==null?void 0:t[a.field],d=this.graph.referencedBy(e.resourceId,n.queryStep.query.resource,a.relationName);if(d.size!==0)for(let u of Array.from(d))if(s){let y=n.windowIndex;if(!y.has(u))continue;this.repositionForRelationalChange(y,u,a.index,l);}else {let y=this.parentWindowHolding(n,u);if(!y)continue;this.repositionForRelationalChange(y.wi,u,a.index,l);}}if(o){if(s)n.windowInitialized&&await this.reconcilePromotions(n,n.windowIndex,e);else if(n.windowIndexes){let a=this.includeForeignColumn(n);for(let[l,d]of Array.from(n.windowIndexes))await this.reconcilePromotions(n,d,e,{column:a,parentId:l});}}}}repositionForRelationalChange(e,t,n,r){let s=e.remove(t);if(!s)return;let c=[...s.sortKey];c[n]=r,e.insert({id:t,sortKey:c});}async reconcilePromotions(e,t,n,r){let s=e.queryStep.query.limit;if(s===void 0)return;let c=e.queryStep.query.resource,o=this.sortRelationInclude(e),a=e.queryStep.query.where;r&&(a=this.combineWhere(a,{[r.column]:r.parentId}));let d=(await K(this.storage.get({resource:c,where:a,sort:this.storageSortFor(e),limit:s,include:o}))).map(y=>({row:y,value:R(y)})).filter(y=>{var p;return !!((p=y.value)!=null&&p.id)}),u=new Set(d.map(y=>y.value.id));for(let y of t.ids())u.has(y)||(t.remove(y),this.emitScopeOut(e,y,n.meta));for(let{row:y,value:p}of d){let f=this.sortKeyFor(e,p);if(t.has(p.id)){t.remove(p.id),t.insert({id:p.id,sortKey:f});continue}let m=t.insert({id:p.id,sortKey:f});if(!m.inserted)continue;this.graph.setMatched(p.id,e.hash),this.graph.ingest(c,p);let h=this.stripPayloadRelations({...(y==null?void 0:y.value)??{}},o);delete h.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:c,resourceId:p.id,payload:h,meta:n.meta},"windowed relational promotion INSERT"),m.evicted&&this.emitScopeOut(e,m.evicted.id,n.meta);}}sortKeysEqual(e,t){if(!e||e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return false;return true}async reconcileDemotion(e,t,n,r,s,c){t.remove(n);let o=e.queryStep.query.resource,a=this.windowReadWhere(e,t,c),l=this.sortRelationInclude(e),d=await K(this.storage.get({resource:o,where:a,sort:this.storageSortFor(e),limit:2,include:l})),u,y;for(let f of d){let m=R(f);if(!(!(m!=null&&m.id)||m.id===n||t.has(m.id))){u=m,y=f;break}}if(!u){t.insert({id:n,sortKey:r}),this.emitToSubscribers(e,s,"windowed UPDATE");return}if(t.insert({id:u.id,sortKey:this.sortKeyFor(e,u)}),t.insert({id:n,sortKey:r}).inserted){this.emitToSubscribers(e,s,"windowed UPDATE");return}this.graph.setMatched(u.id,e.hash);let p=this.stripPayloadRelations({...(y==null?void 0:y.value)??{}},l);delete p.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:o,resourceId:u.id,payload:p,meta:s.meta},"windowed demotion backfill INSERT"),this.emitScopeOut(e,n,s.meta);}fullInsertDelta(e,t,n){let r={...(n==null?void 0:n.value)??{}};return delete r.id,{type:"SYNC",op:"INSERT",resource:e.queryStep.query.resource,resourceId:t.resourceId,payload:r,meta:t.meta}}async backfillWindow(e,t,n,r){let s=t.backfillCount;if(s<=0)return;let c=e.queryStep.query.resource,o=this.windowReadWhere(e,t,r),a=this.sortRelationInclude(e),l=await K(this.storage.get({resource:c,where:o,sort:this.storageSortFor(e),limit:s,include:a}));for(let d of l){let u=R(d);if(!(u!=null&&u.id)||t.has(u.id))continue;t.insert({id:u.id,sortKey:this.sortKeyFor(e,u)}),this.graph.setMatched(u.id,e.hash);let y=this.stripPayloadRelations({...(d==null?void 0:d.value)??{}},a);delete y.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:c,resourceId:u.id,payload:y,meta:n},"windowed backfill INSERT");}}buildCursorWhere(e,t){if(!t)return;let n=[...e.queryStep.query.sort??[],{key:"id",direction:"asc"}],r=[...t.sortKey,t.id],s=[];for(let c=0;c<n.length;c++){let o=[];for(let l=0;l<c;l++)o.push(this.cursorCond(n[l].key,r[l]));let a=n[c].direction==="desc"?"$lt":"$gt";o.push(this.cursorCond(n[c].key,{[a]:r[c]})),s.push(o.length===1?o[0]:{$and:o});}return s.length===1?s[0]:{$or:s}}cursorCond(e,t){let n=e.indexOf(".");return n===-1?{[e]:t}:{[e.slice(0,n)]:{[e.slice(n+1)]:t}}}windowReadWhere(e,t,n){let r=e.queryStep.query.where;return n&&(r=this.combineWhere(r,{[n.column]:n.parentId})),this.combineWhere(r,this.buildCursorWhere(e,t.boundary()))}combineWhere(e,t){return t?!e||Object.keys(e).length===0?t:{$and:[e,t]}:e}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 c=this.buildIncludeFromChildQueries(r);n[s.relationName]=Object.keys(c).length>0?c:true;}return n}sendInsertsForTree(e,t,n,r){var o,a;let s=(a=(o=t==null?void 0:t.value)==null?void 0:o.id)==null?void 0:a.value;if(!s)return;let c={op:"INSERT",resource:n,resourceId:s,type:"SYNC",payload:t.value,meta:r};for(let l of Array.from(e.subscriptions))try{l(c);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:s,stepPath:e.queryStep.stepPath.join(".")});}this.graph.setMatched(s,e.hash);for(let l of Array.from(e.childQueries)){let d=this.queryNodes.get(l);if(!d||!d.relationName)continue;let u=d.relationName,y=d.queryStep.query.resource,p=t.value[u];if(!p)continue;let f=p.value;if(Array.isArray(f))for(let m of f)this.sendInsertsForTree(d,m,y,r);else f&&typeof f=="object"&&this.sendInsertsForTree(d,f,y,r);}}handleMutation(e,t){if(e.op==="INSERT"){if(this.graph.has(e.resourceId))return;let n=R(t);if(!n)return;this.graph.applyWrite(e.resource,e.resourceId,n),this.getMatchingQueries(e,n).then(async r=>{try{for(let s of r){let c=this.queryNodes.get(s);if(!c)continue;if(c.windowIndex){let a=await this.resolveSortRelations(c,e.resourceId,n);this.handleWindowedInsert(c,c.windowIndex,e,a);continue}let o=this.includeForeignColumn(c);if(o){let a=n[o];if(a!=null){let l=await this.resolveSortRelations(c,e.resourceId,n);this.handleWindowedInsert(c,this.ensureParentWindow(c,a),e,l);}continue}this.graph.setMatched(e.resourceId,s);for(let a of Array.from(c.subscriptions))try{a(e);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:l,queryHash:c.hash,resource:e.resource,resourceId:e.resourceId,stepPath:c.queryStep.stepPath.join(".")});}}}catch(s){this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:s,resource:e.resource,resourceId:e.resourceId});}},r=>{this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:r,resource:e.resource,resourceId:e.resourceId});});return}if(e.op==="UPDATE"){let n=R(t);if(!n)return;let r=new Set(this.graph.matchedQueriesOf(e.resourceId));this.graph.applyWrite(e.resource,e.resourceId,n,e.payload),this.handleRelationalSortFanout(e,n).catch(s=>{this.logger.error("[QueryEngine] Error during relational sort fan-out",{error:s,resource:e.resource,resourceId:e.resourceId});}),this.getMatchingQueries(e,n).then(async s=>{let c=new Set(s),o=new Set;for(let u of Array.from(this.queryNodes.values()))u.queryStep.query.resource===e.resource&&(u.windowIndex?(o.add(u.hash),await this.handleWindowedUpdate(u,e,t,n,c.has(u.hash))):this.isWindowedIncludeNode(u)&&(o.add(u.hash),await this.handleWindowedIncludeUpdate(u,e,t,n,c.has(u.hash))));let a=[],l=[],d=[];for(let u of s)o.has(u)||(r.has(u)?d.push(u):a.push(u));for(let u of Array.from(r))o.has(u)||c.has(u)||l.push(u);for(let u of a)this.graph.setMatched(e.resourceId,u);for(let u of l)this.graph.clearMatched(e.resourceId,u);for(let u of [...l,...d]){let y=this.queryNodes.get(u);if(y)for(let p of Array.from(y.subscriptions))try{p(e);}catch(f){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:f,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(a.length>0)for(let u of a){let y=this.queryNodes.get(u);if(!y)continue;let p=this.buildIncludeFromChildQueries(u);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(p).length>0?p:void 0}).then(f=>{!f||f.length===0||this.sendInsertsForTree(y,f[0],e.resource,e.meta);});}});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?K([]):Promise.all(n.map(async r=>{let s=r.queryStep.query.where,c=r.queryStep.query.resource,o=e.resourceId;if(!this.graph.has(o))return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,p=y==null?void 0:y.queryStep.query.resource,f=p?this.graph.reference(o,p,r.relationName):void 0;if(!f)return {hash:r.hash,matches:false};if(!y||!this.graph.matches(f,y.hash))return {hash:r.hash,matches:false}}if(!s)return {hash:r.hash,matches:true};let a=be(s,c,this.schema),l=Object.keys(a).length>0;if(!l&&t!==void 0)return {hash:r.hash,matches:D(t,s)};let d=await this.storage.get({resource:c,where:{id:o},include:l?a:void 0});if(!d||d.length===0)return {hash:r.hash,matches:false};let u=R(d[0]);return u?{hash:r.hash,matches:D(u,s)}:{hash:r.hash,matches:false}})).then(r=>r.filter(s=>s.matches).map(s=>s.hash))}};var br=i=>i,qt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],$t=i=>i.length===1?i[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let s of i){let c=await s({...e,value:n,rawValue:t});c&&(t=c,n=R(t),n.id=e.value.id,r=true);}return r?t:void 0}),Qt=i=>i.length===1?i[0]:(async e=>{for(let t of i)await t(e);}),Ce=i=>{let e=i.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of qt){let r=e.map(s=>s[n]).filter(s=>s!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=Qt(r):t[n]=$t(r));}return t},Ir=(...i)=>{let e={},t=new Set;for(let n of i)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=i.map(c=>c[n]),s=Ce(r);s&&(e[n]=s);}return e};var tt=Be(Le());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(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()});var Me=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()})),Xt=Me.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),en=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),Ye=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),X=en.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:Ye}),Ae=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("SYNC"),resource:zod.z.string(),resourceId:zod.z.string(),op:zod.z.enum(["INSERT","UPDATE","DELETE"]),payload:Xt,meta:Ye}),Ee=(i,e)=>{i.op==="DELETE"&&Object.keys(i.payload).length>0&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"DELETE delta payload must be empty"});};Ae.superRefine(Ee);var Xe=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var et=X.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:X.shape.meta});var Oe=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(Oe);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=Oe(n);return e}return i},nt=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?tt.default.parse(r.cookie):{}},c=new URL(t.url),o=c.pathname.split("/"),a=c.searchParams,l=Oe(tn__default.default.parse(a.toString())),d=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:s.headers,cookies:s.cookies,queryParams:l}))??{};if(t.method==="POST")try{let u=o[o.length-1],y=o[o.length-2];if(y==="query"){if(o.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let x=o[o.length-3],C=t.body?await t.json():{};if(!x||x.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let E=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:x,procedure:u,input:C.input,context:d,queryParams:l}});return Response.json(E)}let p=y,f=t.body?await t.json():{},{success:m,data:h,error:T}=et.safeParse(f);if(!m)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:T},{status:400});let S=h,w=await i.handleMutation({req:{...s,type:"MUTATE",resource:p,input:S.payload,context:d,resourceId:S.resourceId,procedure:u,queryParams:{},meta:S.meta}});return Response.json(w)}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 it=Be(Le());var N=zod.z.string(),je=Xe,nn=zod.z.object({id:N,type:zod.z.literal("SUBSCRIBE")}).and(je),rn=zod.z.object({id:N,type:zod.z.literal("UNSUBSCRIBE")}).and(je),sn=zod.z.object({id:N,type:zod.z.literal("QUERY")}).and(je),on=zod.z.object({id:N,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),an=X.extend({id:N}),cn=an,rt=zod.z.union([nn,sn,on,cn,rn]),ln=zod.z.object({id:N,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),un=zod.z.object({id:N,type:zod.z.literal("REPLY"),data:zod.z.any()}),dn=Ae.extend({id:N}).superRefine(Ee);zod.z.union([ln,un,dn]);zod.z.object({resource:zod.z.string(),data:zod.z.array(Me)});var st=i=>{let e={},t=i.logger;return (n,r)=>{var u;let s=y=>{n.send(JSON.stringify(y));},c=pe(),o=new Map,a={headers:r.headers,cookies:typeof r.headers.cookie=="string"?it.default.parse(r.headers.cookie):{}},l=tn.parse(r.url.split("?")[1]),d=(u=i.contextProvider)==null?void 0:u.call(i,{transport:"WEBSOCKET",headers:a.headers,cookies:a.cookies,queryParams:l});e[c]=n,t.info("Client connected:",c),n.on("message",async y=>{try{t.debug("Message received from the client:",y);let p=rt.parse(JSON.parse(y.toString()));if(p.type==="SUBSCRIBE"||p.type==="QUERY"){let{type:f,id:m,...h}=p,T=f==="SUBSCRIBE";try{let S=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h.resource,procedure:h.procedure,input:h.input,context:await d??{},queryParams:l},subscription:T?w=>{var x;!w.resourceId||!w.payload||!Object.keys(w.payload).length||(x=e[c])==null||x.send(JSON.stringify(w));}:void 0});if(T){if(!S||!S.data||!S.query)throw new Error("Cannot subscribe to a one-shot query: the procedure must return a query builder (a Tracked Query), not a computed value");S.unsubscribe&&o.set(H(h),S.unsubscribe),s({id:m,type:"REPLY",data:{resource:S.query.resource,data:(S.data??[]).map(w=>w.value)}});}else s({id:m,type:"REPLY",data:S});}catch(S){s({id:m,type:"REJECT",resource:h.resource,message:S.message}),t.error("Error handling query from the client:",S);}}else if(p.type==="UNSUBSCRIBE"){let{type:f,id:m,...h}=p,T=o.get(H(h));T&&(T(),o.delete(H(h)));}else if(p.type==="CUSTOM_QUERY"){let{resource:f,procedure:m,input:h,id:T}=p;t.debug("Received custom query from client:",p);try{let S=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:f,procedure:m,input:h,context:await d??{},queryParams:l}});s({id:T,type:"REPLY",data:S});}catch(S){s({id:T,type:"REJECT",resource:f,message:S.message}),t.error("Error handling custom query from the client:",S);}}else if(p.type==="MUTATE"){let{resource:f}=p;t.debug("Received mutation from client:",p);try{let m=await i.handleMutation({req:{...a,type:"MUTATE",resource:f,input:p.payload,context:{messageId:p.id,...await d??{}},resourceId:p.resourceId,procedure:p.procedure,queryParams:l,meta:p.meta}});s({id:p.id,type:"REPLY",data:m});}catch(m){s({id:p.id,type:"REJECT",resource:f,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(p){t.error("Error handling message from the client:",p);}}),n.on("close",()=>{t.info("Connection closed",c),delete e[c];for(let y of Array.from(o.values()))y();});}};function ot(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 Zr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,st(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{nt(e)(ot(n)).then(c=>c.json().then(o=>r.status(c.status).send(o)));});};var ee=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,s,c,o,a){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=s,this._single=c,this._sort=o,this._shouldAwait=a,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new i(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new i(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new i(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 i(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new i(this._collection,this._client,this._where,this._include,this._limit,this._single,n,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(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,n){return new i(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var pn=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Pe=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>pn(n)?R(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function te(i,e,t){let n=new Pe(i),r=c=>{let o=ee._init(c,n,true);return Object.assign(Object.create(o),{insert:async l=>{let d=i._getTimestamp(),u=await i.rawInsert(c.name,l.id,{value:Object.fromEntries(Object.entries(l).map(([y,p])=>[y,{value:p,_meta:{timestamp:d}}]))},void 0,t);return R(u.data)},update:async(l,d)=>{let u=i._getTimestamp(),{id:y,...p}=d,f=await i.rawUpdate(c.name,l,{value:Object.fromEntries(Object.entries(p).map(([T,S])=>[T,{value:S,_meta:{timestamp:u}}]))},void 0,t),m=R(f.data),h={};for(let T of Object.keys(p))T in m&&(h[T]=m[T]);return h}})},s={get(c,o){if(o==="findOne")return i.findOne.bind(i);if(o==="find")return i.find.bind(i);if(o==="insert")return (a,l)=>{let d=i._getTimestamp();return i.rawInsert(a.name,l.id,{value:Object.fromEntries(Object.entries(l).map(([u,y])=>[u,{value:y,_meta:{timestamp:d}}]))},void 0,t).then(u=>R(u.data))};if(o==="update")return (a,l,d)=>{let u=i._getTimestamp(),{id:y,...p}=d;return i.rawUpdate(a.name,l,{value:Object.fromEntries(Object.entries(p).map(([f,m])=>[f,{value:m,_meta:{timestamp:u}}]))},void 0,t).then(f=>{let m=R(f.data),h={};for(let T of Object.keys(p))T in m&&(h[T]=m[T]);return h})};if(o==="transaction")return async a=>i.transaction(async({trx:l,commit:d,rollback:u})=>{let y=te(l,e,t);return a({trx:y,commit:d,rollback:u})});if(o in e){let a=e[o];return r(a)}}};return new Proxy({},s)}var Ve=class i{routes;schema;constructor(e){this.routes=e.routes,this.schema=e.schema;}static create(e){return new i(e)}},si=i=>Ve.create(i),fn=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),mn=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),De=class{middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:n})=>{var c;let r=((c=e.meta)==null?void 0:c.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(r);return await this.wrapInMiddlewares(async o=>{if(!o.procedure)throw new Error("Procedure is required for mutations");let a=this.customMutations[o.procedure];if(a){let l=a.inputValidator["~standard"].validate(o.input),d=l instanceof Promise?await l:l;if(d.issues){let y=d.issues.map(p=>{var m;let f=(m=p.path)==null?void 0:m.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return f?`${f}: ${p.message}`:p.message}).join(", ");throw new Error(`Validation failed: ${y}`)}o.input=d.value;let u=te(s,n,o.context);return a.handler({req:o,db:u})}throw new Error(`Unknown procedure: ${o.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{let s=this.customQueries[r.procedure];if(!s)throw new Error(`Unknown query procedure: ${r.procedure}`);let c=s.inputValidator["~standard"].validate(r.input),o=c instanceof Promise?await c:c;if(o.issues){let l=o.issues.map(d=>{var y;let u=(y=d.path)==null?void 0:y.map(p=>typeof p=="object"&&"key"in p?String(p.key):String(p)).join(".");return u?`${u}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${l}`)}r.input=o.value;let a=te(t,n,r.context);return s.handler({req:r,db:a})})(e);wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>s=>r({req:s,next:n}),e)(t)}};function oi(i){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>i({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var ke=class i{middlewares;constructor(e=[]){this.middlewares=e;}withProcedures(e){let t=e({mutation:mn,query:fn}),n={},r={};for(let[s,c]of Object.entries(t))c._type==="mutation"?n[s]=c:r[s]=c;return new De(n,r).use(...this.middlewares)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new i([...this.middlewares,...t])}static create(){return new i}},ai=ke.create;var ne=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([s,c])=>[s,{value:c,_meta:{timestamp:n}}]))});return R(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:s,...c}=n,o=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(c).map(([d,u])=>[d,{value:u,_meta:{timestamp:r}}]))}),a=R(o.data),l={};for(let d of Object.keys(c))d in a&&(l[d]=a[d]);return l}};var vn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function k(i){var r,s,c;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((c=(s=t.constructor)==null?void 0:s.name)==null?void 0:c.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function ct(i){let e=k(i);return vn[e]}var wn="42701";function re(i){var t;if(i.code===wn)return true;let e=((t=i.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function Ne(i,e){let{type:t,enumValues:n,enumName:r}=i;if(n&&n.length>0)return e==="postgres"&&r?r:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function bn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let s of Object.values(e))for(let c of Object.values(s.fields)){let o=c.getStorageFieldType();o.enumValues&&o.enumName&&r.set(o.enumName,{name:o.enumName,values:o.enumValues});}for(let s of Array.from(r.values())){let{name:c,values:o}=s;try{let a=o.map(l=>`'${l}'`).join(", ");await kysely.sql`
2
2
  DO $$ BEGIN
3
3
  CREATE TYPE ${kysely.sql.id(c)} AS ENUM (${kysely.sql.raw(a)});
4
4
  EXCEPTION
5
5
  WHEN duplicate_object THEN null;
6
6
  END $$;
7
- `.execute(i);}catch(a){n==null||n.warn("Could not create enum type",c,a);}}}function ne(i,e){return i.some(t=>t.name===e)}function Sn(i,e){return (i==null?void 0:i.columns.some(t=>t.name===e))??false}function Ve(i,e){let[t]=e.split(".");return ne(i,t)}function Pe(i,e,t,n=false){let r=i;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&Ve(t,e.references)&&(r=r.references(e.references)),r}function vn(i,e,t,n,r){let o=[];for(let[c,s]of Object.entries(i.fields)){let a=e==null?void 0:e.columns.find(u=>u.name===c),l=s.getStorageFieldType();a?(a.dataType,l.type):(o.push({name:c,storageFieldType:l}),l.references&&!Ve(t,l.references)&&n.push({tableName:r,columnName:c,references:l.references}));}return o}function st(i,e){return e==="postgres"&&!!i.enumValues&&i.enumValues.length>0&&!!i.enumName}async function wn(i,e,t,n,r,o){if(t.length===0)return;let c=i.schema.createTable(e);for(let{name:s,storageFieldType:a}of t)if(st(a,r))c=c.addColumn(s,kysely.sql.raw(a.enumName),l=>Pe(l,a,n));else {let l=Ne(a,r);c=c.addColumn(s,l,u=>Pe(u,a,n));}await c.execute().catch(s=>{if(!te(s))throw o==null||o.error("Error creating table",e,s),s});}async function bn(i,e,t,n,r,o,c){for(let{name:s,storageFieldType:a}of t){let l=a.references?Ve(n,a.references):false,u=st(a,o)?kysely.sql.raw(a.enumName):Ne(a,o);await i.schema.alterTable(e).addColumn(s,u,d=>Pe(d,a,n,!l)).execute().catch(d=>{if(!te(d))throw c==null||c.error("Error adding column",s,d),d}),a.references&&!l&&!r.some(d=>d.tableName===e&&d.columnName===s)&&r.push({tableName:e,columnName:s,references:a.references}),a.index&&await i.schema.createIndex(`${e}_${s}_index`).on(e).column(s).execute().catch(()=>{});}}async function In(i,e,t,n,r,o){let c=`${e}_meta`,s=[];for(let[a,l]of Object.entries(t.fields)){let u=l.getStorageFieldType();Sn(n,a)||s.push({name:a,storageFieldType:u});}if(!n&&s.length>0){let a=i.schema.createTable(c);for(let{name:l,storageFieldType:u}of s)a=a.addColumn(l,"varchar",d=>{let p=d;return u.primary&&(p=p.primaryKey(),ne(r,e)&&(p=p.references(`${e}.${l}`))),p});await a.execute().catch(l=>{if(!te(l))throw o==null||o.error("Error creating meta table",c,l),l});}else if(n)for(let{name:a,storageFieldType:l}of s)await i.schema.alterTable(c).addColumn(a,"varchar",u=>{let d=u;return l.primary&&(d=d.primaryKey(),ne(r,e)&&(d=d.references(`${e}.${a}`))),d}).execute().catch(u=>{if(!te(u))throw o==null||o.error("Error adding meta column",a,u),u});}async function ot(i,e,t,n,r){let[o,c]=n.split("."),s=`${e}_${t}_fk`;try{await kysely.sql`
7
+ `.execute(i);}catch(a){n==null||n.warn("Could not create enum type",c,a);}}}function ie(i,e){return i.some(t=>t.name===e)}function In(i,e){return (i==null?void 0:i.columns.some(t=>t.name===e))??false}function _e(i,e){let[t]=e.split(".");return ie(i,t)}function Fe(i,e,t,n=false){let r=i;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&_e(t,e.references)&&(r=r.references(e.references)),r}function Cn(i,e,t,n,r){let s=[];for(let[c,o]of Object.entries(i.fields)){let a=e==null?void 0:e.columns.find(d=>d.name===c),l=o.getStorageFieldType();a?(a.dataType,l.type):(s.push({name:c,storageFieldType:l}),l.references&&!_e(t,l.references)&&n.push({tableName:r,columnName:c,references:l.references}));}return s}function lt(i,e){return e==="postgres"&&!!i.enumValues&&i.enumValues.length>0&&!!i.enumName}async function Ln(i,e,t,n,r,s){if(t.length===0)return;let c=i.schema.createTable(e);for(let{name:o,storageFieldType:a}of t)if(lt(a,r))c=c.addColumn(o,kysely.sql.raw(a.enumName),l=>Fe(l,a,n));else {let l=Ne(a,r);c=c.addColumn(o,l,d=>Fe(d,a,n));}await c.execute().catch(o=>{if(!re(o))throw s==null||s.error("Error creating table",e,o),o});}async function Mn(i,e,t,n,r,s,c){for(let{name:o,storageFieldType:a}of t){let l=a.references?_e(n,a.references):false,d=lt(a,s)?kysely.sql.raw(a.enumName):Ne(a,s);await i.schema.alterTable(e).addColumn(o,d,u=>Fe(u,a,n,!l)).execute().catch(u=>{if(!re(u))throw c==null||c.error("Error adding column",o,u),u}),a.references&&!l&&!r.some(u=>u.tableName===e&&u.columnName===o)&&r.push({tableName:e,columnName:o,references:a.references}),a.index&&await i.schema.createIndex(`${e}_${o}_index`).on(e).column(o).execute().catch(()=>{});}}async function An(i,e,t,n,r,s){let c=`${e}_meta`,o=[];for(let[a,l]of Object.entries(t.fields)){let d=l.getStorageFieldType();In(n,a)||o.push({name:a,storageFieldType:d});}if(!n&&o.length>0){let a=i.schema.createTable(c);for(let{name:l,storageFieldType:d}of o)a=a.addColumn(l,"varchar",u=>{let y=u;return d.primary&&(y=y.primaryKey(),ie(r,e)&&(y=y.references(`${e}.${l}`))),y});await a.execute().catch(l=>{if(!re(l))throw s==null||s.error("Error creating meta table",c,l),l});}else if(n)for(let{name:a,storageFieldType:l}of o)await i.schema.alterTable(c).addColumn(a,"varchar",d=>{let u=d;return l.primary&&(u=u.primaryKey(),ie(r,e)&&(u=u.references(`${e}.${a}`))),u}).execute().catch(d=>{if(!re(d))throw s==null||s.error("Error adding meta column",a,d),d});}async function ut(i,e,t,n,r){let[s,c]=n.split("."),o=`${e}_${t}_fk`;try{await kysely.sql`
8
8
  ALTER TABLE ${kysely.sql.id(e)}
9
- ADD CONSTRAINT ${kysely.sql.id(s)}
9
+ ADD CONSTRAINT ${kysely.sql.id(o)}
10
10
  FOREIGN KEY (${kysely.sql.id(t)})
11
- REFERENCES ${kysely.sql.id(o)} (${kysely.sql.id(c)})
12
- `.execute(i);}catch(a){te(a)||r==null||r.warn("Could not add foreign key constraint",e,t,n,a);}}async function Cn(i,e,t,n){for(let{tableName:r,columnName:o,references:c}of e){let s=t.find(u=>u.name===r),a=s==null?void 0:s.columns.find(u=>u.name===o),[l]=c.split(".");s&&a&&ne(t,l)&&await ot(i,r,o,c,n);}}async function Ln(i,e,t,n){for(let[r,o]of Object.entries(e)){let c=`${r}_meta`,s=t.find(a=>a.name===c);if(s)for(let[a,l]of Object.entries(o.fields)){let u=l.getStorageFieldType(),d=s.columns.find(p=>p.name===a);u.primary&&d&&ne(t,r)&&await ot(i,c,a,`${r}.${a}`,n);}}}async function at(i,e,t){let n=k(i),r=await i.introspection.getTables(),o=[];await Rn(i,e,n,t);for(let[s,a]of Object.entries(e)){let l=r.find(p=>p.name===s),u=r.find(p=>p.name===`${s}_meta`),d=vn(a,l,r,o,s);if(l)for(let[p,y]of Object.entries(a.fields)){let f=l.columns.find(T=>T.name===p),m=y.getStorageFieldType(),h=Ne(m,n);f&&f.dataType!==h&&(t==null||t.warn("Column type mismatch:",p,"expected to have type:",h,"but has type:",f.dataType));}!l&&d.length>0?await wn(i,s,d,r,n,t):l&&await bn(i,s,d,r,o,n,t),await In(i,s,a,u,r,t);}let c=await i.introspection.getTables();await Cn(i,o,c,t),await Ln(i,e,c,t);}function fe(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 o=n.$or,c=n.$and;return (o?t.or:t.and)(o?n.$or.map(s=>fe(i,e,t,s)):c?n.$and.map(s=>fe(i,e,t,s)):Object.entries(n).map(([s,a])=>{var l,u;if(r.fields[s])return (a==null?void 0:a.$eq)!==void 0?t(`${e}.${s}`,a.$eq===null?"is":"=",a.$eq):(a==null?void 0:a.$in)!==void 0?t(`${e}.${s}`,"in",a.$in):(a==null?void 0:a.$not)!==void 0?((l=a==null?void 0:a.$not)==null?void 0:l.$in)!==void 0?t(`${e}.${s}`,"not in",a.$not.$in):((u=a==null?void 0:a.$not)==null?void 0:u.$eq)!==void 0?t(`${e}.${s}`,a.$not.$eq===null?"is not":"!=",a.$not.$eq):t(`${e}.${s}`,a.$not===null?"is not":"!=",a.$not):(a==null?void 0:a.$gt)!==void 0?t(`${e}.${s}`,">",a.$gt):(a==null?void 0:a.$gte)!==void 0?t(`${e}.${s}`,">=",a.$gte):(a==null?void 0:a.$lt)!==void 0?t(`${e}.${s}`,"<",a.$lt):(a==null?void 0:a.$lte)!==void 0?t(`${e}.${s}`,"<=",a.$lte):t(`${e}.${s}`,a===null?"is":"=",a);if(r.relations[s]){let d=r.relations[s],p=d.entity.name;return d.type==="many"?t.exists(he(i,p,t.selectFrom(p).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),a)):fe(i,p,t,a)}return null}).filter(Boolean))}function me(i,e,t,n,r=new Set){let o=i[e];if(!o)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let c of n.$and)t=me(i,e,t,c,r);return t}else if(n.$or){for(let c of n.$or)t=me(i,e,t,c,r);return t}for(let[c,s]of Object.entries(n)){if(!o.relations[c])continue;let a=o.relations[c],l=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,d=a.type==="one"?a.relationalColumn:"id";r.has(l)||(r.add(l),t=t.leftJoin(l,`${l}.${u}`,`${e}.${d}`)),s instanceof Object&&!Array.isArray(s)&&s!==null&&(t=me(i,l,t,s,r));}return t}function he(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=me(i,e,t,n),t.where(r=>fe(i,e,r,n)))}function Mn(i,e,t,n,r){let o=k(r),c=e[t];if(o==="sqlite"&&(c!=null&&c.fields)){let s=Object.keys(c.fields),a=i.selectFrom(n);for(let l of s)a=a.select(`${n}.${l}`);return a}return i.selectFrom(n).selectAll(n)}function An(i,e,t,n,r){let o=k(r),c=e[t];if(o==="sqlite"&&(c!=null&&c.fields)){let s=Object.keys(c.fields),a=i.selectFrom(n);for(let l of s)a=a.select(`${n}.${l}`);return a}return i.selectFrom(n).selectAll(n)}function ke(i,e,t,n){var r,o;for(let c of n){let s=c.key.indexOf(".");if(s!==-1){let a=c.key.slice(0,s),l=c.key.slice(s+1),u=(o=(r=i==null?void 0:i[e])==null?void 0:r.relations)==null?void 0:o[a];if((u==null?void 0:u.type)==="one"&&u.relationalColumn){let d=u.entity.name,p=String(u.relationalColumn);t=t.orderBy(y=>y.selectFrom(d).select(`${d}.${l}`).whereRef(`${d}.id`,"=",`${e}.${p}`),c.direction);continue}if(u)throw new Error(`Relational sort on "${c.key}" is only supported for "one" relations with a relationalColumn`)}t=t.orderBy(c.key,c.direction);}return t}function Te(i,e,t,n,r,o){if(!n)return t;if(!i)throw new Error("Schema not initialized");let c=i[e];if(!c)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:s,jsonArrayFrom:a}=r;for(let l of Object.keys(n)){if(!c.relations[l])throw new Error(`Relation ${l} not found in resource ${e}`);let u=c.relations[l],d=u.entity.name,p=n[l],y=u.type==="one"?"id":u.foreignColumn,f=u.type==="one"?u.relationalColumn:"id",m=u.type==="one"?s:a,h=H(p)?p:null,T=h?h.include:p&&typeof p=="object"?p:void 0;t=t.select(R=>{let w=`${d}_meta`,x=An(R,i,d,d,o).whereRef(`${d}.${y}`,"=",`${e}.${f}`).select(C=>s(Mn(C,i,d,w,o).whereRef(`${w}.id`,"=",`${d}.id`)).as("_meta"));return h!=null&&h.where&&(x=he(i,d,x,h.where)),h!=null&&h.orderBy&&(x=ke(i,d,x,h.orderBy)),(h==null?void 0:h.limit)!==void 0&&(x=x.limit(h.limit)),T&&Object.keys(T).length>0&&(x=Te(i,d,x,T,r,o)),m(x).as(l)});}return t}var De=class i extends ee{db;dialectHelpers;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.dialectHelpers=it(this.db),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){this.schema=e,this.logger=t,this.server=n,await at(this.db,e,t);}selectMetaColumns(e,t,n){var c;let r=k(this.db),o=(c=this.schema)==null?void 0:c[t];if(r==="sqlite"&&(o!=null&&o.fields)){let s=Object.keys(o.fields),a=e.selectFrom(n);for(let l of s)a=a.select(`${n}.${l}`);return a}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,o=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(a=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(a,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));o=Te(this.schema,e,o,n,this.dialectHelpers,this.db);let c=await o.executeTakeFirst();if(!c)return;let s=this.parseRelationalJsonStrings(c,e);return this.convertToMaterializedLiveType(s,e)}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:o,sort:c}=e,s=`${t}_meta`,a=this.db.selectFrom(t).selectAll(t).select(u=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(u,t,s).whereRef(`${s}.id`,"=",`${t}.id`)).as("_meta"));a=he(this.schema,t,a,n),a=Te(this.schema,t,a,r,this.dialectHelpers,this.db),o!==void 0&&(a=a.limit(o)),c!==void 0&&(a=ke(this.schema,t,a,c));let l=await a.execute();return l.length===0?[]:l.map(u=>{let d=this.parseRelationalJsonStrings(u,t);return this.convertToMaterializedLiveType(d,t)})}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,o){var m,h,T,R,w,x,C,O,_,Q,z;let c=(m=this.server)==null?void 0:m.getHooks(e),s=(h=this.schema)==null?void 0:h[e],[a,l]=((T=s==null?void 0:s.mergeMutation)==null?void 0:T.call(s,"set",n.value,void 0))??[n,n.value];if(!l)return {data:n,acceptedValues:null};let u=a,d={...u,value:{...u.value,id:{value:t}}};if(c!=null&&c.beforeInsert){let L=S(d);L.id=t;let v=await c.beforeInsert({ctx:o,value:L,rawValue:d,db:this});v&&(u=v);}let p={},y={};for(let[L,v]of Object.entries(u.value)){let M=(R=v._meta)==null?void 0:R.timestamp;if(!M)continue;let I=(x=(w=s==null?void 0:s.fields[L])==null?void 0:w.getStorageFieldType)==null?void 0:x.call(w);(I==null?void 0:I.type)==="jsonb"||(I==null?void 0:I.type)==="json"?p[L]=JSON.stringify(v.value):p[L]=v.value,y[L]=M;}await this.db.insertInto(e).values({...p,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute(),(O=(C=this.logger)==null?void 0:C.debug)==null||O.call(C,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(o==null?void 0:o.messageId)??"(none)",hasContext:!!o,contextKeys:o?Object.keys(o):[]});let f=this.buildMutation(e,t,"INSERT",u,r,o==null?void 0:o.messageId);if(f&&((z=(_=this.logger)==null?void 0:_.debug)==null||z.call(_,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:((Q=f.meta)==null?void 0:Q.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,u)),c!=null&&c.afterInsert){let L={...u,value:{...u.value,id:{value:t}}},v=S(L);v.id=t,await c.afterInsert({ctx:o,value:v,rawValue:L,db:this});}return {data:u,acceptedValues:l}}async rawUpdate(e,t,n,r,o){var h,T,R,w,x,C,O,_,Q,z,L;let c=(h=this.server)==null?void 0:h.getHooks(e),s=(T=this.schema)==null?void 0:T[e],a=await this.rawFindById(e,t),[l,u]=((R=s==null?void 0:s.mergeMutation)==null?void 0:R.call(s,"set",n.value,a))??[n,n.value];if(!u)return {data:n,acceptedValues:null};let d=l,p={...d,value:{...d.value,id:{value:t}}};if(c!=null&&c.beforeUpdate){let v=S(p);v.id=t;let M;if(a){let A={...a,value:{...a.value,id:{value:t}}};M=S(A),M.id=t;}let I=await c.beforeUpdate({ctx:o,value:v,rawValue:p,previousValue:M,previousRawValue:a,db:this});I&&(d=I);}let y={},f={};for(let[v,M]of Object.entries(d.value)){let I=(w=M._meta)==null?void 0:w.timestamp;if(!I)continue;let A=(C=(x=s==null?void 0:s.fields[v])==null?void 0:x.getStorageFieldType)==null?void 0:C.call(x);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?y[v]=JSON.stringify(M.value):y[v]=M.value,f[v]=I;}if(Object.keys(y).length===0)return {data:d,acceptedValues:u};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(v=>v.column("id").doUpdateSet(f)).execute()]),(_=(O=this.logger)==null?void 0:O.debug)==null||_.call(O,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(o==null?void 0:o.messageId)??"(none)",hasContext:!!o,contextKeys:o?Object.keys(o):[]});let m=this.buildMutation(e,t,"UPDATE",d,r,o==null?void 0:o.messageId);if(m){(L=(Q=this.logger)==null?void 0:Q.debug)==null||L.call(Q,"[rawUpdate] Mutation built, tracking",{mutationId:m.id,hasMeta:!!m.meta,originMutationId:((z=m.meta)==null?void 0:z.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let v=await this.rawFindById(e,t);v&&this.trackMutation(m,v);}if(c!=null&&c.afterUpdate){let v=await this.rawFindById(e,t);if(v){let M={...v,value:{...v.value,id:{value:t}}},I=S(M);I.id=t;let A;if(a){let lt={...a,value:{...a.value,id:{value:t}}};A=S(lt),A.id=t;}await c.afterUpdate({ctx:o,value:I,rawValue:M,previousValue:A,previousRawValue:a,db:this});}}return {data:d,acceptedValues:u}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let o=Math.random().toString(36).substring(2,15),c=this.mutationStack,s=[];this.mutationStack=s;let a=await this.db.savepoint(o).execute(),l=false,u=false;try{return await e({trx:this,commit:async()=>{await a.releaseSavepoint(o).execute(),l=!0,c.push(...s);},rollback:async()=>{await a.rollbackToSavepoint(o).execute(),u=!0,s.length=0;}}).then(d=>a.isCommitted||a.isRolledBack||l||u?d:a.releaseSavepoint(o).execute().then(()=>(c.push(...s),d)))}catch(d){throw u||await a.rollbackToSavepoint(o).execute().catch(()=>{}),s.length=0,d}finally{this.mutationStack=c;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let o=new i(r,this.schema,this.logger,this.server);return o.mutationStack=t,await e({trx:o,commit:async()=>{var c,s;await r.commit().execute(),(s=(c=this.logger)==null?void 0:c.debug)==null||s.call(c,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:a})=>{var l;return {id:a.id,resource:a.resource,resourceId:a.resourceId,op:a.op,hasMeta:!!a.meta,originMutationId:((l=a.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(c=>r.isCommitted||r.isRolledBack?c:r.commit().execute().then(()=>{var s,a;return (a=(s=this.logger)==null?void 0:s.debug)==null||a.call(s,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:l})=>{var u;return {id:l.id,resource:l.resource,resourceId:l.resourceId,op:l.op,hasMeta:!!l.meta,originMutationId:((u=l.meta)==null?void 0:u.originMutationId)??"(none)"}})}),this.notifyMutations(t),c}))}catch(o){throw await r.rollback().execute(),t.length=0,o}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var o,c;if(k(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(s=>this.parseRelationalJsonStrings(s,t));let r={};for(let[s,a]of Object.entries(e))if(s==="_meta"&&typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{r[s]=JSON.parse(a);}catch{r[s]=a;}else r[s]=a;else if(this.isRelationalField(t,s))if(typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{let l=JSON.parse(a);if(this.schema){let u=this.schema[t],d=(o=u==null?void 0:u.relations)==null?void 0:o[s];if(d){let p=d.entity.name;r[s]=this.parseRelationalJsonStrings(l,p);}else r[s]=l;}else r[s]=l;}catch{r[s]=a;}else r[s]=a;else if(typeof a=="object"&&a!==null&&!Array.isArray(a))if(this.schema){let l=this.schema[t],u=(c=l==null?void 0:l.relations)==null?void 0:c[s];if(u){let d=u.entity.name;r[s]=this.parseRelationalJsonStrings(a,d);}else r[s]=a;}else r[s]=a;else Array.isArray(a)?r[s]=a.map(l=>{var u,d;if(typeof l=="string")try{let p=JSON.parse(l);if(this.schema){let y=this.schema[t],f=(u=y==null?void 0:y.relations)==null?void 0:u[s];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(p,m)}}return p}catch{return l}if(typeof l=="object"&&l!==null&&this.schema){let p=this.schema[t],y=(d=p==null?void 0:p.relations)==null?void 0:d[s];if(y){let f=y.entity.name;return this.parseRelationalJsonStrings(l,f)}}return l}):r[s]=a;else r[s]=a;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((o,[c,s])=>{var d,p,y,f,m,h,T,R,w;if(c==="_meta")return o;let a=(p=(d=n==null?void 0:n.fields[c])==null?void 0:d.getStorageFieldType)==null?void 0:p.call(d),l=(a==null?void 0:a.type)==="jsonb"||(a==null?void 0:a.type)==="json",u=(n==null?void 0:n.relations)&&c in n.relations;if(c==="id")o[c]={value:s};else if(l)o[c]={value:s,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[c]}};else if(u){let x=n.relations[c].entity,C=(x==null?void 0:x.name)??t;Array.isArray(s)?o[c]={value:s.map(O=>this.convertToMaterializedLiveType(O,C)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[c],relation:true}}:s!==null&&typeof s=="object"?o[c]={...this.convertToMaterializedLiveType(s,C),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[c],relation:true}}:o[c]={value:s,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[c],relation:true}};}else Array.isArray(s)?o[c]={value:s,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[c]}}:typeof s=="object"&&s!==null&&!(s instanceof Date)?o[c]={value:s,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[c]}}:o[c]={value:s,_meta:{timestamp:(w=e==null?void 0:e._meta)==null?void 0:w[c]}};return o},{})}}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",o=typeof t.savepoint=="function",c=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||o&&c}buildMutation(e,t,n,r,o,c){var a;let s={};for(let[l,u]of Object.entries(r.value)){if(l==="id")continue;let d=(a=u._meta)==null?void 0:a.timestamp;d&&(s[l]={value:u.value,_meta:{timestamp:d}});}return Object.keys(s).length===0?null:{id:o??de(),type:"SYNC",resource:e,resourceId:t,op:n,payload:s,meta:c?{originMutationId:c}:void 0}}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:o}of n)this.server.notifySubscribers(r,o);}}};var Fe=class i{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var t;if(this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=$e({level:e.logLevel??D.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),e.hooks)for(let[n,r]of Object.entries(e.hooks)){let o=ve([r]);o&&this.hooksRegistry.set(n,o);}this.initPromise=this.storage.init(this.schema,this.logger,this).catch(n=>{this.initError=n;}),this.contextProvider=e.contextProvider,this.queryEngine=new ye({storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleMutation(e){return await this.ensureInitialized(),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)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async p=>{let y=this.router.routes[p.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:p,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:r,cookies:o,queryParams:c,context:s}=e.req,a={headers:r,cookies:o,queryParams:c,context:s},l=t.buildQueryRequest(),u=e.subscription?this.queryEngine.subscribe(l,p=>{var y;(y=e.subscription)==null||y.call(e,p);},a):void 0,d=await this.queryEngine.get(l,{context:a});return e.subscription?{data:d,unsubscribe:u,query:l}:d.map(p=>S(p))}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)=>o=>r({req:o,next:n}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},Ai=Fe.create;exports.QueryBuilder=Y;exports.Route=je;exports.RouteFactory=Ee;exports.Router=Oe;exports.SQLStorage=De;exports.Server=Fe;exports.Storage=ee;exports.createMiddleware=Zr;exports.createServerDB=X;exports.defineHooks=mr;exports.expressAdapter=qr;exports.mergeEntityHooks=ve;exports.mergeHooks=hr;exports.routeFactory=Yr;exports.router=Gr;exports.server=Ai;
11
+ REFERENCES ${kysely.sql.id(s)} (${kysely.sql.id(c)})
12
+ `.execute(i);}catch(a){re(a)||r==null||r.warn("Could not add foreign key constraint",e,t,n,a);}}async function En(i,e,t,n){for(let{tableName:r,columnName:s,references:c}of e){let o=t.find(d=>d.name===r),a=o==null?void 0:o.columns.find(d=>d.name===s),[l]=c.split(".");o&&a&&ie(t,l)&&await ut(i,r,s,c,n);}}async function On(i,e,t,n){for(let[r,s]of Object.entries(e)){let c=`${r}_meta`,o=t.find(a=>a.name===c);if(o)for(let[a,l]of Object.entries(s.fields)){let d=l.getStorageFieldType(),u=o.columns.find(y=>y.name===a);d.primary&&u&&ie(t,r)&&await ut(i,c,a,`${r}.${a}`,n);}}}async function dt(i,e,t){let n=k(i),r=await i.introspection.getTables(),s=[];await bn(i,e,n,t);for(let[o,a]of Object.entries(e)){let l=r.find(y=>y.name===o),d=r.find(y=>y.name===`${o}_meta`),u=Cn(a,l,r,s,o);if(l)for(let[y,p]of Object.entries(a.fields)){let f=l.columns.find(T=>T.name===y),m=p.getStorageFieldType(),h=Ne(m,n);f&&f.dataType!==h&&(t==null||t.warn("Column type mismatch:",y,"expected to have type:",h,"but has type:",f.dataType));}!l&&u.length>0?await Ln(i,o,u,r,n,t):l&&await Mn(i,o,u,r,s,n,t),await An(i,o,a,d,r,t);}let c=await i.introspection.getTables();await En(i,s,c,t),await On(i,e,c,t);}function ge(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,c=n.$and;return (s?t.or:t.and)(s?n.$or.map(o=>ge(i,e,t,o)):c?n.$and.map(o=>ge(i,e,t,o)):Object.entries(n).map(([o,a])=>{var l,d;if(r.fields[o])return (a==null?void 0:a.$eq)!==void 0?t(`${e}.${o}`,a.$eq===null?"is":"=",a.$eq):(a==null?void 0:a.$in)!==void 0?t(`${e}.${o}`,"in",a.$in):(a==null?void 0:a.$not)!==void 0?((l=a==null?void 0:a.$not)==null?void 0:l.$in)!==void 0?t(`${e}.${o}`,"not in",a.$not.$in):((d=a==null?void 0:a.$not)==null?void 0:d.$eq)!==void 0?t(`${e}.${o}`,a.$not.$eq===null?"is not":"!=",a.$not.$eq):t(`${e}.${o}`,a.$not===null?"is not":"!=",a.$not):(a==null?void 0:a.$gt)!==void 0?t(`${e}.${o}`,">",a.$gt):(a==null?void 0:a.$gte)!==void 0?t(`${e}.${o}`,">=",a.$gte):(a==null?void 0:a.$lt)!==void 0?t(`${e}.${o}`,"<",a.$lt):(a==null?void 0:a.$lte)!==void 0?t(`${e}.${o}`,"<=",a.$lte):t(`${e}.${o}`,a===null?"is":"=",a);if(r.relations[o]){let u=r.relations[o],y=u.entity.name;return u.type==="many"?t.exists(Se(i,y,t.selectFrom(y).select("id").whereRef(u.foreignColumn,"=",`${e}.id`),a)):ge(i,y,t,a)}return null}).filter(Boolean))}function xe(i,e,t,n,r=new Set){let s=i[e];if(!s)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let c of n.$and)t=xe(i,e,t,c,r);return t}else if(n.$or){for(let c of n.$or)t=xe(i,e,t,c,r);return t}for(let[c,o]of Object.entries(n)){if(!s.relations[c])continue;let a=s.relations[c],l=a.entity.name,d=a.type==="one"?"id":a.foreignColumn,u=a.type==="one"?a.relationalColumn:"id";r.has(l)||(r.add(l),t=t.leftJoin(l,`${l}.${d}`,`${e}.${u}`)),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=xe(i,l,t,o,r));}return t}function Se(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=xe(i,e,t,n),t.where(r=>ge(i,e,r,n)))}function jn(i,e,t,n,r){let s=k(r),c=e[t];if(s==="sqlite"&&(c!=null&&c.fields)){let o=Object.keys(c.fields),a=i.selectFrom(n);for(let l of o)a=a.select(`${n}.${l}`);return a}return i.selectFrom(n).selectAll(n)}function Pn(i,e,t,n,r){let s=k(r),c=e[t];if(s==="sqlite"&&(c!=null&&c.fields)){let o=Object.keys(c.fields),a=i.selectFrom(n);for(let l of o)a=a.select(`${n}.${l}`);return a}return i.selectFrom(n).selectAll(n)}function qe(i,e,t,n){var r,s;for(let c of n){let o=c.key.indexOf(".");if(o!==-1){let a=c.key.slice(0,o),l=c.key.slice(o+1),d=(s=(r=i==null?void 0:i[e])==null?void 0:r.relations)==null?void 0:s[a];if((d==null?void 0:d.type)==="one"&&d.relationalColumn){let u=d.entity.name,y=String(d.relationalColumn);t=t.orderBy(p=>p.selectFrom(u).select(`${u}.${l}`).whereRef(`${u}.id`,"=",`${e}.${y}`),c.direction);continue}if(d)throw new Error(`Relational sort on "${c.key}" is only supported for "one" relations with a relationalColumn`)}t=t.orderBy(c.key,c.direction);}return t}function Re(i,e,t,n,r,s){if(!n)return t;if(!i)throw new Error("Schema not initialized");let c=i[e];if(!c)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:o,jsonArrayFrom:a}=r;for(let l of Object.keys(n)){if(!c.relations[l])throw new Error(`Relation ${l} not found in resource ${e}`);let d=c.relations[l],u=d.entity.name,y=n[l],p=d.type==="one"?"id":d.foreignColumn,f=d.type==="one"?d.relationalColumn:"id",m=d.type==="one"?o:a,h=z(y)?y:null,T=h?h.include:y&&typeof y=="object"?y:void 0;t=t.select(S=>{let w=`${u}_meta`,x=Pn(S,i,u,u,s).whereRef(`${u}.${p}`,"=",`${e}.${f}`).select(C=>o(jn(C,i,u,w,s).whereRef(`${w}.id`,"=",`${u}.id`)).as("_meta"));return h!=null&&h.where&&(x=Se(i,u,x,h.where)),h!=null&&h.orderBy&&(x=qe(i,u,x,h.orderBy)),(h==null?void 0:h.limit)!==void 0&&(x=x.limit(h.limit)),T&&Object.keys(T).length>0&&(x=Re(i,u,x,T,r,s)),m(x).as(l)});}return t}var $e=class i extends ne{db;dialectHelpers;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.dialectHelpers=ct(this.db),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){this.schema=e,this.logger=t,this.server=n,await dt(this.db,e,t);}selectMetaColumns(e,t,n){var c;let r=k(this.db),s=(c=this.schema)==null?void 0:c[t];if(r==="sqlite"&&(s!=null&&s.fields)){let o=Object.keys(s.fields),a=e.selectFrom(n);for(let l of o)a=a.select(`${n}.${l}`);return a}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,s=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(a=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(a,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));s=Re(this.schema,e,s,n,this.dialectHelpers,this.db);let c=await s.executeTakeFirst();if(!c)return;let o=this.parseRelationalJsonStrings(c,e);return this.convertToMaterializedLiveType(o,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return R(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:s,sort:c}=e,o=`${t}_meta`,a=this.db.selectFrom(t).selectAll(t).select(d=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(d,t,o).whereRef(`${o}.id`,"=",`${t}.id`)).as("_meta"));a=Se(this.schema,t,a,n),a=Re(this.schema,t,a,r,this.dialectHelpers,this.db),s!==void 0&&(a=a.limit(s)),c!==void 0&&(a=qe(this.schema,t,a,c));let l=await a.execute();return l.length===0?[]:l.map(d=>{let u=this.parseRelationalJsonStrings(d,t);return this.convertToMaterializedLiveType(u,t)})}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=>R(r))}async rawInsert(e,t,n,r,s){var m,h,T,S,w,x,C,E,_,q,J;let c=(m=this.server)==null?void 0:m.getHooks(e),o=(h=this.schema)==null?void 0:h[e],[a,l]=((T=o==null?void 0:o.mergeMutation)==null?void 0:T.call(o,"set",n.value,void 0))??[n,n.value];if(!l)return {data:n,acceptedValues:null};let d=a,u={...d,value:{...d.value,id:{value:t}}};if(c!=null&&c.beforeInsert){let L=R(u);L.id=t;let v=await c.beforeInsert({ctx:s,value:L,rawValue:u,db:this});v&&(d=v);}let y={},p={};for(let[L,v]of Object.entries(d.value)){let M=(S=v._meta)==null?void 0:S.timestamp;if(!M)continue;let I=(x=(w=o==null?void 0:o.fields[L])==null?void 0:w.getStorageFieldType)==null?void 0:x.call(w);(I==null?void 0:I.type)==="jsonb"||(I==null?void 0:I.type)==="json"?y[L]=JSON.stringify(v.value):y[L]=v.value,p[L]=M;}await this.db.insertInto(e).values({...y,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...p,id:t}).execute(),(E=(C=this.logger)==null?void 0:C.debug)==null||E.call(C,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(s==null?void 0:s.messageId)??"(none)",hasContext:!!s,contextKeys:s?Object.keys(s):[]});let f=this.buildMutation(e,t,"INSERT",d,r,s==null?void 0:s.messageId);if(f&&((J=(_=this.logger)==null?void 0:_.debug)==null||J.call(_,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:((q=f.meta)==null?void 0:q.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,d)),c!=null&&c.afterInsert){let L={...d,value:{...d.value,id:{value:t}}},v=R(L);v.id=t,await c.afterInsert({ctx:s,value:v,rawValue:L,db:this});}return {data:d,acceptedValues:l}}async rawUpdate(e,t,n,r,s){var h,T,S,w,x,C,E,_,q,J,L;let c=(h=this.server)==null?void 0:h.getHooks(e),o=(T=this.schema)==null?void 0:T[e],a=await this.rawFindById(e,t),[l,d]=((S=o==null?void 0:o.mergeMutation)==null?void 0:S.call(o,"set",n.value,a))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let u=l,y={...u,value:{...u.value,id:{value:t}}};if(c!=null&&c.beforeUpdate){let v=R(y);v.id=t;let M;if(a){let A={...a,value:{...a.value,id:{value:t}}};M=R(A),M.id=t;}let I=await c.beforeUpdate({ctx:s,value:v,rawValue:y,previousValue:M,previousRawValue:a,db:this});I&&(u=I);}let p={},f={};for(let[v,M]of Object.entries(u.value)){let I=(w=M._meta)==null?void 0:w.timestamp;if(!I)continue;let A=(C=(x=o==null?void 0:o.fields[v])==null?void 0:x.getStorageFieldType)==null?void 0:C.call(x);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?p[v]=JSON.stringify(M.value):p[v]=M.value,f[v]=I;}if(Object.keys(p).length===0)return {data:u,acceptedValues:d};await Promise.all([this.db.updateTable(e).set(p).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(v=>v.column("id").doUpdateSet(f)).execute()]),(_=(E=this.logger)==null?void 0:E.debug)==null||_.call(E,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(s==null?void 0:s.messageId)??"(none)",hasContext:!!s,contextKeys:s?Object.keys(s):[]});let m=this.buildMutation(e,t,"UPDATE",u,r,s==null?void 0:s.messageId);if(m){(L=(q=this.logger)==null?void 0:q.debug)==null||L.call(q,"[rawUpdate] Mutation built, tracking",{mutationId:m.id,hasMeta:!!m.meta,originMutationId:((J=m.meta)==null?void 0:J.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let v=await this.rawFindById(e,t);v&&this.trackMutation(m,v);}if(c!=null&&c.afterUpdate){let v=await this.rawFindById(e,t);if(v){let M={...v,value:{...v.value,id:{value:t}}},I=R(M);I.id=t;let A;if(a){let pt={...a,value:{...a.value,id:{value:t}}};A=R(pt),A.id=t;}await c.afterUpdate({ctx:s,value:I,rawValue:M,previousValue:A,previousRawValue:a,db:this});}}return {data:u,acceptedValues:d}}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),c=this.mutationStack,o=[];this.mutationStack=o;let a=await this.db.savepoint(s).execute(),l=false,d=false;try{return await e({trx:this,commit:async()=>{await a.releaseSavepoint(s).execute(),l=!0,c.push(...o);},rollback:async()=>{await a.rollbackToSavepoint(s).execute(),d=!0,o.length=0;}}).then(u=>a.isCommitted||a.isRolledBack||l||d?u:a.releaseSavepoint(s).execute().then(()=>(c.push(...o),u)))}catch(u){throw d||await a.rollbackToSavepoint(s).execute().catch(()=>{}),o.length=0,u}finally{this.mutationStack=c;}}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()=>{var c,o;await r.commit().execute(),(o=(c=this.logger)==null?void 0:c.debug)==null||o.call(c,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:a})=>{var l;return {id:a.id,resource:a.resource,resourceId:a.resourceId,op:a.op,hasMeta:!!a.meta,originMutationId:((l=a.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(c=>r.isCommitted||r.isRolledBack?c:r.commit().execute().then(()=>{var o,a;return (a=(o=this.logger)==null?void 0:o.debug)==null||a.call(o,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:l})=>{var d;return {id:l.id,resource:l.resource,resourceId:l.resourceId,op:l.op,hasMeta:!!l.meta,originMutationId:((d=l.meta)==null?void 0:d.originMutationId)??"(none)"}})}),this.notifyMutations(t),c}))}catch(s){throw await r.rollback().execute(),t.length=0,s}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var s,c;if(k(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(o=>this.parseRelationalJsonStrings(o,t));let r={};for(let[o,a]of Object.entries(e))if(o==="_meta"&&typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{r[o]=JSON.parse(a);}catch{r[o]=a;}else r[o]=a;else if(this.isRelationalField(t,o))if(typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{let l=JSON.parse(a);if(this.schema){let d=this.schema[t],u=(s=d==null?void 0:d.relations)==null?void 0:s[o];if(u){let y=u.entity.name;r[o]=this.parseRelationalJsonStrings(l,y);}else r[o]=l;}else r[o]=l;}catch{r[o]=a;}else r[o]=a;else if(typeof a=="object"&&a!==null&&!Array.isArray(a))if(this.schema){let l=this.schema[t],d=(c=l==null?void 0:l.relations)==null?void 0:c[o];if(d){let u=d.entity.name;r[o]=this.parseRelationalJsonStrings(a,u);}else r[o]=a;}else r[o]=a;else Array.isArray(a)?r[o]=a.map(l=>{var d,u;if(typeof l=="string")try{let y=JSON.parse(l);if(this.schema){let p=this.schema[t],f=(d=p==null?void 0:p.relations)==null?void 0:d[o];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(y,m)}}return y}catch{return l}if(typeof l=="object"&&l!==null&&this.schema){let y=this.schema[t],p=(u=y==null?void 0:y.relations)==null?void 0:u[o];if(p){let f=p.entity.name;return this.parseRelationalJsonStrings(l,f)}}return l}):r[o]=a;else r[o]=a;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((s,[c,o])=>{var u,y,p,f,m,h,T,S,w;if(c==="_meta")return s;let a=(y=(u=n==null?void 0:n.fields[c])==null?void 0:u.getStorageFieldType)==null?void 0:y.call(u),l=(a==null?void 0:a.type)==="jsonb"||(a==null?void 0:a.type)==="json",d=(n==null?void 0:n.relations)&&c in n.relations;if(c==="id")s[c]={value:o};else if(l)s[c]={value:o,_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[c]}};else if(d){let x=n.relations[c].entity,C=(x==null?void 0:x.name)??t;Array.isArray(o)?s[c]={value:o.map(E=>this.convertToMaterializedLiveType(E,C)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[c],relation:true}}:o!==null&&typeof o=="object"?s[c]={...this.convertToMaterializedLiveType(o,C),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[c],relation:true}}:s[c]={value:o,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[c],relation:true}};}else Array.isArray(o)?s[c]={value:o,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[c]}}:typeof o=="object"&&o!==null&&!(o instanceof Date)?s[c]={value:o,_meta:{timestamp:(S=e==null?void 0:e._meta)==null?void 0:S[c]}}:s[c]={value:o,_meta:{timestamp:(w=e==null?void 0:e._meta)==null?void 0:w[c]}};return s},{})}}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",c=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||s&&c}buildMutation(e,t,n,r,s,c){var a;let o={};for(let[l,d]of Object.entries(r.value)){if(l==="id")continue;let u=(a=d._meta)==null?void 0:a.timestamp;u&&(o[l]={value:d.value,_meta:{timestamp:u}});}return Object.keys(o).length===0?null:{id:s??pe(),type:"SYNC",resource:e,resourceId:t,op:n,payload:o,meta:c?{originMutationId:c}:void 0}}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 Qe=class i{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var t;if(this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=We({level:e.logLevel??F.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),e.hooks)for(let[n,r]of Object.entries(e.hooks)){let s=Ce([r]);s&&this.hooksRegistry.set(n,s);}this.initPromise=this.storage.init(this.schema,this.logger,this).catch(n=>{this.initError=n;}),this.contextProvider=e.contextProvider,this.queryEngine=new he({storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleMutation(e){return await this.ensureInitialized(),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)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async y=>{let p=this.router.routes[y.resource];if(!p)throw new Error("Invalid resource");return p.handleCustomQuery({req:y,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:r,cookies:s,queryParams:c,context:o}=e.req,a={headers:r,cookies:s,queryParams:c,context:o},l=t.buildQueryRequest(),d=e.subscription?this.queryEngine.subscribe(l,y=>{var p;(p=e.subscription)==null||p.call(e,y);},a):void 0,u=await this.queryEngine.get(l,{context:a});return e.subscription?{data:u,unsubscribe:d,query:l}:u.map(y=>R(y))}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)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},Ni=Qe.create;exports.QueryBuilder=ee;exports.Route=De;exports.RouteFactory=ke;exports.Router=Ve;exports.SQLStorage=$e;exports.Server=Qe;exports.Storage=ne;exports.createMiddleware=oi;exports.createServerDB=te;exports.defineHooks=br;exports.expressAdapter=Zr;exports.mergeEntityHooks=Ce;exports.mergeHooks=Ir;exports.routeFactory=ai;exports.router=si;exports.server=Ni;
package/dist/server.d.cts CHANGED
@@ -63,7 +63,26 @@ interface QueryExecutor extends DataSource {
63
63
  subscribe(query: RawQueryRequest, callback: (value: any[]) => void): () => void;
64
64
  }
65
65
  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>>[];
66
+ /**
67
+ * Type-only brand recording a {@link QueryBuilder}'s inferable parameters.
68
+ *
69
+ * `CustomQueryResult` (client entry point) has to recognise a query-builder
70
+ * value returned from a route handler whose type flows through the *server*
71
+ * entry point. The two entry points are emitted as separate `.d.ts` graphs, so
72
+ * each gets its own `declare class QueryBuilder`; because the class has
73
+ * `private` members, TypeScript compares those declarations *nominally* and any
74
+ * `extends QueryBuilder<...>` check across the boundary fails. Narrowing on this
75
+ * structural brand instead makes the check independent of class identity — and
76
+ * therefore also of duplicate installed package versions.
77
+ */
78
+ interface QueryBuilderBrand<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection>, TSingle extends boolean> {
79
+ collection: TCollection;
80
+ include: TInclude;
81
+ single: TSingle;
82
+ }
66
83
  declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection> = {}, TSingle extends boolean = false, TShouldAwait extends boolean = false> {
84
+ /** Never assigned at runtime; exists only to carry {@link QueryBuilderBrand}. */
85
+ readonly __queryBuilderBrand: QueryBuilderBrand<TCollection, TInclude, TSingle>;
67
86
  private _collection;
68
87
  private _client;
69
88
  private _where;
package/dist/server.d.ts CHANGED
@@ -63,7 +63,26 @@ interface QueryExecutor extends DataSource {
63
63
  subscribe(query: RawQueryRequest, callback: (value: any[]) => void): () => void;
64
64
  }
65
65
  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>>[];
66
+ /**
67
+ * Type-only brand recording a {@link QueryBuilder}'s inferable parameters.
68
+ *
69
+ * `CustomQueryResult` (client entry point) has to recognise a query-builder
70
+ * value returned from a route handler whose type flows through the *server*
71
+ * entry point. The two entry points are emitted as separate `.d.ts` graphs, so
72
+ * each gets its own `declare class QueryBuilder`; because the class has
73
+ * `private` members, TypeScript compares those declarations *nominally* and any
74
+ * `extends QueryBuilder<...>` check across the boundary fails. Narrowing on this
75
+ * structural brand instead makes the check independent of class identity — and
76
+ * therefore also of duplicate installed package versions.
77
+ */
78
+ interface QueryBuilderBrand<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection>, TSingle extends boolean> {
79
+ collection: TCollection;
80
+ include: TInclude;
81
+ single: TSingle;
82
+ }
66
83
  declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection> = {}, TSingle extends boolean = false, TShouldAwait extends boolean = false> {
84
+ /** Never assigned at runtime; exists only to carry {@link QueryBuilderBrand}. */
85
+ readonly __queryBuilderBrand: QueryBuilderBrand<TCollection, TInclude, TSingle>;
67
86
  private _collection;
68
87
  private _client;
69
88
  private _where;
package/dist/server.js CHANGED
@@ -1,12 +1,12 @@
1
- import {a,b,z as z$2,G as G$1,F,B as B$1,E,C,D as D$1}from'./chunk-3XEJ2M4E.js';import Z from'crypto';import wt,{parse}from'qs';import {z as z$1}from'zod';import {Kysely,PostgresDialect,sql}from'kysely';import {jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from'kysely/helpers/mysql';import {jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from'kysely/helpers/postgres';import {jsonArrayFrom,jsonObjectFrom}from'kysely/helpers/sqlite';var ce=a(ee=>{Object.defineProperty(ee,"__esModule",{value:true});ee.parse=pt;ee.serialize=ht;var ct=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,dt=/^[\u0021-\u003A\u003C-\u007E]*$/,ut=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,lt=/^[\u0020-\u003A\u003D-\u007E]*$/,yt=Object.prototype.toString,ft=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function pt(c,e){let t=new ft,n=c.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||mt,o=0;do{let a=c.indexOf("=",o);if(a===-1)break;let s=c.indexOf(";",o),i=s===-1?n:s;if(a>i){o=c.lastIndexOf(";",a-1)+1;continue}let d=Pe(c,o,a),u=ke(c,a,d),l=c.slice(d,u);if(t[l]===void 0){let f=Pe(c,a+1,i),y=ke(c,i,f),p=r(c.slice(f,y));t[l]=p;}o=i+1;}while(o<n);return t}function Pe(c,e,t){do{let n=c.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function ke(c,e,t){for(;e>t;){let n=c.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function ht(c,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!ct.test(c))throw new TypeError(`argument name is invalid: ${c}`);let r=n(e);if(!dt.test(r))throw new TypeError(`argument val is invalid: ${e}`);let o=c+"="+r;if(!t)return o;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);o+="; Max-Age="+t.maxAge;}if(t.domain){if(!ut.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);o+="; Domain="+t.domain;}if(t.path){if(!lt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);o+="; Path="+t.path;}if(t.expires){if(!gt(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);o+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(o+="; HttpOnly"),t.secure&&(o+="; Secure"),t.partitioned&&(o+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":o+="; Priority=Low";break;case "medium":o+="; Priority=Medium";break;case "high":o+="; 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":o+="; SameSite=Strict";break;case "lax":o+="; SameSite=Lax";break;case "none":o+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return o}function mt(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function gt(c){return yt.call(c)==="[object Date]"}});var Me="0123456789ABCDEFGHJKMNPQRSTVWXYZ",B=32;var Ge=16,Ee=10,je=0xffffffffffff;var D;(function(c){c.Base32IncorrectEncoding="B32_ENC_INVALID",c.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",c.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",c.EncodeTimeNegative="ENC_TIME_NEG",c.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",c.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",c.PRNGDetectFailure="PRNG_DETECT",c.ULIDInvalid="ULID_INVALID",c.Unexpected="UNEXPECTED",c.UUIDInvalid="UUID_INVALID";})(D||(D={}));var N=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Ye(c){let e=Math.floor(c()*B);return e===B&&(e=B-1),Me.charAt(e)}function Xe(c){var n;let e=et(),t=e&&(e.crypto||e.msCrypto)||(typeof Z<"u"?Z: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=Z)!=null&&n.randomBytes)return ()=>Z.randomBytes(1).readUInt8()/255;throw new N(D.PRNGDetectFailure,"Failed to find a reliable PRNG")}function et(){return rt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function tt(c,e){let t="";for(;c>0;c--)t=Ye(e)+t;return t}function nt(c,e=Ee){if(isNaN(c))throw new N(D.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>je)throw new N(D.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${je}: ${c}`);if(c<0)throw new N(D.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new N(D.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,n="";for(let r=e;r>0;r--)t=c%B,n=Me.charAt(t)+n,c=(c-t)/B;return n}function rt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ae(c,e){let t=Xe(),n=Date.now();return nt(n,Ee)+tt(Ge,t)}var Y=()=>Ae().toLowerCase(),G=c=>({then(e,t){try{if(e){let n=e(c);return n instanceof Promise?n:G(n)}return G(c)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:G(r)}throw n}}}),_=c=>c instanceof Promise?c:G(c);function oe(c){return B$1({resource:c.query.resource,where:c.query.where,include:c.query.include,stepPath:c.stepPath,isMany:c.isMany,relationName:c.relationName})}function it(c,e){let t=c==null,n=e==null;if(t&&n)return 0;if(t)return -1;if(n)return 1;if(typeof c=="number"&&typeof e=="number")return c-e;if(typeof c=="boolean"&&typeof e=="boolean")return Number(c)-Number(e);let r=String(c),o=String(e);return r<o?-1:r>o?1:0}var W=class{limit;directions;entries=[];index=new Map;constructor(e){if(!Number.isInteger(e.limit)||e.limit<0)throw new Error("WindowIndex limit must be a non-negative integer");this.limit=e.limit,this.directions=(e.orderBy??[]).map(t=>t.direction);}get size(){return this.entries.length}get isFull(){return this.entries.length>=this.limit}compare(e,t){for(let n=0;n<this.directions.length;n++){let r=it(e.sortKey[n],t.sortKey[n]);if(r!==0)return this.directions[n]==="desc"?-r:r}return e.id<t.id?-1:e.id>t.id?1:0}lowerBound(e){let t=0,n=this.entries.length;for(;t<n;){let r=t+n>>>1;this.compare(this.entries[r],e)<0?t=r+1:n=r;}return t}insert(e){if(this.limit===0)return {inserted:false};if(this.index.has(e.id))throw new Error(`WindowIndex already contains id "${e.id}"`);let t=this.lowerBound(e);if(this.isFull&&t>=this.limit)return {inserted:false};if(this.entries.splice(t,0,e),this.index.set(e.id,e),this.entries.length>this.limit){let n=this.entries.pop();if(n)return this.index.delete(n.id),{inserted:true,evicted:n}}return {inserted:true}}remove(e){let t=this.index.get(e);if(!t)return;let n=this.lowerBound(t);return this.entries.splice(n,1),this.index.delete(e),t}has(e){return this.index.has(e)}position(e){let t=this.index.get(e);if(t)return this.lowerBound(t)}boundary(){return this.entries[this.entries.length-1]}needsBackfill(){return this.entries.length<this.limit}get backfillCount(){return Math.max(0,this.limit-this.entries.length)}snapshot(){return this.entries.map(e=>({id:e.id,sortKey:[...e.sortKey]}))}ids(){return this.entries.map(e=>e.id)}};var X=class{storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){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,o]of Object.entries(n.relations))o.type==="one"&&o.relationalColumn&&t.set(String(o.relationalColumn),{relationName:r,targetResource:o.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 o=this.objectNodes.get(e),a=this.objectNodes.get(t);if(o&&o.referencesObjects.set(n,t),a&&r){let s=a.referencedByObjects.get(r);s||(s=new Set,a.referencedByObjects.set(r,s)),s.add(e);}}removeRelation(e,t,n,r){let o=this.objectNodes.get(e),a=this.objectNodes.get(t);if(o&&o.referencesObjects.delete(n),a&&r){let s=a.referencedByObjects.get(r);s&&(s.delete(e),s.size===0&&a.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let o=r.relations[n];if(!o)return;let a=this.schema[t];if(a!=null&&a.relations){if(o.type==="many"&&o.foreignColumn){for(let[s,i]of Object.entries(a.relations))if(i.entity.name===e&&i.type==="one"&&i.relationalColumn===o.foreignColumn)return s}if(o.type==="one"&&o.relationalColumn){for(let[s,i]of Object.entries(a.relations))if(i.entity.name===e&&i.type==="many"&&i.foreignColumn===o.relationalColumn)return s}}}updateRelationsFromMutation(e,t,n,r){let o=this.getRelationalColumns(e),a=this.objectNodes.get(t);if(a)for(let[s,{relationName:i,targetResource:d}]of Array.from(o)){if(!(r&&s in r))continue;let l=this.getInverseRelationName(e,d,i),f=a.referencesObjects.get(i),y=n[s];f!==y&&(f&&this.removeRelation(t,f,i,l),y&&(this.ensureObjectNode(y,d),this.storeRelation(t,y,i,l)));}}get(e,t){let n=this.addedSortRelations(e.resource,e.sort,e.include),r={...e.include??{}};for(let a of n)r[a]=true;let o={...e,...e.limit!==void 0?{sort:[...e.sort??[],{key:"id",direction:"asc"}]}:{},...Object.keys(r).length>0?{include:this.prepareResolveInclude(r,e.resource)}:{}};return _(this.storage.get(o)).then(a=>(this.ingest(e,a),this.stripResolveRelations(a,e.resource,e.include,e.sort),a))}addedSortRelations(e,t,n){var o,a;let r=[];for(let s of t??[]){let i=s.key.indexOf(".");if(i===-1)continue;let d=s.key.slice(0,i);(a=(o=this.schema[e])==null?void 0:o.relations)!=null&&a[d]&&(n&&d in n||r.includes(d)||r.push(d));}return r}stripResolveRelations(e,t,n,r){var a,s,i;let o=this.addedSortRelations(t,r,n);if(o.length>0)for(let d of e){let u=d==null?void 0:d.value;if(u)for(let l of o)delete u[l];}if(n)for(let[d,u]of Object.entries(n)){let l=(s=(a=this.schema[t])==null?void 0:a.relations)==null?void 0:s[d],f=l==null?void 0:l.entity.name;if(!f)continue;let y=E(u)?u:null,p=y?y.include:u&&typeof u=="object"?u:void 0,h=y==null?void 0:y.orderBy;for(let m of e){let g=(i=m==null?void 0:m.value)==null?void 0:i[d];if(!g)continue;let w=l.type==="many"?Array.isArray(g.value)?g.value:[]:[g];this.stripResolveRelations(w,f,p,h);}}}relationalSortDeps(e){var r,o;let t=[],n=e.sort??[];for(let a=0;a<n.length;a++){let s=n[a].key.indexOf(".");if(s===-1)continue;let i=n[a].key.slice(0,s),d=n[a].key.slice(s+1),u=(o=(r=this.schema[e.resource])==null?void 0:r.relations)==null?void 0:o[i];u&&t.push({index:a,relationName:i,field:d,targetResource:u.entity.name});}return t}sortRelationInclude(e){let t=this.relationalSortDeps(e.queryStep.query);if(t.length===0)return;let n={};for(let r of t)n[r.relationName]=true;return n}relationalSortFkColumns(e){let t=new Set,n=this.relationalSortDeps(e.queryStep.query);if(n.length===0)return t;let r=this.getRelationalColumns(e.queryStep.query.resource);for(let[o,{relationName:a}]of Array.from(r))n.some(s=>s.relationName===a)&&t.add(o);return t}ownWriteTouchesSortRelationFk(e,t){if(!t)return false;for(let n of Array.from(this.relationalSortFkColumns(e)))if(n in t)return true;return false}async resolveSortRelations(e,t,n){let r=this.sortRelationInclude(e);if(!r)return n;let o=await _(this.storage.get({resource:e.queryStep.query.resource,where:{id:t},include:r})),a=o[0]?z$2(o[0]):void 0;if(!a||typeof a!="object")return n;for(let s of Object.keys(r))s in a||(a[s]=void 0);return a}stripPayloadRelations(e,t){if(t)for(let n of Object.keys(t))delete e[n];return e}prepareResolveInclude(e,t){var r,o,a;let n={};for(let[s,i]of Object.entries(e)){let d=(a=(o=(r=this.schema[t])==null?void 0:r.relations)==null?void 0:o[s])==null?void 0:a.entity.name;if(E(i)){let u=i.limit!==void 0,l={...i.include??{}};if(u&&d)for(let y of this.addedSortRelations(d,i.orderBy,i.include))l[y]=true;let f=d&&Object.keys(l).length>0?this.prepareResolveInclude(l,d):i.include;n[s]={...i,...f!==void 0?{include:f}:{},...u?{orderBy:[...i.orderBy??[],{key:"id",direction:"asc"}]}:{}};}else i&&typeof i=="object"&&d?n[s]=this.prepareResolveInclude(i,d):n[s]=i;}return n}ingest(e,t){for(let n of this.buildSteps({query:e})){let r=n.stepPath.length===0?t:this.extractByPath(t,e.resource,n.stepPath);this.trackObjects(n,r);}}extractByPath(e,t,n){var a,s,i;let r=e,o=t;for(let d of n){let u=(s=(a=this.schema[o])==null?void 0:a.relations)==null?void 0:s[d],l=(u==null?void 0:u.type)==="many",f=[];for(let y of r){let p=(i=y==null?void 0:y.value)==null?void 0:i[d];if(p)if(l){if(Array.isArray(p.value))for(let h of p.value)h&&f.push(h);}else p.value!=null&&f.push(p);}r=f,u&&(o=u.entity.name);}return r}subscribe(e,t,n={}){let r=this.buildSteps({query:e}),o={},a=[];for(let s of r){this.logger.debug("[QueryEngine] Subscribing to step",s.stepPath.join("."));let i=oe(s),d=o[s.stepPath.at(-2)??""],u=s.stepPath.at(-1)??"",l=this.queryNodes.get(i);if(l)l.subscriptions.add(t);else {let f=s.stepPath.length===0&&s.query.limit!==void 0;if(l={hash:i,queryStep:s,relationName:u,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:d,childQueries:new Set,windowIndex:f?new W({limit:s.query.limit,orderBy:this.orderByFor(s.query)}):void 0},this.queryNodes.set(l.hash,l),d){let y=this.queryNodes.get(d);y&&y.childQueries.add(l.hash);}}o[u]=i,a.push(()=>{let f=this.queryNodes.get(i);f&&(f.subscriptions.delete(t),f.subscriptions.size===0&&this.queryNodes.delete(i));});}return ()=>{for(let s of a)s();}}buildSteps(e){var y,p;let{query:t,stepPath:n=[],parentResource:r}=e,{include:o}=t,a=n.length===0,s=n.at(-1),i;if(!a&&r&&s){let h=(p=(y=this.schema[r])==null?void 0:y.relations)==null?void 0:p[s];h&&(i=h.type==="many");}let{include:d,...u}=t,f=[{query:u,stepPath:[...n],includedRelations:o&&typeof o=="object"?Object.keys(o):[],isMany:i,relationName:s}];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`);f.push(...Object.entries(o).flatMap(([m,g])=>{let w=h.relations[m];if(!w)throw new Error(`Relation ${m} not found for resource ${t.resource}`);let x=w.entity.name,S=E(g)?g:null;return this.buildSteps({query:{resource:x,include:S?S.include:typeof g=="object"?g:void 0,where:S==null?void 0:S.where,limit:S==null?void 0:S.limit,sort:S==null?void 0:S.orderBy},stepPath:[...n,m],parentResource:t.resource})}));}return f}trackObjects(e,t){var i;this.logger.debug("[QueryEngine] Tracking step objects",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=oe(e),r=this.queryNodes.get(n),o=e.query.resource;if(!r)return;let a=this.getRelationalColumns(o);for(let d of t){let u=z$2(d),l=u.id;this.ensureObjectNode(l,o,n),r.trackedObjects.add(l);for(let[f,{relationName:y,targetResource:p}]of Array.from(a)){let h=u[f];if(h){this.ensureObjectNode(h,p);let m=this.getInverseRelationName(o,p,y);this.storeRelation(l,h,y,m);}}this.loadNestedRelations(o,l,u),this.logger.debug("[QueryEngine] Loaded nested relations for",l);}if(r.windowIndex&&!r.windowInitialized){for(let d of t){let u=z$2(d);!(u!=null&&u.id)||r.windowIndex.has(u.id)||r.windowIndex.insert({id:u.id,sortKey:this.sortKeyFor(r,u)});}r.windowInitialized=true;}let s=this.includeForeignColumn(r);if(s){r.seededParents??=new Set;for(let d of t){let u=z$2(d),l=u==null?void 0:u.id,f=u==null?void 0:u[s];if(!l||f==null||r.seededParents.has(f))continue;let y=this.ensureParentWindow(r,f);y.has(l)||y.insert({id:l,sortKey:this.sortKeyFor(r,u)});}for(let d of t){let u=(i=z$2(d))==null?void 0:i[s];u!=null&&r.seededParents.add(u);}}}orderByFor(e){return (e.sort??[]).map(t=>({key:t.key,direction:t.direction}))}sortKeyFor(e,t,n){return (e.queryStep.query.sort??[]).map((r,o)=>{let a=r.key.indexOf(".");if(a===-1)return t==null?void 0:t[r.key];let s=r.key.slice(0,a),i=r.key.slice(a+1),d=t==null?void 0:t[s];if(d&&typeof d=="object"&&i in d)return d[i];if(!(t&&typeof t=="object"&&s in t))return n==null?void 0:n[o]})}storageSortFor(e){return [...e.queryStep.query.sort??[],{key:"id",direction:"asc"}]}includeForeignColumn(e){var o,a;if(e.queryStep.stepPath.length===0||e.queryStep.query.limit===void 0||!e.relationName||!e.parentQuery)return;let t=this.queryNodes.get(e.parentQuery),n=t==null?void 0:t.queryStep.query.resource;if(!n)return;let r=(a=(o=this.schema[n])==null?void 0:o.relations)==null?void 0:a[e.relationName];if(!((r==null?void 0:r.type)!=="many"||!r.foreignColumn))return String(r.foreignColumn)}isWindowedIncludeNode(e){return this.includeForeignColumn(e)!==void 0}ensureParentWindow(e,t){e.windowIndexes||(e.windowIndexes=new Map);let n=e.windowIndexes.get(t);return n||(n=new W({limit:e.queryStep.query.limit,orderBy:this.orderByFor(e.queryStep.query)}),e.windowIndexes.set(t,n)),n}parentWindowHolding(e,t){if(e.windowIndexes){for(let[n,r]of Array.from(e.windowIndexes))if(r.has(t))return {parentId:n,wi:r}}}emitToSubscribers(e,t,n){for(let r of Array.from(e.subscriptions))try{r(t);}catch(o){this.logger.error(`[QueryEngine] Error in subscription during ${n}`,{error:o,queryHash:e.hash,resource:t.resource,resourceId:t.resourceId});}}emitScopeOut(e,t,n){var r;e.trackedObjects.delete(t),(r=this.objectNodes.get(t))==null||r.matchedQueries.delete(e.hash),this.emitToSubscribers(e,{type:"SYNC",op:"DELETE",resource:e.queryStep.query.resource,resourceId:t,payload:{},meta:n},"scope-out DELETE");}handleWindowedInsert(e,t,n,r){var a;let o=t.insert({id:n.resourceId,sortKey:this.sortKeyFor(e,r)});o.inserted&&(e.trackedObjects.add(n.resourceId),(a=this.objectNodes.get(n.resourceId))==null||a.matchedQueries.add(e.hash),this.emitToSubscribers(e,n,"windowed scope-in INSERT"),o.evicted&&this.emitScopeOut(e,o.evicted.id,n.meta));}async handleWindowedUpdate(e,t,n,r,o){let a=e.windowIndex;if(!a)return;let s=t.resourceId,i=a.has(s);if(o&&(!i||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,s,r)),o){if(i){await this.refreshInWindow(e,a,t,r);return}this.scopeInViaUpdate(e,a,t,n,r);return}i&&(a.remove(s),this.emitScopeOut(e,s,t.meta),await this.backfillWindow(e,a,t.meta));}async refreshInWindow(e,t,n,r,o){var d,u;let a=n.resourceId,s=(d=t.remove(a))==null?void 0:d.sortKey,i=this.sortKeyFor(e,r,s);if(t.insert({id:a,sortKey:i}),t.isFull&&((u=t.boundary())==null?void 0:u.id)===a&&!this.sortKeysEqual(s,i)){await this.reconcileDemotion(e,t,a,i,n,o);return}this.emitToSubscribers(e,n,"windowed UPDATE");}scopeInViaUpdate(e,t,n,r,o){var i;let a=n.resourceId,s=t.insert({id:a,sortKey:this.sortKeyFor(e,o)});s.inserted&&(e.trackedObjects.add(a),(i=this.objectNodes.get(a))==null||i.matchedQueries.add(e.hash),this.emitToSubscribers(e,this.fullInsertDelta(e,n,r),"windowed scope-in INSERT"),s.evicted&&this.emitScopeOut(e,s.evicted.id,n.meta));}async handleWindowedIncludeUpdate(e,t,n,r,o){let a=this.includeForeignColumn(e);if(!a)return;let s=t.resourceId,i=o?r[a]:void 0,d=this.parentWindowHolding(e,s),u=d==null?void 0:d.parentId,l=u!==void 0&&u===i;if((i!==void 0&&!l||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,s,r)),l){await this.refreshInWindow(e,d.wi,t,r,{column:a,parentId:u});return}if(d&&(d.wi.remove(s),this.emitScopeOut(e,s,t.meta),await this.backfillWindow(e,d.wi,t.meta,{column:a,parentId:d.parentId})),i!==void 0){let f=this.ensureParentWindow(e,i);f.has(s)||this.scopeInViaUpdate(e,f,t,n,r);}}async handleRelationalSortFanout(e,t){if(!e.payload)return;let n=this.objectNodes.get(e.resourceId);for(let r of Array.from(this.queryNodes.values())){let o=this.relationalSortDeps(r.queryStep.query);if(o.length===0)continue;let a=!!r.windowIndex,s=this.isWindowedIncludeNode(r);if(!a&&!s)continue;let i=false;for(let d of o){if(d.targetResource!==e.resource||!(d.field in e.payload))continue;i=true;let u=t==null?void 0:t[d.field],l=this.getInverseRelationName(r.queryStep.query.resource,e.resource,d.relationName),f=n&&l?n.referencedByObjects.get(l):void 0;if(!(!f||f.size===0))for(let y of Array.from(f))if(a){let p=r.windowIndex;if(!p.has(y))continue;this.repositionForRelationalChange(p,y,d.index,u);}else {let p=this.parentWindowHolding(r,y);if(!p)continue;this.repositionForRelationalChange(p.wi,y,d.index,u);}}if(i){if(a)r.windowInitialized&&await this.reconcilePromotions(r,r.windowIndex,e);else if(r.windowIndexes){let d=this.includeForeignColumn(r);for(let[u,l]of Array.from(r.windowIndexes))await this.reconcilePromotions(r,l,e,{column:d,parentId:u});}}}}repositionForRelationalChange(e,t,n,r){let o=e.remove(t);if(!o)return;let a=[...o.sortKey];a[n]=r,e.insert({id:t,sortKey:a});}async reconcilePromotions(e,t,n,r){let o=e.queryStep.query.limit;if(o===void 0)return;let a=e.queryStep.query.resource,s=this.sortRelationInclude(e),i=e.queryStep.query.where;r&&(i=this.combineWhere(i,{[r.column]:r.parentId}));let u=(await _(this.storage.get({resource:a,where:i,sort:this.storageSortFor(e),limit:o,include:s}))).map(f=>({row:f,value:z$2(f)})).filter(f=>{var y;return !!((y=f.value)!=null&&y.id)}),l=new Set(u.map(f=>f.value.id));for(let f of t.ids())l.has(f)||(t.remove(f),this.emitScopeOut(e,f,n.meta));for(let{row:f,value:y}of u){let p=this.sortKeyFor(e,y);if(t.has(y.id)){t.remove(y.id),t.insert({id:y.id,sortKey:p});continue}let h=t.insert({id:y.id,sortKey:p});if(!h.inserted)continue;e.trackedObjects.add(y.id),this.ensureObjectNode(y.id,a,e.hash).matchedQueries.add(e.hash),this.registerObjectRelations(a,y.id,y);let m=this.stripPayloadRelations({...(f==null?void 0:f.value)??{}},s);delete m.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:a,resourceId:y.id,payload:m,meta:n.meta},"windowed relational promotion INSERT"),h.evicted&&this.emitScopeOut(e,h.evicted.id,n.meta);}}registerObjectRelations(e,t,n){let r=this.getRelationalColumns(e);for(let[o,{relationName:a,targetResource:s}]of Array.from(r)){let i=n==null?void 0:n[o];if(!i)continue;this.ensureObjectNode(i,s);let d=this.getInverseRelationName(e,s,a);this.storeRelation(t,i,a,d);}}sortKeysEqual(e,t){if(!e||e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return false;return true}async reconcileDemotion(e,t,n,r,o,a){t.remove(n);let s=e.queryStep.query.resource,i=this.windowReadWhere(e,t,a),d=this.sortRelationInclude(e),u=await _(this.storage.get({resource:s,where:i,sort:this.storageSortFor(e),limit:2,include:d})),l,f;for(let p of u){let h=z$2(p);if(!(!(h!=null&&h.id)||h.id===n||t.has(h.id))){l=h,f=p;break}}if(!l){t.insert({id:n,sortKey:r}),this.emitToSubscribers(e,o,"windowed UPDATE");return}if(t.insert({id:l.id,sortKey:this.sortKeyFor(e,l)}),t.insert({id:n,sortKey:r}).inserted){this.emitToSubscribers(e,o,"windowed UPDATE");return}e.trackedObjects.add(l.id),this.ensureObjectNode(l.id,s,e.hash).matchedQueries.add(e.hash);let y=this.stripPayloadRelations({...(f==null?void 0:f.value)??{}},d);delete y.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:s,resourceId:l.id,payload:y,meta:o.meta},"windowed demotion backfill INSERT"),this.emitScopeOut(e,n,o.meta);}fullInsertDelta(e,t,n){let r={...(n==null?void 0:n.value)??{}};return delete r.id,{type:"SYNC",op:"INSERT",resource:e.queryStep.query.resource,resourceId:t.resourceId,payload:r,meta:t.meta}}async backfillWindow(e,t,n,r){let o=t.backfillCount;if(o<=0)return;let a=e.queryStep.query.resource,s=this.windowReadWhere(e,t,r),i=this.sortRelationInclude(e),d=await _(this.storage.get({resource:a,where:s,sort:this.storageSortFor(e),limit:o,include:i}));for(let u of d){let l=z$2(u);if(!(l!=null&&l.id)||t.has(l.id))continue;t.insert({id:l.id,sortKey:this.sortKeyFor(e,l)}),e.trackedObjects.add(l.id),this.ensureObjectNode(l.id,a,e.hash).matchedQueries.add(e.hash);let f=this.stripPayloadRelations({...(u==null?void 0:u.value)??{}},i);delete f.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:a,resourceId:l.id,payload:f,meta:n},"windowed backfill INSERT");}}buildCursorWhere(e,t){if(!t)return;let n=[...e.queryStep.query.sort??[],{key:"id",direction:"asc"}],r=[...t.sortKey,t.id],o=[];for(let a=0;a<n.length;a++){let s=[];for(let d=0;d<a;d++)s.push(this.cursorCond(n[d].key,r[d]));let i=n[a].direction==="desc"?"$lt":"$gt";s.push(this.cursorCond(n[a].key,{[i]:r[a]})),o.push(s.length===1?s[0]:{$and:s});}return o.length===1?o[0]:{$or:o}}cursorCond(e,t){let n=e.indexOf(".");return n===-1?{[e]:t}:{[e.slice(0,n)]:{[e.slice(n+1)]:t}}}windowReadWhere(e,t,n){let r=e.queryStep.query.where;return n&&(r=this.combineWhere(r,{[n.column]:n.parentId})),this.combineWhere(r,this.buildCursorWhere(e,t.boundary()))}combineWhere(e,t){return t?!e||Object.keys(e).length===0?t:{$and:[e,t]}:e}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[o,a]of Object.entries(r.relations)){let s=n[o];if(!s)continue;let i=a.entity.name,d=this.getInverseRelationName(e,i,o);if(a.type==="one")s&&typeof s=="object"&&s.id&&(this.ensureObjectNode(s.id,i),this.storeRelation(t,s.id,o,d),this.loadNestedRelations(i,s.id,s));else if(a.type==="many"&&Array.isArray(s)){for(let u of s)if(u&&typeof u=="object"&&u.id){this.ensureObjectNode(u.id,i);let l=this.getInverseRelationName(i,e,o);l&&this.storeRelation(u.id,t,l,o),this.loadNestedRelations(i,u.id,u);}}}}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 o=this.queryNodes.get(r);if(!o||!o.relationName)continue;let a=this.buildIncludeFromChildQueries(r);n[o.relationName]=Object.keys(a).length>0?a:true;}return n}sendInsertsForTree(e,t,n,r){var i,d;let o=(d=(i=t==null?void 0:t.value)==null?void 0:i.id)==null?void 0:d.value;if(!o)return;let a={op:"INSERT",resource:n,resourceId:o,type:"SYNC",payload:t.value,meta:r};for(let u of Array.from(e.subscriptions))try{u(a);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:n,resourceId:o,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(o),this.ensureObjectNode(o,n,e.hash).matchedQueries.add(e.hash);for(let u of Array.from(e.childQueries)){let l=this.queryNodes.get(u);if(!l||!l.relationName)continue;let f=l.relationName,y=l.queryStep.query.resource,p=t.value[f];if(!p)continue;let h=p.value;if(Array.isArray(h))for(let m of h)this.sendInsertsForTree(l,m,y,r);else h&&typeof h=="object"&&this.sendInsertsForTree(l,h,y,r);}}handleMutation(e,t){if(e.op==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=z$2(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 o=this.getRelationalColumns(e.resource);for(let[s,{relationName:i,targetResource:d}]of Array.from(o)){let u=n[s];if(u){this.ensureObjectNode(u,d);let l=this.getInverseRelationName(e.resource,d,i);this.storeRelation(e.resourceId,u,i,l);}}let a=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(async s=>{try{for(let i of s){let d=this.queryNodes.get(i);if(!d)continue;if(d.windowIndex){let l=await this.resolveSortRelations(d,e.resourceId,n);this.handleWindowedInsert(d,d.windowIndex,e,l);continue}let u=this.includeForeignColumn(d);if(u){let l=n[u];if(l!=null){let f=await this.resolveSortRelations(d,e.resourceId,n);this.handleWindowedInsert(d,this.ensureParentWindow(d,l),e,f);}continue}d.trackedObjects.add(e.resourceId),a&&a.matchedQueries.add(i);for(let l of Array.from(d.subscriptions))try{l(e);}catch(f){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:f,queryHash:d.hash,resource:e.resource,resourceId:e.resourceId,stepPath:d.queryStep.stepPath.join(".")});}}}catch(i){this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:i,resource:e.resource,resourceId:e.resourceId});}},s=>{this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:s,resource:e.resource,resourceId:e.resourceId});});return}if(e.op==="UPDATE"){let n=z$2(t);if(!n)return;let r=this.objectNodes.get(e.resourceId),o=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.handleRelationalSortFanout(e,n).catch(a=>{this.logger.error("[QueryEngine] Error during relational sort fan-out",{error:a,resource:e.resource,resourceId:e.resourceId});}),this.getMatchingQueries(e,n).then(async a=>{let s=new Set(a),i=new Set;for(let y of Array.from(this.queryNodes.values()))y.queryStep.query.resource===e.resource&&(y.windowIndex?(i.add(y.hash),await this.handleWindowedUpdate(y,e,t,n,s.has(y.hash))):this.isWindowedIncludeNode(y)&&(i.add(y.hash),await this.handleWindowedIncludeUpdate(y,e,t,n,s.has(y.hash))));let d=[],u=[],l=[];for(let y of a)i.has(y)||(o.has(y)?l.push(y):d.push(y));for(let y of Array.from(o))i.has(y)||s.has(y)||u.push(y);for(let y of d){let p=this.queryNodes.get(y);p&&p.trackedObjects.add(e.resourceId);}for(let y of u){let p=this.queryNodes.get(y);p&&p.trackedObjects.delete(e.resourceId);}let f=this.objectNodes.get(e.resourceId);if(f){for(let y of d)f.matchedQueries.add(y);for(let y of u)f.matchedQueries.delete(y);}for(let y of [...u,...l]){let p=this.queryNodes.get(y);if(p)for(let h of Array.from(p.subscriptions))try{h(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:p.hash,resource:e.resource,resourceId:e.resourceId,stepPath:p.queryStep.stepPath.join(".")});}}if(d.length>0)for(let y of d){let p=this.queryNodes.get(y);if(!p)continue;let h=this.buildIncludeFromChildQueries(y);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(h).length>0?h:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(p,m[0],e.resource,e.meta);});}});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?_([]):Promise.all(n.map(async r=>{let o=r.queryStep.query.where,a=r.queryStep.query.resource,s=e.resourceId,i=this.objectNodes.get(s);if(!i)return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,p=y==null?void 0:y.queryStep.query.resource,h=p?this.getInverseRelationName(p,a,r.relationName):void 0,m=h?i.referencesObjects.get(h):void 0;if(!m)return {hash:r.hash,matches:false};let g=this.objectNodes.get(m);if(!g||!y||!g.matchedQueries.has(y.hash))return {hash:r.hash,matches:false}}if(!o)return {hash:r.hash,matches:true};let d=C(o,a,this.schema),u=Object.keys(d).length>0;if(!u&&t!==void 0)return {hash:r.hash,matches:D$1(t,o)};let l=await this.storage.get({resource:a,where:{id:s},include:u?d:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let f=z$2(l[0]);return f?{hash:r.hash,matches:D$1(f,o)}:{hash:r.hash,matches:false}})).then(r=>r.filter(o=>o.matches).map(o=>o.hash))}};var pn=c=>c,st=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],ot=c=>c.length===1?c[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let o of c){let a=await o({...e,value:n,rawValue:t});a&&(t=a,n=z$2(t),n.id=e.value.id,r=true);}return r?t:void 0}),at=c=>c.length===1?c[0]:(async e=>{for(let t of c)await t(e);}),ae=c=>{let e=c.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of st){let r=e.map(o=>o[n]).filter(o=>o!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=at(r):t[n]=ot(r));}return t},hn=(...c)=>{let e={},t=new Set;for(let n of c)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=c.map(a=>a[n]),o=ae(r);o&&(e[n]=o);}return e};var Ne=b(ce(),1);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(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()});var de=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()})),Tt=de.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),St=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),Le=z$1.object({timestamp:z$1.string().optional(),originMutationId:z$1.string().optional()}).optional(),H=St.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:Le}),ue=z$1.object({id:z$1.string().optional(),type:z$1.literal("SYNC"),resource:z$1.string(),resourceId:z$1.string(),op:z$1.enum(["INSERT","UPDATE","DELETE"]),payload:Tt,meta:Le}),le=(c,e)=>{c.op==="DELETE"&&Object.keys(c.payload).length>0&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"DELETE delta payload must be empty"});};ue.superRefine(le);var Qe=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var De=H.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:H.shape.meta});var ye=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(ye);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,n]of Object.entries(c))e[t]=ye(n);return e}return c},_e=c=>{let e=c.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,o={headers:r,cookies:r.cookie?Ne.default.parse(r.cookie):{}},a=new URL(t.url),s=a.pathname.split("/"),i=a.searchParams,d=ye(wt.parse(i.toString())),u=await((n=c.contextProvider)==null?void 0:n.call(c,{transport:"HTTP",headers:o.headers,cookies:o.cookies,queryParams:d}))??{};if(t.method==="POST")try{let l=s[s.length-1],f=s[s.length-2];if(f==="query"){if(s.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let S=s[s.length-3],C=t.body?await t.json():{};if(!S||S.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let E=await c.handleCustomQuery({req:{...o,type:"CUSTOM_QUERY",resource:S,procedure:l,input:C.input,context:u,queryParams:d}});return Response.json(E)}let y=f,p=t.body?await t.json():{},{success:h,data:m,error:g}=De.safeParse(p);if(!h)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:g},{status:400});let w=m,x=await c.handleMutation({req:{...o,type:"MUTATE",resource:y,input:w.payload,context:u,resourceId:w.resourceId,procedure:l,queryParams:{},meta:w.meta}});return Response.json(x)}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(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var Fe=b(ce(),1);var k=z$1.string(),fe=Qe,bt=z$1.object({id:k,type:z$1.literal("SUBSCRIBE")}).and(fe),Rt=z$1.object({id:k,type:z$1.literal("UNSUBSCRIBE")}).and(fe),xt=z$1.object({id:k,type:z$1.literal("QUERY")}).and(fe),vt=z$1.object({id:k,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),It=H.extend({id:k}),Ct=It,$e=z$1.union([bt,xt,vt,Ct,Rt]),Ot=z$1.object({id:k,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),jt=z$1.object({id:k,type:z$1.literal("REPLY"),data:z$1.any()}),Mt=ue.extend({id:k}).superRefine(le);z$1.union([Ot,jt,Mt]);z$1.object({resource:z$1.string(),data:z$1.array(de)});var qe=c=>{let e={},t=c.logger;return (n,r)=>{var l;let o=f=>{n.send(JSON.stringify(f));},a=Y(),s=new Map,i={headers:r.headers,cookies:typeof r.headers.cookie=="string"?Fe.default.parse(r.headers.cookie):{}},d=parse(r.url.split("?")[1]),u=(l=c.contextProvider)==null?void 0:l.call(c,{transport:"WEBSOCKET",headers:i.headers,cookies:i.cookies,queryParams:d});e[a]=n,t.info("Client connected:",a),n.on("message",async f=>{try{t.debug("Message received from the client:",f);let y=$e.parse(JSON.parse(f.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:p,id:h,...m}=y,g=p==="SUBSCRIBE";try{let w=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:m.resource,procedure:m.procedure,input:m.input,context:await u??{},queryParams:d},subscription:g?x=>{var S;!x.resourceId||!x.payload||!Object.keys(x.payload).length||(S=e[a])==null||S.send(JSON.stringify(x));}:void 0});if(g){if(!w||!w.data||!w.query)throw new Error("Cannot subscribe to a one-shot query: the procedure must return a query builder (a Tracked Query), not a computed value");w.unsubscribe&&s.set(B$1(m),w.unsubscribe),o({id:h,type:"REPLY",data:{resource:w.query.resource,data:(w.data??[]).map(x=>x.value)}});}else o({id:h,type:"REPLY",data:w});}catch(w){o({id:h,type:"REJECT",resource:m.resource,message:w.message}),t.error("Error handling query from the client:",w);}}else if(y.type==="UNSUBSCRIBE"){let{type:p,id:h,...m}=y,g=s.get(B$1(m));g&&(g(),s.delete(B$1(m)));}else if(y.type==="CUSTOM_QUERY"){let{resource:p,procedure:h,input:m,id:g}=y;t.debug("Received custom query from client:",y);try{let w=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:p,procedure:h,input:m,context:await u??{},queryParams:d}});o({id:g,type:"REPLY",data:w});}catch(w){o({id:g,type:"REJECT",resource:p,message:w.message}),t.error("Error handling custom query from the client:",w);}}else if(y.type==="MUTATE"){let{resource:p}=y;t.debug("Received mutation from client:",y);try{let h=await c.handleMutation({req:{...i,type:"MUTATE",resource:p,input:y.payload,context:{messageId:y.id,...await u??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:d,meta:y.meta}});o({id:y.id,type:"REPLY",data:h});}catch(h){o({id:y.id,type:"REJECT",resource:p,message:h.message}),t.error("Error parsing mutation from the client:",h);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",a),delete e[a];for(let f of Array.from(s.values()))f();});}};function Be(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var qn=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,qe(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{_e(e)(Be(n)).then(a=>a.json().then(s=>r.status(a.status).send(s)));});};var V=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,o,a,s,i){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=o,this._single=a,this._sort=s,this._shouldAwait=i,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new c(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new c(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new c(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 c(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new c(this._collection,this._client,this._where,this._include,this._limit,this._single,n,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(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,n){return new c(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var At=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),pe=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>At(n)?z$2(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function U(c,e,t){let n=new pe(c),r=a=>{let s=V._init(a,n,true);return Object.assign(Object.create(s),{insert:async d=>{let u=c._getTimestamp(),l=await c.rawInsert(a.name,d.id,{value:Object.fromEntries(Object.entries(d).map(([f,y])=>[f,{value:y,_meta:{timestamp:u}}]))},void 0,t);return z$2(l.data)},update:async(d,u)=>{let l=c._getTimestamp(),{id:f,...y}=u,p=await c.rawUpdate(a.name,d,{value:Object.fromEntries(Object.entries(y).map(([g,w])=>[g,{value:w,_meta:{timestamp:l}}]))},void 0,t),h=z$2(p.data),m={};for(let g of Object.keys(y))g in h&&(m[g]=h[g]);return m}})},o={get(a,s){if(s==="findOne")return c.findOne.bind(c);if(s==="find")return c.find.bind(c);if(s==="insert")return (i,d)=>{let u=c._getTimestamp();return c.rawInsert(i.name,d.id,{value:Object.fromEntries(Object.entries(d).map(([l,f])=>[l,{value:f,_meta:{timestamp:u}}]))},void 0,t).then(l=>z$2(l.data))};if(s==="update")return (i,d,u)=>{let l=c._getTimestamp(),{id:f,...y}=u;return c.rawUpdate(i.name,d,{value:Object.fromEntries(Object.entries(y).map(([p,h])=>[p,{value:h,_meta:{timestamp:l}}]))},void 0,t).then(p=>{let h=z$2(p.data),m={};for(let g of Object.keys(y))g in h&&(m[g]=h[g]);return m})};if(s==="transaction")return async i=>c.transaction(async({trx:d,commit:u,rollback:l})=>{let f=U(d,e,t);return i({trx:f,commit:u,rollback:l})});if(s in e){let i=e[s];return r(i)}}};return new Proxy({},o)}var he=class c{routes;schema;constructor(e){this.routes=e.routes,this.schema=e.schema;}static create(e){return new c(e)}},Jn=c=>he.create(c),Pt=(c=>({handler:e=>({_type:"query",inputValidator:c??z$1.undefined(),handler:e})})),kt=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z$1.undefined(),handler:e})})),me=class{middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:n})=>{var a;let r=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let i=this.customMutations[s.procedure];if(i){let d=i.inputValidator["~standard"].validate(s.input),u=d instanceof Promise?await d:d;if(u.issues){let f=u.issues.map(y=>{var h;let p=(h=y.path)==null?void 0:h.map(m=>typeof m=="object"&&"key"in m?String(m.key):String(m)).join(".");return p?`${p}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${f}`)}s.input=u.value;let l=U(o,n,s.context);return i.handler({req:s,db:l})}throw new Error(`Unknown procedure: ${s.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{let o=this.customQueries[r.procedure];if(!o)throw new Error(`Unknown query procedure: ${r.procedure}`);let a=o.inputValidator["~standard"].validate(r.input),s=a instanceof Promise?await a:a;if(s.issues){let d=s.issues.map(u=>{var f;let l=(f=u.path)==null?void 0:f.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${u.message}`:u.message}).join(", ");throw new Error(`Validation failed: ${d}`)}r.input=s.value;let i=U(t,n,r.context);return o.handler({req:r,db:i})})(e);wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}};function Zn(c){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>c({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var ge=class c{middlewares;constructor(e=[]){this.middlewares=e;}withProcedures(e){let t=e({mutation:kt,query:Pt}),n={},r={};for(let[o,a]of Object.entries(t))a._type==="mutation"?n[o]=a:r[o]=a;return new me(n,r).use(...this.middlewares)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new c([...this.middlewares,...t])}static create(){return new c}},Gn=ge.create;var z=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([o,a])=>[o,{value:a,_meta:{timestamp:n}}]))});return z$2(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:o,...a}=n,s=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,{value:l,_meta:{timestamp:r}}]))}),i=z$2(s.data),d={};for(let u of Object.keys(a))u in i&&(d[u]=i[u]);return d}};var Ft={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function P(c){var r,o,a;let e=(r=c.getExecutor)==null?void 0:r.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((a=(o=t.constructor)==null?void 0:o.name)==null?void 0:a.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function He(c){let e=P(c);return Ft[e]}var qt="42701";function K(c){var t;if(c.code===qt)return true;let e=((t=c.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function Se(c,e){let{type:t,enumValues:n,enumName:r}=c;if(n&&n.length>0)return e==="postgres"&&r?r:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function Bt(c,e,t,n){if(t!=="postgres")return;let r=new Map;for(let o of Object.values(e))for(let a of Object.values(o.fields)){let s=a.getStorageFieldType();s.enumValues&&s.enumName&&r.set(s.enumName,{name:s.enumName,values:s.enumValues});}for(let o of Array.from(r.values())){let{name:a,values:s}=o;try{let i=s.map(d=>`'${d}'`).join(", ");await sql`
1
+ import {a,b,z as z$2,G as G$1,F as F$1,B,E,C,D}from'./chunk-3XEJ2M4E.js';import Y from'crypto';import vt,{parse}from'qs';import {z as z$1}from'zod';import {Kysely,PostgresDialect,sql}from'kysely';import {jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from'kysely/helpers/mysql';import {jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from'kysely/helpers/postgres';import {jsonArrayFrom,jsonObjectFrom}from'kysely/helpers/sqlite';var ye=a(ie=>{Object.defineProperty(ie,"__esModule",{value:true});ie.parse=Tt;ie.serialize=St;var yt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ft=/^[\u0021-\u003A\u003C-\u007E]*$/,ht=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,pt=/^[\u0020-\u003A\u003D-\u007E]*$/,mt=Object.prototype.toString,gt=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function Tt(c,e){let t=new gt,n=c.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||wt,s=0;do{let o=c.indexOf("=",s);if(o===-1)break;let a=c.indexOf(";",s),i=a===-1?n:a;if(o>i){s=c.lastIndexOf(";",o-1)+1;continue}let d=Qe(c,s,o),l=_e(c,o,d),u=c.slice(d,l);if(t[u]===void 0){let y=Qe(c,o+1,i),f=_e(c,i,y),h=r(c.slice(y,f));t[u]=h;}s=i+1;}while(s<n);return t}function Qe(c,e,t){do{let n=c.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function _e(c,e,t){for(;e>t;){let n=c.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function St(c,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!yt.test(c))throw new TypeError(`argument name is invalid: ${c}`);let r=n(e);if(!ft.test(r))throw new TypeError(`argument val is invalid: ${e}`);let s=c+"="+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(!ht.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain;}if(t.path){if(!pt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path;}if(t.expires){if(!xt(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 wt(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function xt(c){return mt.call(c)==="[object Date]"}});var Le="0123456789ABCDEFGHJKMNPQRSTVWXYZ",W=32;var tt=16,ke=10,je=0xffffffffffff;var Q;(function(c){c.Base32IncorrectEncoding="B32_ENC_INVALID",c.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",c.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",c.EncodeTimeNegative="ENC_TIME_NEG",c.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",c.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",c.PRNGDetectFailure="PRNG_DETECT",c.ULIDInvalid="ULID_INVALID",c.Unexpected="UNEXPECTED",c.UUIDInvalid="UUID_INVALID";})(Q||(Q={}));var _=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function nt(c){let e=Math.floor(c()*W);return e===W&&(e=W-1),Le.charAt(e)}function rt(c){var n;let e=it(),t=e&&(e.crypto||e.msCrypto)||(typeof Y<"u"?Y: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=Y)!=null&&n.randomBytes)return ()=>Y.randomBytes(1).readUInt8()/255;throw new _(Q.PRNGDetectFailure,"Failed to find a reliable PRNG")}function it(){return at()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function st(c,e){let t="";for(;c>0;c--)t=nt(e)+t;return t}function ot(c,e=ke){if(isNaN(c))throw new _(Q.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>je)throw new _(Q.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${je}: ${c}`);if(c<0)throw new _(Q.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new _(Q.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,n="";for(let r=e;r>0;r--)t=c%W,n=Le.charAt(t)+n,c=(c-t)/W;return n}function at(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function De(c,e){let t=rt(),n=Date.now();return ot(n,ke)+st(tt,t)}var ee=()=>De().toLowerCase(),X=c=>({then(e,t){try{if(e){let n=e(c);return n instanceof Promise?n:X(n)}return X(c)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:X(r)}throw n}}}),$=c=>c instanceof Promise?c:X(c);function H(c,e){let t=new Map,n=c[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}function F(c,e,t,n){let r=c[e];if(!(r!=null&&r.relations))return;let s=r.relations[n];if(!s)return;let o=c[t];if(o!=null&&o.relations){if(s.type==="many"&&s.foreignColumn){for(let[a,i]of Object.entries(o.relations))if(i.entity.name===e&&i.type==="one"&&i.relationalColumn===s.foreignColumn)return a}if(s.type==="one"&&s.relationalColumn){for(let[a,i]of Object.entries(o.relations))if(i.entity.name===e&&i.type==="many"&&i.foreignColumn===s.relationalColumn)return a}}}var te=new Set,ne=class{schema;nodes=new Map;constructor(e){this.schema=e;}ensureNode(e){let t=this.nodes.get(e);return t||(t={matchedQueries:new Set,references:new Map,referencedBy:new Map},this.nodes.set(e,t)),t}link(e,t,n,r){if(this.ensureNode(e).references.set(n,t),!r)return;let s=this.ensureNode(t),o=s.referencedBy.get(r);o||(o=new Set,s.referencedBy.set(r,o)),o.add(e);}unlink(e,t,n,r){var o,a,i;if((o=this.nodes.get(e))==null||o.references.delete(n),!r)return;let s=(a=this.nodes.get(t))==null?void 0:a.referencedBy.get(r);s&&(s.delete(e),s.size===0&&((i=this.nodes.get(t))==null||i.referencedBy.delete(r)));}ingest(e,t){let n=t==null?void 0:t.id;if(n){this.ensureNode(n);for(let[r,{relationName:s,targetResource:o}]of Array.from(H(this.schema,e))){let a=t[r];a&&this.link(n,a,s,F(this.schema,e,o,s));}this.ingestNested(e,n,t);}}ingestNested(e,t,n){var s;let r=(s=this.schema[e])==null?void 0:s.relations;if(r)for(let[o,a]of Object.entries(r)){let i=n[o];if(!i)continue;let d=a.entity.name;if(a.type==="one")typeof i=="object"&&i.id&&(this.link(t,i.id,o,F(this.schema,e,d,o)),this.ingestNested(d,i.id,i));else if(a.type==="many"&&Array.isArray(i)){let l=F(this.schema,d,e,o);for(let u of i)u&&typeof u=="object"&&u.id&&(this.ensureNode(u.id),l&&this.link(u.id,t,l,o),this.ingestNested(d,u.id,u));}}}applyWrite(e,t,n,r){var s;this.ensureNode(t);for(let[o,{relationName:a,targetResource:i}]of Array.from(H(this.schema,e))){if(r&&!(o in r))continue;let d=F(this.schema,e,i,a),l=(s=this.nodes.get(t))==null?void 0:s.references.get(a),u=n==null?void 0:n[o];l!==u&&(l&&this.unlink(t,l,a,d),u&&this.link(t,u,a,d));}}setMatched(e,t){this.ensureNode(e).matchedQueries.add(t);}clearMatched(e,t){var n;(n=this.nodes.get(e))==null||n.matchedQueries.delete(t);}matches(e,t){var n;return ((n=this.nodes.get(e))==null?void 0:n.matchedQueries.has(t))??false}matchedQueriesOf(e){var t;return ((t=this.nodes.get(e))==null?void 0:t.matchedQueries)??te}reference(e,t,n){var o,a,i;let r=(a=(o=this.schema[t])==null?void 0:o.relations)==null?void 0:a[n];if(!r)return;let s=F(this.schema,t,r.entity.name,n);if(s)return (i=this.nodes.get(e))==null?void 0:i.references.get(s)}referencedBy(e,t,n){var o,a,i;let r=(a=(o=this.schema[t])==null?void 0:o.relations)==null?void 0:a[n];if(!r)return te;let s=F(this.schema,t,r.entity.name,n);return s?((i=this.nodes.get(e))==null?void 0:i.referencedBy.get(s))??te:te}has(e){return this.nodes.has(e)}};function ue(c){return B({resource:c.query.resource,where:c.query.where,include:c.query.include,stepPath:c.stepPath,isMany:c.isMany,relationName:c.relationName})}function ct(c,e){let t=c==null,n=e==null;if(t&&n)return 0;if(t)return -1;if(n)return 1;if(typeof c=="number"&&typeof e=="number")return c-e;if(typeof c=="boolean"&&typeof e=="boolean")return Number(c)-Number(e);let r=String(c),s=String(e);return r<s?-1:r>s?1:0}var V=class{limit;directions;entries=[];index=new Map;constructor(e){if(!Number.isInteger(e.limit)||e.limit<0)throw new Error("WindowIndex limit must be a non-negative integer");this.limit=e.limit,this.directions=(e.orderBy??[]).map(t=>t.direction);}get size(){return this.entries.length}get isFull(){return this.entries.length>=this.limit}compare(e,t){for(let n=0;n<this.directions.length;n++){let r=ct(e.sortKey[n],t.sortKey[n]);if(r!==0)return this.directions[n]==="desc"?-r:r}return e.id<t.id?-1:e.id>t.id?1:0}lowerBound(e){let t=0,n=this.entries.length;for(;t<n;){let r=t+n>>>1;this.compare(this.entries[r],e)<0?t=r+1:n=r;}return t}insert(e){if(this.limit===0)return {inserted:false};if(this.index.has(e.id))throw new Error(`WindowIndex already contains id "${e.id}"`);let t=this.lowerBound(e);if(this.isFull&&t>=this.limit)return {inserted:false};if(this.entries.splice(t,0,e),this.index.set(e.id,e),this.entries.length>this.limit){let n=this.entries.pop();if(n)return this.index.delete(n.id),{inserted:true,evicted:n}}return {inserted:true}}remove(e){let t=this.index.get(e);if(!t)return;let n=this.lowerBound(t);return this.entries.splice(n,1),this.index.delete(e),t}has(e){return this.index.has(e)}position(e){let t=this.index.get(e);if(t)return this.lowerBound(t)}boundary(){return this.entries[this.entries.length-1]}needsBackfill(){return this.entries.length<this.limit}get backfillCount(){return Math.max(0,this.limit-this.entries.length)}snapshot(){return this.entries.map(e=>({id:e.id,sortKey:[...e.sortKey]}))}ids(){return this.entries.map(e=>e.id)}};var re=class{storage;schema;logger;queryNodes=new Map;graph;constructor(e){this.storage=e.storage,this.schema=e.schema,this.logger=e.logger,this.graph=new ne(e.schema);}get(e,t){let n=this.addedSortRelations(e.resource,e.sort,e.include),r={...e.include??{}};for(let o of n)r[o]=true;let s={...e,...e.limit!==void 0?{sort:[...e.sort??[],{key:"id",direction:"asc"}]}:{},...Object.keys(r).length>0?{include:this.prepareResolveInclude(r,e.resource)}:{}};return $(this.storage.get(s)).then(o=>(this.ingest(e,o),this.stripResolveRelations(o,e.resource,e.include,e.sort),o))}addedSortRelations(e,t,n){var s,o;let r=[];for(let a of t??[]){let i=a.key.indexOf(".");if(i===-1)continue;let d=a.key.slice(0,i);(o=(s=this.schema[e])==null?void 0:s.relations)!=null&&o[d]&&(n&&d in n||r.includes(d)||r.push(d));}return r}stripResolveRelations(e,t,n,r){var o,a,i;let s=this.addedSortRelations(t,r,n);if(s.length>0)for(let d of e){let l=d==null?void 0:d.value;if(l)for(let u of s)delete l[u];}if(n)for(let[d,l]of Object.entries(n)){let u=(a=(o=this.schema[t])==null?void 0:o.relations)==null?void 0:a[d],y=u==null?void 0:u.entity.name;if(!y)continue;let f=E(l)?l:null,h=f?f.include:l&&typeof l=="object"?l:void 0,p=f==null?void 0:f.orderBy;for(let m of e){let g=(i=m==null?void 0:m.value)==null?void 0:i[d];if(!g)continue;let w=u.type==="many"?Array.isArray(g.value)?g.value:[]:[g];this.stripResolveRelations(w,y,h,p);}}}relationalSortDeps(e){var r,s;let t=[],n=e.sort??[];for(let o=0;o<n.length;o++){let a=n[o].key.indexOf(".");if(a===-1)continue;let i=n[o].key.slice(0,a),d=n[o].key.slice(a+1),l=(s=(r=this.schema[e.resource])==null?void 0:r.relations)==null?void 0:s[i];l&&t.push({index:o,relationName:i,field:d,targetResource:l.entity.name});}return t}sortRelationInclude(e){let t=this.relationalSortDeps(e.queryStep.query);if(t.length===0)return;let n={};for(let r of t)n[r.relationName]=true;return n}relationalSortFkColumns(e){let t=new Set,n=this.relationalSortDeps(e.queryStep.query);if(n.length===0)return t;let r=H(this.schema,e.queryStep.query.resource);for(let[s,{relationName:o}]of Array.from(r))n.some(a=>a.relationName===o)&&t.add(s);return t}ownWriteTouchesSortRelationFk(e,t){if(!t)return false;for(let n of Array.from(this.relationalSortFkColumns(e)))if(n in t)return true;return false}async resolveSortRelations(e,t,n){let r=this.sortRelationInclude(e);if(!r)return n;let s=await $(this.storage.get({resource:e.queryStep.query.resource,where:{id:t},include:r})),o=s[0]?z$2(s[0]):void 0;if(!o||typeof o!="object")return n;for(let a of Object.keys(r))a in o||(o[a]=void 0);return o}stripPayloadRelations(e,t){if(t)for(let n of Object.keys(t))delete e[n];return e}prepareResolveInclude(e,t){var r,s,o;let n={};for(let[a,i]of Object.entries(e)){let d=(o=(s=(r=this.schema[t])==null?void 0:r.relations)==null?void 0:s[a])==null?void 0:o.entity.name;if(E(i)){let l=i.limit!==void 0,u={...i.include??{}};if(l&&d)for(let f of this.addedSortRelations(d,i.orderBy,i.include))u[f]=true;let y=d&&Object.keys(u).length>0?this.prepareResolveInclude(u,d):i.include;n[a]={...i,...y!==void 0?{include:y}:{},...l?{orderBy:[...i.orderBy??[],{key:"id",direction:"asc"}]}:{}};}else i&&typeof i=="object"&&d?n[a]=this.prepareResolveInclude(i,d):n[a]=i;}return n}ingest(e,t){for(let n of this.buildSteps({query:e})){let r=n.stepPath.length===0?t:this.extractByPath(t,e.resource,n.stepPath);this.trackObjects(n,r);}}extractByPath(e,t,n){var o,a,i;let r=e,s=t;for(let d of n){let l=(a=(o=this.schema[s])==null?void 0:o.relations)==null?void 0:a[d],u=(l==null?void 0:l.type)==="many",y=[];for(let f of r){let h=(i=f==null?void 0:f.value)==null?void 0:i[d];if(h)if(u){if(Array.isArray(h.value))for(let p of h.value)p&&y.push(p);}else h.value!=null&&y.push(h);}r=y,l&&(s=l.entity.name);}return r}subscribe(e,t,n={}){let r=this.buildSteps({query:e}),s={},o=[];for(let a of r){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let i=ue(a),d=s[a.stepPath.at(-2)??""],l=a.stepPath.at(-1)??"",u=this.queryNodes.get(i);if(u)u.subscriptions.add(t);else {let y=a.stepPath.length===0&&a.query.limit!==void 0;if(u={hash:i,queryStep:a,relationName:l,subscriptions:new Set([t]),parentQuery:d,childQueries:new Set,windowIndex:y?new V({limit:a.query.limit,orderBy:this.orderByFor(a.query)}):void 0},this.queryNodes.set(u.hash,u),d){let f=this.queryNodes.get(d);f&&f.childQueries.add(u.hash);}}s[l]=i,o.push(()=>{let y=this.queryNodes.get(i);y&&(y.subscriptions.delete(t),y.subscriptions.size===0&&this.queryNodes.delete(i));});}return ()=>{for(let a of o)a();}}buildSteps(e){var f,h;let{query:t,stepPath:n=[],parentResource:r}=e,{include:s}=t,o=n.length===0,a=n.at(-1),i;if(!o&&r&&a){let p=(h=(f=this.schema[r])==null?void 0:f.relations)==null?void 0:h[a];p&&(i=p.type==="many");}let{include:d,...l}=t,y=[{query:l,stepPath:[...n],includedRelations:s&&typeof s=="object"?Object.keys(s):[],isMany:i,relationName:a}];if(s&&typeof s=="object"&&Object.keys(s).length>0){let p=this.schema[t.resource];if(!p)throw new Error(`Resource ${t.resource} not found`);y.push(...Object.entries(s).flatMap(([m,g])=>{let w=p.relations[m];if(!w)throw new Error(`Relation ${m} not found for resource ${t.resource}`);let b=w.entity.name,S=E(g)?g:null;return this.buildSteps({query:{resource:b,include:S?S.include:typeof g=="object"?g:void 0,where:S==null?void 0:S.where,limit:S==null?void 0:S.limit,sort:S==null?void 0:S.orderBy},stepPath:[...n,m],parentResource:t.resource})}));}return y}trackObjects(e,t){var a;this.logger.debug("[QueryEngine] Tracking step objects",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=ue(e),r=this.queryNodes.get(n),s=e.query.resource;if(!r)return;for(let i of t){let d=z$2(i);this.graph.ingest(s,d),this.graph.setMatched(d.id,n),this.logger.debug("[QueryEngine] Loaded nested relations for",d.id);}if(r.windowIndex&&!r.windowInitialized){for(let i of t){let d=z$2(i);!(d!=null&&d.id)||r.windowIndex.has(d.id)||r.windowIndex.insert({id:d.id,sortKey:this.sortKeyFor(r,d)});}r.windowInitialized=true;}let o=this.includeForeignColumn(r);if(o){r.seededParents??=new Set;for(let i of t){let d=z$2(i),l=d==null?void 0:d.id,u=d==null?void 0:d[o];if(!l||u==null||r.seededParents.has(u))continue;let y=this.ensureParentWindow(r,u);y.has(l)||y.insert({id:l,sortKey:this.sortKeyFor(r,d)});}for(let i of t){let d=(a=z$2(i))==null?void 0:a[o];d!=null&&r.seededParents.add(d);}}}orderByFor(e){return (e.sort??[]).map(t=>({key:t.key,direction:t.direction}))}sortKeyFor(e,t,n){return (e.queryStep.query.sort??[]).map((r,s)=>{let o=r.key.indexOf(".");if(o===-1)return t==null?void 0:t[r.key];let a=r.key.slice(0,o),i=r.key.slice(o+1),d=t==null?void 0:t[a];if(d&&typeof d=="object"&&i in d)return d[i];if(!(t&&typeof t=="object"&&a in t))return n==null?void 0:n[s]})}storageSortFor(e){return [...e.queryStep.query.sort??[],{key:"id",direction:"asc"}]}includeForeignColumn(e){var s,o;if(e.queryStep.stepPath.length===0||e.queryStep.query.limit===void 0||!e.relationName||!e.parentQuery)return;let t=this.queryNodes.get(e.parentQuery),n=t==null?void 0:t.queryStep.query.resource;if(!n)return;let r=(o=(s=this.schema[n])==null?void 0:s.relations)==null?void 0:o[e.relationName];if(!((r==null?void 0:r.type)!=="many"||!r.foreignColumn))return String(r.foreignColumn)}isWindowedIncludeNode(e){return this.includeForeignColumn(e)!==void 0}ensureParentWindow(e,t){e.windowIndexes||(e.windowIndexes=new Map);let n=e.windowIndexes.get(t);return n||(n=new V({limit:e.queryStep.query.limit,orderBy:this.orderByFor(e.queryStep.query)}),e.windowIndexes.set(t,n)),n}parentWindowHolding(e,t){if(e.windowIndexes){for(let[n,r]of Array.from(e.windowIndexes))if(r.has(t))return {parentId:n,wi:r}}}emitToSubscribers(e,t,n){for(let r of Array.from(e.subscriptions))try{r(t);}catch(s){this.logger.error(`[QueryEngine] Error in subscription during ${n}`,{error:s,queryHash:e.hash,resource:t.resource,resourceId:t.resourceId});}}emitScopeOut(e,t,n){this.graph.clearMatched(t,e.hash),this.emitToSubscribers(e,{type:"SYNC",op:"DELETE",resource:e.queryStep.query.resource,resourceId:t,payload:{},meta:n},"scope-out DELETE");}handleWindowedInsert(e,t,n,r){let s=t.insert({id:n.resourceId,sortKey:this.sortKeyFor(e,r)});s.inserted&&(this.graph.setMatched(n.resourceId,e.hash),this.emitToSubscribers(e,n,"windowed scope-in INSERT"),s.evicted&&this.emitScopeOut(e,s.evicted.id,n.meta));}async handleWindowedUpdate(e,t,n,r,s){let o=e.windowIndex;if(!o)return;let a=t.resourceId,i=o.has(a);if(s&&(!i||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,a,r)),s){if(i){await this.refreshInWindow(e,o,t,r);return}this.scopeInViaUpdate(e,o,t,n,r);return}i&&(o.remove(a),this.emitScopeOut(e,a,t.meta),await this.backfillWindow(e,o,t.meta));}async refreshInWindow(e,t,n,r,s){var d,l;let o=n.resourceId,a=(d=t.remove(o))==null?void 0:d.sortKey,i=this.sortKeyFor(e,r,a);if(t.insert({id:o,sortKey:i}),t.isFull&&((l=t.boundary())==null?void 0:l.id)===o&&!this.sortKeysEqual(a,i)){await this.reconcileDemotion(e,t,o,i,n,s);return}this.emitToSubscribers(e,n,"windowed UPDATE");}scopeInViaUpdate(e,t,n,r,s){let o=n.resourceId,a=t.insert({id:o,sortKey:this.sortKeyFor(e,s)});a.inserted&&(this.graph.setMatched(o,e.hash),this.emitToSubscribers(e,this.fullInsertDelta(e,n,r),"windowed scope-in INSERT"),a.evicted&&this.emitScopeOut(e,a.evicted.id,n.meta));}async handleWindowedIncludeUpdate(e,t,n,r,s){let o=this.includeForeignColumn(e);if(!o)return;let a=t.resourceId,i=s?r[o]:void 0,d=this.parentWindowHolding(e,a),l=d==null?void 0:d.parentId,u=l!==void 0&&l===i;if((i!==void 0&&!u||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,a,r)),u){await this.refreshInWindow(e,d.wi,t,r,{column:o,parentId:l});return}if(d&&(d.wi.remove(a),this.emitScopeOut(e,a,t.meta),await this.backfillWindow(e,d.wi,t.meta,{column:o,parentId:d.parentId})),i!==void 0){let y=this.ensureParentWindow(e,i);y.has(a)||this.scopeInViaUpdate(e,y,t,n,r);}}async handleRelationalSortFanout(e,t){if(e.payload)for(let n of Array.from(this.queryNodes.values())){let r=this.relationalSortDeps(n.queryStep.query);if(r.length===0)continue;let s=!!n.windowIndex,o=this.isWindowedIncludeNode(n);if(!s&&!o)continue;let a=false;for(let i of r){if(i.targetResource!==e.resource||!(i.field in e.payload))continue;a=true;let d=t==null?void 0:t[i.field],l=this.graph.referencedBy(e.resourceId,n.queryStep.query.resource,i.relationName);if(l.size!==0)for(let u of Array.from(l))if(s){let y=n.windowIndex;if(!y.has(u))continue;this.repositionForRelationalChange(y,u,i.index,d);}else {let y=this.parentWindowHolding(n,u);if(!y)continue;this.repositionForRelationalChange(y.wi,u,i.index,d);}}if(a){if(s)n.windowInitialized&&await this.reconcilePromotions(n,n.windowIndex,e);else if(n.windowIndexes){let i=this.includeForeignColumn(n);for(let[d,l]of Array.from(n.windowIndexes))await this.reconcilePromotions(n,l,e,{column:i,parentId:d});}}}}repositionForRelationalChange(e,t,n,r){let s=e.remove(t);if(!s)return;let o=[...s.sortKey];o[n]=r,e.insert({id:t,sortKey:o});}async reconcilePromotions(e,t,n,r){let s=e.queryStep.query.limit;if(s===void 0)return;let o=e.queryStep.query.resource,a=this.sortRelationInclude(e),i=e.queryStep.query.where;r&&(i=this.combineWhere(i,{[r.column]:r.parentId}));let l=(await $(this.storage.get({resource:o,where:i,sort:this.storageSortFor(e),limit:s,include:a}))).map(y=>({row:y,value:z$2(y)})).filter(y=>{var f;return !!((f=y.value)!=null&&f.id)}),u=new Set(l.map(y=>y.value.id));for(let y of t.ids())u.has(y)||(t.remove(y),this.emitScopeOut(e,y,n.meta));for(let{row:y,value:f}of l){let h=this.sortKeyFor(e,f);if(t.has(f.id)){t.remove(f.id),t.insert({id:f.id,sortKey:h});continue}let p=t.insert({id:f.id,sortKey:h});if(!p.inserted)continue;this.graph.setMatched(f.id,e.hash),this.graph.ingest(o,f);let m=this.stripPayloadRelations({...(y==null?void 0:y.value)??{}},a);delete m.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:o,resourceId:f.id,payload:m,meta:n.meta},"windowed relational promotion INSERT"),p.evicted&&this.emitScopeOut(e,p.evicted.id,n.meta);}}sortKeysEqual(e,t){if(!e||e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return false;return true}async reconcileDemotion(e,t,n,r,s,o){t.remove(n);let a=e.queryStep.query.resource,i=this.windowReadWhere(e,t,o),d=this.sortRelationInclude(e),l=await $(this.storage.get({resource:a,where:i,sort:this.storageSortFor(e),limit:2,include:d})),u,y;for(let h of l){let p=z$2(h);if(!(!(p!=null&&p.id)||p.id===n||t.has(p.id))){u=p,y=h;break}}if(!u){t.insert({id:n,sortKey:r}),this.emitToSubscribers(e,s,"windowed UPDATE");return}if(t.insert({id:u.id,sortKey:this.sortKeyFor(e,u)}),t.insert({id:n,sortKey:r}).inserted){this.emitToSubscribers(e,s,"windowed UPDATE");return}this.graph.setMatched(u.id,e.hash);let f=this.stripPayloadRelations({...(y==null?void 0:y.value)??{}},d);delete f.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:a,resourceId:u.id,payload:f,meta:s.meta},"windowed demotion backfill INSERT"),this.emitScopeOut(e,n,s.meta);}fullInsertDelta(e,t,n){let r={...(n==null?void 0:n.value)??{}};return delete r.id,{type:"SYNC",op:"INSERT",resource:e.queryStep.query.resource,resourceId:t.resourceId,payload:r,meta:t.meta}}async backfillWindow(e,t,n,r){let s=t.backfillCount;if(s<=0)return;let o=e.queryStep.query.resource,a=this.windowReadWhere(e,t,r),i=this.sortRelationInclude(e),d=await $(this.storage.get({resource:o,where:a,sort:this.storageSortFor(e),limit:s,include:i}));for(let l of d){let u=z$2(l);if(!(u!=null&&u.id)||t.has(u.id))continue;t.insert({id:u.id,sortKey:this.sortKeyFor(e,u)}),this.graph.setMatched(u.id,e.hash);let y=this.stripPayloadRelations({...(l==null?void 0:l.value)??{}},i);delete y.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:o,resourceId:u.id,payload:y,meta:n},"windowed backfill INSERT");}}buildCursorWhere(e,t){if(!t)return;let n=[...e.queryStep.query.sort??[],{key:"id",direction:"asc"}],r=[...t.sortKey,t.id],s=[];for(let o=0;o<n.length;o++){let a=[];for(let d=0;d<o;d++)a.push(this.cursorCond(n[d].key,r[d]));let i=n[o].direction==="desc"?"$lt":"$gt";a.push(this.cursorCond(n[o].key,{[i]:r[o]})),s.push(a.length===1?a[0]:{$and:a});}return s.length===1?s[0]:{$or:s}}cursorCond(e,t){let n=e.indexOf(".");return n===-1?{[e]:t}:{[e.slice(0,n)]:{[e.slice(n+1)]:t}}}windowReadWhere(e,t,n){let r=e.queryStep.query.where;return n&&(r=this.combineWhere(r,{[n.column]:n.parentId})),this.combineWhere(r,this.buildCursorWhere(e,t.boundary()))}combineWhere(e,t){return t?!e||Object.keys(e).length===0?t:{$and:[e,t]}:e}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,r){var a,i;let s=(i=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:i.value;if(!s)return;let o={op:"INSERT",resource:n,resourceId:s,type:"SYNC",payload:t.value,meta:r};for(let d of Array.from(e.subscriptions))try{d(o);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:n,resourceId:s,stepPath:e.queryStep.stepPath.join(".")});}this.graph.setMatched(s,e.hash);for(let d of Array.from(e.childQueries)){let l=this.queryNodes.get(d);if(!l||!l.relationName)continue;let u=l.relationName,y=l.queryStep.query.resource,f=t.value[u];if(!f)continue;let h=f.value;if(Array.isArray(h))for(let p of h)this.sendInsertsForTree(l,p,y,r);else h&&typeof h=="object"&&this.sendInsertsForTree(l,h,y,r);}}handleMutation(e,t){if(e.op==="INSERT"){if(this.graph.has(e.resourceId))return;let n=z$2(t);if(!n)return;this.graph.applyWrite(e.resource,e.resourceId,n),this.getMatchingQueries(e,n).then(async r=>{try{for(let s of r){let o=this.queryNodes.get(s);if(!o)continue;if(o.windowIndex){let i=await this.resolveSortRelations(o,e.resourceId,n);this.handleWindowedInsert(o,o.windowIndex,e,i);continue}let a=this.includeForeignColumn(o);if(a){let i=n[a];if(i!=null){let d=await this.resolveSortRelations(o,e.resourceId,n);this.handleWindowedInsert(o,this.ensureParentWindow(o,i),e,d);}continue}this.graph.setMatched(e.resourceId,s);for(let i of Array.from(o.subscriptions))try{i(e);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:d,queryHash:o.hash,resource:e.resource,resourceId:e.resourceId,stepPath:o.queryStep.stepPath.join(".")});}}}catch(s){this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:s,resource:e.resource,resourceId:e.resourceId});}},r=>{this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:r,resource:e.resource,resourceId:e.resourceId});});return}if(e.op==="UPDATE"){let n=z$2(t);if(!n)return;let r=new Set(this.graph.matchedQueriesOf(e.resourceId));this.graph.applyWrite(e.resource,e.resourceId,n,e.payload),this.handleRelationalSortFanout(e,n).catch(s=>{this.logger.error("[QueryEngine] Error during relational sort fan-out",{error:s,resource:e.resource,resourceId:e.resourceId});}),this.getMatchingQueries(e,n).then(async s=>{let o=new Set(s),a=new Set;for(let u of Array.from(this.queryNodes.values()))u.queryStep.query.resource===e.resource&&(u.windowIndex?(a.add(u.hash),await this.handleWindowedUpdate(u,e,t,n,o.has(u.hash))):this.isWindowedIncludeNode(u)&&(a.add(u.hash),await this.handleWindowedIncludeUpdate(u,e,t,n,o.has(u.hash))));let i=[],d=[],l=[];for(let u of s)a.has(u)||(r.has(u)?l.push(u):i.push(u));for(let u of Array.from(r))a.has(u)||o.has(u)||d.push(u);for(let u of i)this.graph.setMatched(e.resourceId,u);for(let u of d)this.graph.clearMatched(e.resourceId,u);for(let u of [...d,...l]){let y=this.queryNodes.get(u);if(y)for(let f of Array.from(y.subscriptions))try{f(e);}catch(h){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:h,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(i.length>0)for(let u of i){let y=this.queryNodes.get(u);if(!y)continue;let f=this.buildIncludeFromChildQueries(u);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(h=>{!h||h.length===0||this.sendInsertsForTree(y,h[0],e.resource,e.meta);});}});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?$([]):Promise.all(n.map(async r=>{let s=r.queryStep.query.where,o=r.queryStep.query.resource,a=e.resourceId;if(!this.graph.has(a))return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=y==null?void 0:y.queryStep.query.resource,h=f?this.graph.reference(a,f,r.relationName):void 0;if(!h)return {hash:r.hash,matches:false};if(!y||!this.graph.matches(h,y.hash))return {hash:r.hash,matches:false}}if(!s)return {hash:r.hash,matches:true};let i=C(s,o,this.schema),d=Object.keys(i).length>0;if(!d&&t!==void 0)return {hash:r.hash,matches:D(t,s)};let l=await this.storage.get({resource:o,where:{id:a},include:d?i:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let u=z$2(l[0]);return u?{hash:r.hash,matches:D(u,s)}:{hash:r.hash,matches:false}})).then(r=>r.filter(s=>s.matches).map(s=>s.hash))}};var bn=c=>c,dt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],ut=c=>c.length===1?c[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let s of c){let o=await s({...e,value:n,rawValue:t});o&&(t=o,n=z$2(t),n.id=e.value.id,r=true);}return r?t:void 0}),lt=c=>c.length===1?c[0]:(async e=>{for(let t of c)await t(e);}),le=c=>{let e=c.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of dt){let r=e.map(s=>s[n]).filter(s=>s!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=lt(r):t[n]=ut(r));}return t},vn=(...c)=>{let e={},t=new Set;for(let n of c)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=c.map(o=>o[n]),s=le(r);s&&(e[n]=s);}return e};var Ne=b(ye(),1);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(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()});var fe=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()})),Rt=fe.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),bt=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),$e=z$1.object({timestamp:z$1.string().optional(),originMutationId:z$1.string().optional()}).optional(),U=bt.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:$e}),he=z$1.object({id:z$1.string().optional(),type:z$1.literal("SYNC"),resource:z$1.string(),resourceId:z$1.string(),op:z$1.enum(["INSERT","UPDATE","DELETE"]),payload:Rt,meta:$e}),pe=(c,e)=>{c.op==="DELETE"&&Object.keys(c.payload).length>0&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"DELETE delta payload must be empty"});};he.superRefine(pe);var Fe=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var qe=U.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:U.shape.meta});var me=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(me);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,n]of Object.entries(c))e[t]=me(n);return e}return c},Be=c=>{let e=c.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?Ne.default.parse(r.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),i=o.searchParams,d=me(vt.parse(i.toString())),l=await((n=c.contextProvider)==null?void 0:n.call(c,{transport:"HTTP",headers:s.headers,cookies:s.cookies,queryParams:d}))??{};if(t.method==="POST")try{let u=a[a.length-1],y=a[a.length-2];if(y==="query"){if(a.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let S=a[a.length-3],C=t.body?await t.json():{};if(!S||S.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let A=await c.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:S,procedure:u,input:C.input,context:l,queryParams:d}});return Response.json(A)}let f=y,h=t.body?await t.json():{},{success:p,data:m,error:g}=qe.safeParse(h);if(!p)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:g},{status:400});let w=m,b=await c.handleMutation({req:{...s,type:"MUTATE",resource:f,input:w.payload,context:l,resourceId:w.resourceId,procedure:u,queryParams:{},meta:w.meta}});return Response.json(b)}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 He=b(ye(),1);var L=z$1.string(),ge=Fe,It=z$1.object({id:L,type:z$1.literal("SUBSCRIBE")}).and(ge),Ct=z$1.object({id:L,type:z$1.literal("UNSUBSCRIBE")}).and(ge),Mt=z$1.object({id:L,type:z$1.literal("QUERY")}).and(ge),Et=z$1.object({id:L,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),Ot=U.extend({id:L}),At=Ot,We=z$1.union([It,Mt,Et,At,Ct]),Pt=z$1.object({id:L,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),jt=z$1.object({id:L,type:z$1.literal("REPLY"),data:z$1.any()}),Lt=he.extend({id:L}).superRefine(pe);z$1.union([Pt,jt,Lt]);z$1.object({resource:z$1.string(),data:z$1.array(fe)});var Ve=c=>{let e={},t=c.logger;return (n,r)=>{var u;let s=y=>{n.send(JSON.stringify(y));},o=ee(),a=new Map,i={headers:r.headers,cookies:typeof r.headers.cookie=="string"?He.default.parse(r.headers.cookie):{}},d=parse(r.url.split("?")[1]),l=(u=c.contextProvider)==null?void 0:u.call(c,{transport:"WEBSOCKET",headers:i.headers,cookies:i.cookies,queryParams:d});e[o]=n,t.info("Client connected:",o),n.on("message",async y=>{try{t.debug("Message received from the client:",y);let f=We.parse(JSON.parse(y.toString()));if(f.type==="SUBSCRIBE"||f.type==="QUERY"){let{type:h,id:p,...m}=f,g=h==="SUBSCRIBE";try{let w=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:m.resource,procedure:m.procedure,input:m.input,context:await l??{},queryParams:d},subscription:g?b=>{var S;!b.resourceId||!b.payload||!Object.keys(b.payload).length||(S=e[o])==null||S.send(JSON.stringify(b));}:void 0});if(g){if(!w||!w.data||!w.query)throw new Error("Cannot subscribe to a one-shot query: the procedure must return a query builder (a Tracked Query), not a computed value");w.unsubscribe&&a.set(B(m),w.unsubscribe),s({id:p,type:"REPLY",data:{resource:w.query.resource,data:(w.data??[]).map(b=>b.value)}});}else s({id:p,type:"REPLY",data:w});}catch(w){s({id:p,type:"REJECT",resource:m.resource,message:w.message}),t.error("Error handling query from the client:",w);}}else if(f.type==="UNSUBSCRIBE"){let{type:h,id:p,...m}=f,g=a.get(B(m));g&&(g(),a.delete(B(m)));}else if(f.type==="CUSTOM_QUERY"){let{resource:h,procedure:p,input:m,id:g}=f;t.debug("Received custom query from client:",f);try{let w=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:h,procedure:p,input:m,context:await l??{},queryParams:d}});s({id:g,type:"REPLY",data:w});}catch(w){s({id:g,type:"REJECT",resource:h,message:w.message}),t.error("Error handling custom query from the client:",w);}}else if(f.type==="MUTATE"){let{resource:h}=f;t.debug("Received mutation from client:",f);try{let p=await c.handleMutation({req:{...i,type:"MUTATE",resource:h,input:f.payload,context:{messageId:f.id,...await l??{}},resourceId:f.resourceId,procedure:f.procedure,queryParams:d,meta:f.meta}});s({id:f.id,type:"REPLY",data:p});}catch(p){s({id:f.id,type:"REJECT",resource:h,message:p.message}),t.error("Error parsing mutation from the client:",p);}}}catch(f){t.error("Error handling message from the client:",f);}}),n.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let y of Array.from(a.values()))y();});}};function Ue(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var Zn=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Ve(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{Be(e)(Ue(n)).then(o=>o.json().then(a=>r.status(o.status).send(a)));});};var z=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,s,o,a,i){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=s,this._single=o,this._sort=a,this._shouldAwait=i,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new c(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new c(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new c(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 c(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new c(this._collection,this._client,this._where,this._include,this._limit,this._single,n,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(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,n){return new c(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var Dt=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),Te=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>Dt(n)?z$2(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function K(c,e,t){let n=new Te(c),r=o=>{let a=z._init(o,n,true);return Object.assign(Object.create(a),{insert:async d=>{let l=c._getTimestamp(),u=await c.rawInsert(o.name,d.id,{value:Object.fromEntries(Object.entries(d).map(([y,f])=>[y,{value:f,_meta:{timestamp:l}}]))},void 0,t);return z$2(u.data)},update:async(d,l)=>{let u=c._getTimestamp(),{id:y,...f}=l,h=await c.rawUpdate(o.name,d,{value:Object.fromEntries(Object.entries(f).map(([g,w])=>[g,{value:w,_meta:{timestamp:u}}]))},void 0,t),p=z$2(h.data),m={};for(let g of Object.keys(f))g in p&&(m[g]=p[g]);return m}})},s={get(o,a){if(a==="findOne")return c.findOne.bind(c);if(a==="find")return c.find.bind(c);if(a==="insert")return (i,d)=>{let l=c._getTimestamp();return c.rawInsert(i.name,d.id,{value:Object.fromEntries(Object.entries(d).map(([u,y])=>[u,{value:y,_meta:{timestamp:l}}]))},void 0,t).then(u=>z$2(u.data))};if(a==="update")return (i,d,l)=>{let u=c._getTimestamp(),{id:y,...f}=l;return c.rawUpdate(i.name,d,{value:Object.fromEntries(Object.entries(f).map(([h,p])=>[h,{value:p,_meta:{timestamp:u}}]))},void 0,t).then(h=>{let p=z$2(h.data),m={};for(let g of Object.keys(f))g in p&&(m[g]=p[g]);return m})};if(a==="transaction")return async i=>c.transaction(async({trx:d,commit:l,rollback:u})=>{let y=K(d,e,t);return i({trx:y,commit:l,rollback:u})});if(a in e){let i=e[a];return r(i)}}};return new Proxy({},s)}var Se=class c{routes;schema;constructor(e){this.routes=e.routes,this.schema=e.schema;}static create(e){return new c(e)}},ir=c=>Se.create(c),Qt=(c=>({handler:e=>({_type:"query",inputValidator:c??z$1.undefined(),handler:e})})),_t=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z$1.undefined(),handler:e})})),we=class{middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:n})=>{var o;let r=((o=e.meta)==null?void 0:o.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(r);return await this.wrapInMiddlewares(async a=>{if(!a.procedure)throw new Error("Procedure is required for mutations");let i=this.customMutations[a.procedure];if(i){let d=i.inputValidator["~standard"].validate(a.input),l=d instanceof Promise?await d:d;if(l.issues){let y=l.issues.map(f=>{var p;let h=(p=f.path)==null?void 0:p.map(m=>typeof m=="object"&&"key"in m?String(m.key):String(m)).join(".");return h?`${h}: ${f.message}`:f.message}).join(", ");throw new Error(`Validation failed: ${y}`)}a.input=l.value;let u=K(s,n,a.context);return i.handler({req:a,db:u})}throw new Error(`Unknown procedure: ${a.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{let s=this.customQueries[r.procedure];if(!s)throw new Error(`Unknown query procedure: ${r.procedure}`);let o=s.inputValidator["~standard"].validate(r.input),a=o instanceof Promise?await o:o;if(a.issues){let d=a.issues.map(l=>{var y;let u=(y=l.path)==null?void 0:y.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return u?`${u}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${d}`)}r.input=a.value;let i=K(t,n,r.context);return s.handler({req:r,db:i})})(e);wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>s=>r({req:s,next:n}),e)(t)}};function sr(c){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>c({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var xe=class c{middlewares;constructor(e=[]){this.middlewares=e;}withProcedures(e){let t=e({mutation:_t,query:Qt}),n={},r={};for(let[s,o]of Object.entries(t))o._type==="mutation"?n[s]=o:r[s]=o;return new we(n,r).use(...this.middlewares)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new c([...this.middlewares,...t])}static create(){return new c}},or=xe.create;var J=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([s,o])=>[s,{value:o,_meta:{timestamp:n}}]))});return z$2(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:s,...o}=n,a=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([l,u])=>[l,{value:u,_meta:{timestamp:r}}]))}),i=z$2(a.data),d={};for(let l of Object.keys(o))l in i&&(d[l]=i[l]);return d}};var Ht={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function j(c){var r,s,o;let e=(r=c.getExecutor)==null?void 0:r.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((o=(s=t.constructor)==null?void 0:s.name)==null?void 0:o.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function Ke(c){let e=j(c);return Ht[e]}var Vt="42701";function Z(c){var t;if(c.code===Vt)return true;let e=((t=c.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function be(c,e){let{type:t,enumValues:n,enumName:r}=c;if(n&&n.length>0)return e==="postgres"&&r?r:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function Ut(c,e,t,n){if(t!=="postgres")return;let r=new Map;for(let s of Object.values(e))for(let o of Object.values(s.fields)){let a=o.getStorageFieldType();a.enumValues&&a.enumName&&r.set(a.enumName,{name:a.enumName,values:a.enumValues});}for(let s of Array.from(r.values())){let{name:o,values:a}=s;try{let i=a.map(d=>`'${d}'`).join(", ");await sql`
2
2
  DO $$ BEGIN
3
- CREATE TYPE ${sql.id(a)} AS ENUM (${sql.raw(i)});
3
+ CREATE TYPE ${sql.id(o)} AS ENUM (${sql.raw(i)});
4
4
  EXCEPTION
5
5
  WHEN duplicate_object THEN null;
6
6
  END $$;
7
- `.execute(c);}catch(i){n==null||n.warn("Could not create enum type",a,i);}}}function J(c,e){return c.some(t=>t.name===e)}function Wt(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function we(c,e){let[t]=e.split(".");return J(c,t)}function Te(c,e,t,n=false){let r=c;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&we(t,e.references)&&(r=r.references(e.references)),r}function Ht(c,e,t,n,r){let o=[];for(let[a,s]of Object.entries(c.fields)){let i=e==null?void 0:e.columns.find(u=>u.name===a),d=s.getStorageFieldType();i?(i.dataType,d.type):(o.push({name:a,storageFieldType:d}),d.references&&!we(t,d.references)&&n.push({tableName:r,columnName:a,references:d.references}));}return o}function Ve(c,e){return e==="postgres"&&!!c.enumValues&&c.enumValues.length>0&&!!c.enumName}async function Vt(c,e,t,n,r,o){if(t.length===0)return;let a=c.schema.createTable(e);for(let{name:s,storageFieldType:i}of t)if(Ve(i,r))a=a.addColumn(s,sql.raw(i.enumName),d=>Te(d,i,n));else {let d=Se(i,r);a=a.addColumn(s,d,u=>Te(u,i,n));}await a.execute().catch(s=>{if(!K(s))throw o==null||o.error("Error creating table",e,s),s});}async function Ut(c,e,t,n,r,o,a){for(let{name:s,storageFieldType:i}of t){let d=i.references?we(n,i.references):false,u=Ve(i,o)?sql.raw(i.enumName):Se(i,o);await c.schema.alterTable(e).addColumn(s,u,l=>Te(l,i,n,!d)).execute().catch(l=>{if(!K(l))throw a==null||a.error("Error adding column",s,l),l}),i.references&&!d&&!r.some(l=>l.tableName===e&&l.columnName===s)&&r.push({tableName:e,columnName:s,references:i.references}),i.index&&await c.schema.createIndex(`${e}_${s}_index`).on(e).column(s).execute().catch(()=>{});}}async function zt(c,e,t,n,r,o){let a=`${e}_meta`,s=[];for(let[i,d]of Object.entries(t.fields)){let u=d.getStorageFieldType();Wt(n,i)||s.push({name:i,storageFieldType:u});}if(!n&&s.length>0){let i=c.schema.createTable(a);for(let{name:d,storageFieldType:u}of s)i=i.addColumn(d,"varchar",l=>{let f=l;return u.primary&&(f=f.primaryKey(),J(r,e)&&(f=f.references(`${e}.${d}`))),f});await i.execute().catch(d=>{if(!K(d))throw o==null||o.error("Error creating meta table",a,d),d});}else if(n)for(let{name:i,storageFieldType:d}of s)await c.schema.alterTable(a).addColumn(i,"varchar",u=>{let l=u;return d.primary&&(l=l.primaryKey(),J(r,e)&&(l=l.references(`${e}.${i}`))),l}).execute().catch(u=>{if(!K(u))throw o==null||o.error("Error adding meta column",i,u),u});}async function Ue(c,e,t,n,r){let[o,a]=n.split("."),s=`${e}_${t}_fk`;try{await sql`
7
+ `.execute(c);}catch(i){n==null||n.warn("Could not create enum type",o,i);}}}function G(c,e){return c.some(t=>t.name===e)}function zt(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function ve(c,e){let[t]=e.split(".");return G(c,t)}function Re(c,e,t,n=false){let r=c;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&ve(t,e.references)&&(r=r.references(e.references)),r}function Kt(c,e,t,n,r){let s=[];for(let[o,a]of Object.entries(c.fields)){let i=e==null?void 0:e.columns.find(l=>l.name===o),d=a.getStorageFieldType();i?(i.dataType,d.type):(s.push({name:o,storageFieldType:d}),d.references&&!ve(t,d.references)&&n.push({tableName:r,columnName:o,references:d.references}));}return s}function Je(c,e){return e==="postgres"&&!!c.enumValues&&c.enumValues.length>0&&!!c.enumName}async function Jt(c,e,t,n,r,s){if(t.length===0)return;let o=c.schema.createTable(e);for(let{name:a,storageFieldType:i}of t)if(Je(i,r))o=o.addColumn(a,sql.raw(i.enumName),d=>Re(d,i,n));else {let d=be(i,r);o=o.addColumn(a,d,l=>Re(l,i,n));}await o.execute().catch(a=>{if(!Z(a))throw s==null||s.error("Error creating table",e,a),a});}async function Zt(c,e,t,n,r,s,o){for(let{name:a,storageFieldType:i}of t){let d=i.references?ve(n,i.references):false,l=Je(i,s)?sql.raw(i.enumName):be(i,s);await c.schema.alterTable(e).addColumn(a,l,u=>Re(u,i,n,!d)).execute().catch(u=>{if(!Z(u))throw o==null||o.error("Error adding column",a,u),u}),i.references&&!d&&!r.some(u=>u.tableName===e&&u.columnName===a)&&r.push({tableName:e,columnName:a,references:i.references}),i.index&&await c.schema.createIndex(`${e}_${a}_index`).on(e).column(a).execute().catch(()=>{});}}async function Gt(c,e,t,n,r,s){let o=`${e}_meta`,a=[];for(let[i,d]of Object.entries(t.fields)){let l=d.getStorageFieldType();zt(n,i)||a.push({name:i,storageFieldType:l});}if(!n&&a.length>0){let i=c.schema.createTable(o);for(let{name:d,storageFieldType:l}of a)i=i.addColumn(d,"varchar",u=>{let y=u;return l.primary&&(y=y.primaryKey(),G(r,e)&&(y=y.references(`${e}.${d}`))),y});await i.execute().catch(d=>{if(!Z(d))throw s==null||s.error("Error creating meta table",o,d),d});}else if(n)for(let{name:i,storageFieldType:d}of a)await c.schema.alterTable(o).addColumn(i,"varchar",l=>{let u=l;return d.primary&&(u=u.primaryKey(),G(r,e)&&(u=u.references(`${e}.${i}`))),u}).execute().catch(l=>{if(!Z(l))throw s==null||s.error("Error adding meta column",i,l),l});}async function Ze(c,e,t,n,r){let[s,o]=n.split("."),a=`${e}_${t}_fk`;try{await sql`
8
8
  ALTER TABLE ${sql.id(e)}
9
- ADD CONSTRAINT ${sql.id(s)}
9
+ ADD CONSTRAINT ${sql.id(a)}
10
10
  FOREIGN KEY (${sql.id(t)})
11
- REFERENCES ${sql.id(o)} (${sql.id(a)})
12
- `.execute(c);}catch(i){K(i)||r==null||r.warn("Could not add foreign key constraint",e,t,n,i);}}async function Kt(c,e,t,n){for(let{tableName:r,columnName:o,references:a}of e){let s=t.find(u=>u.name===r),i=s==null?void 0:s.columns.find(u=>u.name===o),[d]=a.split(".");s&&i&&J(t,d)&&await Ue(c,r,o,a,n);}}async function Jt(c,e,t,n){for(let[r,o]of Object.entries(e)){let a=`${r}_meta`,s=t.find(i=>i.name===a);if(s)for(let[i,d]of Object.entries(o.fields)){let u=d.getStorageFieldType(),l=s.columns.find(f=>f.name===i);u.primary&&l&&J(t,r)&&await Ue(c,a,i,`${r}.${i}`,n);}}}async function ze(c,e,t){let n=P(c),r=await c.introspection.getTables(),o=[];await Bt(c,e,n,t);for(let[s,i]of Object.entries(e)){let d=r.find(f=>f.name===s),u=r.find(f=>f.name===`${s}_meta`),l=Ht(i,d,r,o,s);if(d)for(let[f,y]of Object.entries(i.fields)){let p=d.columns.find(g=>g.name===f),h=y.getStorageFieldType(),m=Se(h,n);p&&p.dataType!==m&&(t==null||t.warn("Column type mismatch:",f,"expected to have type:",m,"but has type:",p.dataType));}!d&&l.length>0?await Vt(c,s,l,r,n,t):d&&await Ut(c,s,l,r,o,n,t),await zt(c,s,i,u,r,t);}let a=await c.introspection.getTables();await Kt(c,o,a,t),await Jt(c,e,a,t);}function te(c,e,t,n){if(!c)throw new Error("Schema not initialized");let r=c[e];if(!r)throw new Error("Resource not found");let o=n.$or,a=n.$and;return (o?t.or:t.and)(o?n.$or.map(s=>te(c,e,t,s)):a?n.$and.map(s=>te(c,e,t,s)):Object.entries(n).map(([s,i])=>{var d,u;if(r.fields[s])return (i==null?void 0:i.$eq)!==void 0?t(`${e}.${s}`,i.$eq===null?"is":"=",i.$eq):(i==null?void 0:i.$in)!==void 0?t(`${e}.${s}`,"in",i.$in):(i==null?void 0:i.$not)!==void 0?((d=i==null?void 0:i.$not)==null?void 0:d.$in)!==void 0?t(`${e}.${s}`,"not in",i.$not.$in):((u=i==null?void 0:i.$not)==null?void 0:u.$eq)!==void 0?t(`${e}.${s}`,i.$not.$eq===null?"is not":"!=",i.$not.$eq):t(`${e}.${s}`,i.$not===null?"is not":"!=",i.$not):(i==null?void 0:i.$gt)!==void 0?t(`${e}.${s}`,">",i.$gt):(i==null?void 0:i.$gte)!==void 0?t(`${e}.${s}`,">=",i.$gte):(i==null?void 0:i.$lt)!==void 0?t(`${e}.${s}`,"<",i.$lt):(i==null?void 0:i.$lte)!==void 0?t(`${e}.${s}`,"<=",i.$lte):t(`${e}.${s}`,i===null?"is":"=",i);if(r.relations[s]){let l=r.relations[s],f=l.entity.name;return l.type==="many"?t.exists(re(c,f,t.selectFrom(f).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),i)):te(c,f,t,i)}return null}).filter(Boolean))}function ne(c,e,t,n,r=new Set){let o=c[e];if(!o)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let a of n.$and)t=ne(c,e,t,a,r);return t}else if(n.$or){for(let a of n.$or)t=ne(c,e,t,a,r);return t}for(let[a,s]of Object.entries(n)){if(!o.relations[a])continue;let i=o.relations[a],d=i.entity.name,u=i.type==="one"?"id":i.foreignColumn,l=i.type==="one"?i.relationalColumn:"id";r.has(d)||(r.add(d),t=t.leftJoin(d,`${d}.${u}`,`${e}.${l}`)),s instanceof Object&&!Array.isArray(s)&&s!==null&&(t=ne(c,d,t,s,r));}return t}function re(c,e,t,n){return !n||Object.keys(n).length===0?t:(t=ne(c,e,t,n),t.where(r=>te(c,e,r,n)))}function Zt(c,e,t,n,r){let o=P(r),a=e[t];if(o==="sqlite"&&(a!=null&&a.fields)){let s=Object.keys(a.fields),i=c.selectFrom(n);for(let d of s)i=i.select(`${n}.${d}`);return i}return c.selectFrom(n).selectAll(n)}function Gt(c,e,t,n,r){let o=P(r),a=e[t];if(o==="sqlite"&&(a!=null&&a.fields)){let s=Object.keys(a.fields),i=c.selectFrom(n);for(let d of s)i=i.select(`${n}.${d}`);return i}return c.selectFrom(n).selectAll(n)}function be(c,e,t,n){var r,o;for(let a of n){let s=a.key.indexOf(".");if(s!==-1){let i=a.key.slice(0,s),d=a.key.slice(s+1),u=(o=(r=c==null?void 0:c[e])==null?void 0:r.relations)==null?void 0:o[i];if((u==null?void 0:u.type)==="one"&&u.relationalColumn){let l=u.entity.name,f=String(u.relationalColumn);t=t.orderBy(y=>y.selectFrom(l).select(`${l}.${d}`).whereRef(`${l}.id`,"=",`${e}.${f}`),a.direction);continue}if(u)throw new Error(`Relational sort on "${a.key}" is only supported for "one" relations with a relationalColumn`)}t=t.orderBy(a.key,a.direction);}return t}function ie(c,e,t,n,r,o){if(!n)return t;if(!c)throw new Error("Schema not initialized");let a=c[e];if(!a)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:s,jsonArrayFrom:i}=r;for(let d of Object.keys(n)){if(!a.relations[d])throw new Error(`Relation ${d} not found in resource ${e}`);let u=a.relations[d],l=u.entity.name,f=n[d],y=u.type==="one"?"id":u.foreignColumn,p=u.type==="one"?u.relationalColumn:"id",h=u.type==="one"?s:i,m=E(f)?f:null,g=m?m.include:f&&typeof f=="object"?f:void 0;t=t.select(w=>{let x=`${l}_meta`,S=Gt(w,c,l,l,o).whereRef(`${l}.${y}`,"=",`${e}.${p}`).select(C=>s(Zt(C,c,l,x,o).whereRef(`${x}.id`,"=",`${l}.id`)).as("_meta"));return m!=null&&m.where&&(S=re(c,l,S,m.where)),m!=null&&m.orderBy&&(S=be(c,l,S,m.orderBy)),(m==null?void 0:m.limit)!==void 0&&(S=S.limit(m.limit)),g&&Object.keys(g).length>0&&(S=ie(c,l,S,g,r,o)),h(S).as(d)});}return t}var Re=class c extends z{db;dialectHelpers;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.dialectHelpers=He(this.db),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){this.schema=e,this.logger=t,this.server=n,await ze(this.db,e,t);}selectMetaColumns(e,t,n){var a;let r=P(this.db),o=(a=this.schema)==null?void 0:a[t];if(r==="sqlite"&&(o!=null&&o.fields)){let s=Object.keys(o.fields),i=e.selectFrom(n);for(let d of s)i=i.select(`${n}.${d}`);return i}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,o=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(i=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(i,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));o=ie(this.schema,e,o,n,this.dialectHelpers,this.db);let a=await o.executeTakeFirst();if(!a)return;let s=this.parseRelationalJsonStrings(a,e);return this.convertToMaterializedLiveType(s,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return z$2(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:o,sort:a}=e,s=`${t}_meta`,i=this.db.selectFrom(t).selectAll(t).select(u=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(u,t,s).whereRef(`${s}.id`,"=",`${t}.id`)).as("_meta"));i=re(this.schema,t,i,n),i=ie(this.schema,t,i,r,this.dialectHelpers,this.db),o!==void 0&&(i=i.limit(o)),a!==void 0&&(i=be(this.schema,t,i,a));let d=await i.execute();return d.length===0?[]:d.map(u=>{let l=this.parseRelationalJsonStrings(u,t);return this.convertToMaterializedLiveType(l,t)})}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=>z$2(r))}async rawInsert(e,t,n,r,o){var h,m,g,w,x,S,C,E,L,Q,q;let a=(h=this.server)==null?void 0:h.getHooks(e),s=(m=this.schema)==null?void 0:m[e],[i,d]=((g=s==null?void 0:s.mergeMutation)==null?void 0:g.call(s,"set",n.value,void 0))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let u=i,l={...u,value:{...u.value,id:{value:t}}};if(a!=null&&a.beforeInsert){let O=z$2(l);O.id=t;let R=await a.beforeInsert({ctx:o,value:O,rawValue:l,db:this});R&&(u=R);}let f={},y={};for(let[O,R]of Object.entries(u.value)){let j=(w=R._meta)==null?void 0:w.timestamp;if(!j)continue;let I=(S=(x=s==null?void 0:s.fields[O])==null?void 0:x.getStorageFieldType)==null?void 0:S.call(x);(I==null?void 0:I.type)==="jsonb"||(I==null?void 0:I.type)==="json"?f[O]=JSON.stringify(R.value):f[O]=R.value,y[O]=j;}await this.db.insertInto(e).values({...f,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute(),(E=(C=this.logger)==null?void 0:C.debug)==null||E.call(C,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(o==null?void 0:o.messageId)??"(none)",hasContext:!!o,contextKeys:o?Object.keys(o):[]});let p=this.buildMutation(e,t,"INSERT",u,r,o==null?void 0:o.messageId);if(p&&((q=(L=this.logger)==null?void 0:L.debug)==null||q.call(L,"[rawInsert] Mutation built, tracking",{mutationId:p.id,hasMeta:!!p.meta,originMutationId:((Q=p.meta)==null?void 0:Q.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(p,u)),a!=null&&a.afterInsert){let O={...u,value:{...u.value,id:{value:t}}},R=z$2(O);R.id=t,await a.afterInsert({ctx:o,value:R,rawValue:O,db:this});}return {data:u,acceptedValues:d}}async rawUpdate(e,t,n,r,o){var m,g,w,x,S,C,E,L,Q,q,O;let a=(m=this.server)==null?void 0:m.getHooks(e),s=(g=this.schema)==null?void 0:g[e],i=await this.rawFindById(e,t),[d,u]=((w=s==null?void 0:s.mergeMutation)==null?void 0:w.call(s,"set",n.value,i))??[n,n.value];if(!u)return {data:n,acceptedValues:null};let l=d,f={...l,value:{...l.value,id:{value:t}}};if(a!=null&&a.beforeUpdate){let R=z$2(f);R.id=t;let j;if(i){let M={...i,value:{...i.value,id:{value:t}}};j=z$2(M),j.id=t;}let I=await a.beforeUpdate({ctx:o,value:R,rawValue:f,previousValue:j,previousRawValue:i,db:this});I&&(l=I);}let y={},p={};for(let[R,j]of Object.entries(l.value)){let I=(x=j._meta)==null?void 0:x.timestamp;if(!I)continue;let M=(C=(S=s==null?void 0:s.fields[R])==null?void 0:S.getStorageFieldType)==null?void 0:C.call(S);(M==null?void 0:M.type)==="jsonb"||(M==null?void 0:M.type)==="json"?y[R]=JSON.stringify(j.value):y[R]=j.value,p[R]=I;}if(Object.keys(y).length===0)return {data:l,acceptedValues:u};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...p,id:t}).onConflict(R=>R.column("id").doUpdateSet(p)).execute()]),(L=(E=this.logger)==null?void 0:E.debug)==null||L.call(E,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(o==null?void 0:o.messageId)??"(none)",hasContext:!!o,contextKeys:o?Object.keys(o):[]});let h=this.buildMutation(e,t,"UPDATE",l,r,o==null?void 0:o.messageId);if(h){(O=(Q=this.logger)==null?void 0:Q.debug)==null||O.call(Q,"[rawUpdate] Mutation built, tracking",{mutationId:h.id,hasMeta:!!h.meta,originMutationId:((q=h.meta)==null?void 0:q.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let R=await this.rawFindById(e,t);R&&this.trackMutation(h,R);}if(a!=null&&a.afterUpdate){let R=await this.rawFindById(e,t);if(R){let j={...R,value:{...R.value,id:{value:t}}},I=z$2(j);I.id=t;let M;if(i){let Je={...i,value:{...i.value,id:{value:t}}};M=z$2(Je),M.id=t;}await a.afterUpdate({ctx:o,value:I,rawValue:j,previousValue:M,previousRawValue:i,db:this});}}return {data:l,acceptedValues:u}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let o=Math.random().toString(36).substring(2,15),a=this.mutationStack,s=[];this.mutationStack=s;let i=await this.db.savepoint(o).execute(),d=false,u=false;try{return await e({trx:this,commit:async()=>{await i.releaseSavepoint(o).execute(),d=!0,a.push(...s);},rollback:async()=>{await i.rollbackToSavepoint(o).execute(),u=!0,s.length=0;}}).then(l=>i.isCommitted||i.isRolledBack||d||u?l:i.releaseSavepoint(o).execute().then(()=>(a.push(...s),l)))}catch(l){throw u||await i.rollbackToSavepoint(o).execute().catch(()=>{}),s.length=0,l}finally{this.mutationStack=a;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let o=new c(r,this.schema,this.logger,this.server);return o.mutationStack=t,await e({trx:o,commit:async()=>{var a,s;await r.commit().execute(),(s=(a=this.logger)==null?void 0:a.debug)==null||s.call(a,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:i})=>{var d;return {id:i.id,resource:i.resource,resourceId:i.resourceId,op:i.op,hasMeta:!!i.meta,originMutationId:((d=i.meta)==null?void 0:d.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(a=>r.isCommitted||r.isRolledBack?a:r.commit().execute().then(()=>{var s,i;return (i=(s=this.logger)==null?void 0:s.debug)==null||i.call(s,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:d})=>{var u;return {id:d.id,resource:d.resource,resourceId:d.resourceId,op:d.op,hasMeta:!!d.meta,originMutationId:((u=d.meta)==null?void 0:u.originMutationId)??"(none)"}})}),this.notifyMutations(t),a}))}catch(o){throw await r.rollback().execute(),t.length=0,o}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var o,a;if(P(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(s=>this.parseRelationalJsonStrings(s,t));let r={};for(let[s,i]of Object.entries(e))if(s==="_meta"&&typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{r[s]=JSON.parse(i);}catch{r[s]=i;}else r[s]=i;else if(this.isRelationalField(t,s))if(typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let d=JSON.parse(i);if(this.schema){let u=this.schema[t],l=(o=u==null?void 0:u.relations)==null?void 0:o[s];if(l){let f=l.entity.name;r[s]=this.parseRelationalJsonStrings(d,f);}else r[s]=d;}else r[s]=d;}catch{r[s]=i;}else r[s]=i;else if(typeof i=="object"&&i!==null&&!Array.isArray(i))if(this.schema){let d=this.schema[t],u=(a=d==null?void 0:d.relations)==null?void 0:a[s];if(u){let l=u.entity.name;r[s]=this.parseRelationalJsonStrings(i,l);}else r[s]=i;}else r[s]=i;else Array.isArray(i)?r[s]=i.map(d=>{var u,l;if(typeof d=="string")try{let f=JSON.parse(d);if(this.schema){let y=this.schema[t],p=(u=y==null?void 0:y.relations)==null?void 0:u[s];if(p){let h=p.entity.name;return this.parseRelationalJsonStrings(f,h)}}return f}catch{return d}if(typeof d=="object"&&d!==null&&this.schema){let f=this.schema[t],y=(l=f==null?void 0:f.relations)==null?void 0:l[s];if(y){let p=y.entity.name;return this.parseRelationalJsonStrings(d,p)}}return d}):r[s]=i;else r[s]=i;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((o,[a,s])=>{var l,f,y,p,h,m,g,w,x;if(a==="_meta")return o;let i=(f=(l=n==null?void 0:n.fields[a])==null?void 0:l.getStorageFieldType)==null?void 0:f.call(l),d=(i==null?void 0:i.type)==="jsonb"||(i==null?void 0:i.type)==="json",u=(n==null?void 0:n.relations)&&a in n.relations;if(a==="id")o[a]={value:s};else if(d)o[a]={value:s,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[a]}};else if(u){let S=n.relations[a].entity,C=(S==null?void 0:S.name)??t;Array.isArray(s)?o[a]={value:s.map(E=>this.convertToMaterializedLiveType(E,C)),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[a],relation:true}}:s!==null&&typeof s=="object"?o[a]={...this.convertToMaterializedLiveType(s,C),_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[a],relation:true}}:o[a]={value:s,_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[a],relation:true}};}else Array.isArray(s)?o[a]={value:s,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[a]}}:typeof s=="object"&&s!==null&&!(s instanceof Date)?o[a]={value:s,_meta:{timestamp:(w=e==null?void 0:e._meta)==null?void 0:w[a]}}:o[a]={value:s,_meta:{timestamp:(x=e==null?void 0:e._meta)==null?void 0:x[a]}};return o},{})}}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",o=typeof t.savepoint=="function",a=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||o&&a}buildMutation(e,t,n,r,o,a){var i;let s={};for(let[d,u]of Object.entries(r.value)){if(d==="id")continue;let l=(i=u._meta)==null?void 0:i.timestamp;l&&(s[d]={value:u.value,_meta:{timestamp:l}});}return Object.keys(s).length===0?null:{id:o??Y(),type:"SYNC",resource:e,resourceId:t,op:n,payload:s,meta:a?{originMutationId:a}:void 0}}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:o}of n)this.server.notifySubscribers(r,o);}}};var xe=class c{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var t;if(this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=G$1({level:e.logLevel??F.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),e.hooks)for(let[n,r]of Object.entries(e.hooks)){let o=ae([r]);o&&this.hooksRegistry.set(n,o);}this.initPromise=this.storage.init(this.schema,this.logger,this).catch(n=>{this.initError=n;}),this.contextProvider=e.contextProvider,this.queryEngine=new X({storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleMutation(e){return await this.ensureInitialized(),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)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async f=>{let y=this.router.routes[f.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:f,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:r,cookies:o,queryParams:a,context:s}=e.req,i={headers:r,cookies:o,queryParams:a,context:s},d=t.buildQueryRequest(),u=e.subscription?this.queryEngine.subscribe(d,f=>{var y;(y=e.subscription)==null||y.call(e,f);},i):void 0,l=await this.queryEngine.get(d,{context:i});return e.subscription?{data:l,unsubscribe:u,query:d}:l.map(f=>z$2(f))}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)=>o=>r({req:o,next:n}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},jr=xe.create;export{V as QueryBuilder,me as Route,ge as RouteFactory,he as Router,Re as SQLStorage,xe as Server,z as Storage,Zn as createMiddleware,U as createServerDB,pn as defineHooks,qn as expressAdapter,ae as mergeEntityHooks,hn as mergeHooks,Gn as routeFactory,Jn as router,jr as server};
11
+ REFERENCES ${sql.id(s)} (${sql.id(o)})
12
+ `.execute(c);}catch(i){Z(i)||r==null||r.warn("Could not add foreign key constraint",e,t,n,i);}}async function Yt(c,e,t,n){for(let{tableName:r,columnName:s,references:o}of e){let a=t.find(l=>l.name===r),i=a==null?void 0:a.columns.find(l=>l.name===s),[d]=o.split(".");a&&i&&G(t,d)&&await Ze(c,r,s,o,n);}}async function Xt(c,e,t,n){for(let[r,s]of Object.entries(e)){let o=`${r}_meta`,a=t.find(i=>i.name===o);if(a)for(let[i,d]of Object.entries(s.fields)){let l=d.getStorageFieldType(),u=a.columns.find(y=>y.name===i);l.primary&&u&&G(t,r)&&await Ze(c,o,i,`${r}.${i}`,n);}}}async function Ge(c,e,t){let n=j(c),r=await c.introspection.getTables(),s=[];await Ut(c,e,n,t);for(let[a,i]of Object.entries(e)){let d=r.find(y=>y.name===a),l=r.find(y=>y.name===`${a}_meta`),u=Kt(i,d,r,s,a);if(d)for(let[y,f]of Object.entries(i.fields)){let h=d.columns.find(g=>g.name===y),p=f.getStorageFieldType(),m=be(p,n);h&&h.dataType!==m&&(t==null||t.warn("Column type mismatch:",y,"expected to have type:",m,"but has type:",h.dataType));}!d&&u.length>0?await Jt(c,a,u,r,n,t):d&&await Zt(c,a,u,r,s,n,t),await Gt(c,a,i,l,r,t);}let o=await c.introspection.getTables();await Yt(c,s,o,t),await Xt(c,e,o,t);}function se(c,e,t,n){if(!c)throw new Error("Schema not initialized");let r=c[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=>se(c,e,t,a)):o?n.$and.map(a=>se(c,e,t,a)):Object.entries(n).map(([a,i])=>{var d,l;if(r.fields[a])return (i==null?void 0:i.$eq)!==void 0?t(`${e}.${a}`,i.$eq===null?"is":"=",i.$eq):(i==null?void 0:i.$in)!==void 0?t(`${e}.${a}`,"in",i.$in):(i==null?void 0:i.$not)!==void 0?((d=i==null?void 0:i.$not)==null?void 0:d.$in)!==void 0?t(`${e}.${a}`,"not in",i.$not.$in):((l=i==null?void 0:i.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${a}`,i.$not.$eq===null?"is not":"!=",i.$not.$eq):t(`${e}.${a}`,i.$not===null?"is not":"!=",i.$not):(i==null?void 0:i.$gt)!==void 0?t(`${e}.${a}`,">",i.$gt):(i==null?void 0:i.$gte)!==void 0?t(`${e}.${a}`,">=",i.$gte):(i==null?void 0:i.$lt)!==void 0?t(`${e}.${a}`,"<",i.$lt):(i==null?void 0:i.$lte)!==void 0?t(`${e}.${a}`,"<=",i.$lte):t(`${e}.${a}`,i===null?"is":"=",i);if(r.relations[a]){let u=r.relations[a],y=u.entity.name;return u.type==="many"?t.exists(ae(c,y,t.selectFrom(y).select("id").whereRef(u.foreignColumn,"=",`${e}.id`),i)):se(c,y,t,i)}return null}).filter(Boolean))}function oe(c,e,t,n,r=new Set){let s=c[e];if(!s)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let o of n.$and)t=oe(c,e,t,o,r);return t}else if(n.$or){for(let o of n.$or)t=oe(c,e,t,o,r);return t}for(let[o,a]of Object.entries(n)){if(!s.relations[o])continue;let i=s.relations[o],d=i.entity.name,l=i.type==="one"?"id":i.foreignColumn,u=i.type==="one"?i.relationalColumn:"id";r.has(d)||(r.add(d),t=t.leftJoin(d,`${d}.${l}`,`${e}.${u}`)),a instanceof Object&&!Array.isArray(a)&&a!==null&&(t=oe(c,d,t,a,r));}return t}function ae(c,e,t,n){return !n||Object.keys(n).length===0?t:(t=oe(c,e,t,n),t.where(r=>se(c,e,r,n)))}function en(c,e,t,n,r){let s=j(r),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(n);for(let d of a)i=i.select(`${n}.${d}`);return i}return c.selectFrom(n).selectAll(n)}function tn(c,e,t,n,r){let s=j(r),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(n);for(let d of a)i=i.select(`${n}.${d}`);return i}return c.selectFrom(n).selectAll(n)}function Ie(c,e,t,n){var r,s;for(let o of n){let a=o.key.indexOf(".");if(a!==-1){let i=o.key.slice(0,a),d=o.key.slice(a+1),l=(s=(r=c==null?void 0:c[e])==null?void 0:r.relations)==null?void 0:s[i];if((l==null?void 0:l.type)==="one"&&l.relationalColumn){let u=l.entity.name,y=String(l.relationalColumn);t=t.orderBy(f=>f.selectFrom(u).select(`${u}.${d}`).whereRef(`${u}.id`,"=",`${e}.${y}`),o.direction);continue}if(l)throw new Error(`Relational sort on "${o.key}" is only supported for "one" relations with a relationalColumn`)}t=t.orderBy(o.key,o.direction);}return t}function ce(c,e,t,n,r,s){if(!n)return t;if(!c)throw new Error("Schema not initialized");let o=c[e];if(!o)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:a,jsonArrayFrom:i}=r;for(let d of Object.keys(n)){if(!o.relations[d])throw new Error(`Relation ${d} not found in resource ${e}`);let l=o.relations[d],u=l.entity.name,y=n[d],f=l.type==="one"?"id":l.foreignColumn,h=l.type==="one"?l.relationalColumn:"id",p=l.type==="one"?a:i,m=E(y)?y:null,g=m?m.include:y&&typeof y=="object"?y:void 0;t=t.select(w=>{let b=`${u}_meta`,S=tn(w,c,u,u,s).whereRef(`${u}.${f}`,"=",`${e}.${h}`).select(C=>a(en(C,c,u,b,s).whereRef(`${b}.id`,"=",`${u}.id`)).as("_meta"));return m!=null&&m.where&&(S=ae(c,u,S,m.where)),m!=null&&m.orderBy&&(S=Ie(c,u,S,m.orderBy)),(m==null?void 0:m.limit)!==void 0&&(S=S.limit(m.limit)),g&&Object.keys(g).length>0&&(S=ce(c,u,S,g,r,s)),p(S).as(d)});}return t}var Ce=class c extends J{db;dialectHelpers;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.dialectHelpers=Ke(this.db),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){this.schema=e,this.logger=t,this.server=n,await Ge(this.db,e,t);}selectMetaColumns(e,t,n){var o;let r=j(this.db),s=(o=this.schema)==null?void 0:o[t];if(r==="sqlite"&&(s!=null&&s.fields)){let a=Object.keys(s.fields),i=e.selectFrom(n);for(let d of a)i=i.select(`${n}.${d}`);return i}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,s=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(i=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(i,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));s=ce(this.schema,e,s,n,this.dialectHelpers,this.db);let o=await s.executeTakeFirst();if(!o)return;let a=this.parseRelationalJsonStrings(o,e);return this.convertToMaterializedLiveType(a,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return z$2(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=`${t}_meta`,i=this.db.selectFrom(t).selectAll(t).select(l=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(l,t,a).whereRef(`${a}.id`,"=",`${t}.id`)).as("_meta"));i=ae(this.schema,t,i,n),i=ce(this.schema,t,i,r,this.dialectHelpers,this.db),s!==void 0&&(i=i.limit(s)),o!==void 0&&(i=Ie(this.schema,t,i,o));let d=await i.execute();return d.length===0?[]:d.map(l=>{let u=this.parseRelationalJsonStrings(l,t);return this.convertToMaterializedLiveType(u,t)})}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=>z$2(r))}async rawInsert(e,t,n,r,s){var p,m,g,w,b,S,C,A,k,D,B;let o=(p=this.server)==null?void 0:p.getHooks(e),a=(m=this.schema)==null?void 0:m[e],[i,d]=((g=a==null?void 0:a.mergeMutation)==null?void 0:g.call(a,"set",n.value,void 0))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let l=i,u={...l,value:{...l.value,id:{value:t}}};if(o!=null&&o.beforeInsert){let M=z$2(u);M.id=t;let R=await o.beforeInsert({ctx:s,value:M,rawValue:u,db:this});R&&(l=R);}let y={},f={};for(let[M,R]of Object.entries(l.value)){let E=(w=R._meta)==null?void 0:w.timestamp;if(!E)continue;let I=(S=(b=a==null?void 0:a.fields[M])==null?void 0:b.getStorageFieldType)==null?void 0:S.call(b);(I==null?void 0:I.type)==="jsonb"||(I==null?void 0:I.type)==="json"?y[M]=JSON.stringify(R.value):y[M]=R.value,f[M]=E;}await this.db.insertInto(e).values({...y,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...f,id:t}).execute(),(A=(C=this.logger)==null?void 0:C.debug)==null||A.call(C,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(s==null?void 0:s.messageId)??"(none)",hasContext:!!s,contextKeys:s?Object.keys(s):[]});let h=this.buildMutation(e,t,"INSERT",l,r,s==null?void 0:s.messageId);if(h&&((B=(k=this.logger)==null?void 0:k.debug)==null||B.call(k,"[rawInsert] Mutation built, tracking",{mutationId:h.id,hasMeta:!!h.meta,originMutationId:((D=h.meta)==null?void 0:D.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(h,l)),o!=null&&o.afterInsert){let M={...l,value:{...l.value,id:{value:t}}},R=z$2(M);R.id=t,await o.afterInsert({ctx:s,value:R,rawValue:M,db:this});}return {data:l,acceptedValues:d}}async rawUpdate(e,t,n,r,s){var m,g,w,b,S,C,A,k,D,B,M;let o=(m=this.server)==null?void 0:m.getHooks(e),a=(g=this.schema)==null?void 0:g[e],i=await this.rawFindById(e,t),[d,l]=((w=a==null?void 0:a.mergeMutation)==null?void 0:w.call(a,"set",n.value,i))??[n,n.value];if(!l)return {data:n,acceptedValues:null};let u=d,y={...u,value:{...u.value,id:{value:t}}};if(o!=null&&o.beforeUpdate){let R=z$2(y);R.id=t;let E;if(i){let O={...i,value:{...i.value,id:{value:t}}};E=z$2(O),E.id=t;}let I=await o.beforeUpdate({ctx:s,value:R,rawValue:y,previousValue:E,previousRawValue:i,db:this});I&&(u=I);}let f={},h={};for(let[R,E]of Object.entries(u.value)){let I=(b=E._meta)==null?void 0:b.timestamp;if(!I)continue;let O=(C=(S=a==null?void 0:a.fields[R])==null?void 0:S.getStorageFieldType)==null?void 0:C.call(S);(O==null?void 0:O.type)==="jsonb"||(O==null?void 0:O.type)==="json"?f[R]=JSON.stringify(E.value):f[R]=E.value,h[R]=I;}if(Object.keys(f).length===0)return {data:u,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(f).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...h,id:t}).onConflict(R=>R.column("id").doUpdateSet(h)).execute()]),(k=(A=this.logger)==null?void 0:A.debug)==null||k.call(A,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(s==null?void 0:s.messageId)??"(none)",hasContext:!!s,contextKeys:s?Object.keys(s):[]});let p=this.buildMutation(e,t,"UPDATE",u,r,s==null?void 0:s.messageId);if(p){(M=(D=this.logger)==null?void 0:D.debug)==null||M.call(D,"[rawUpdate] Mutation built, tracking",{mutationId:p.id,hasMeta:!!p.meta,originMutationId:((B=p.meta)==null?void 0:B.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let R=await this.rawFindById(e,t);R&&this.trackMutation(p,R);}if(o!=null&&o.afterUpdate){let R=await this.rawFindById(e,t);if(R){let E={...R,value:{...R.value,id:{value:t}}},I=z$2(E);I.id=t;let O;if(i){let Xe={...i,value:{...i.value,id:{value:t}}};O=z$2(Xe),O.id=t;}await o.afterUpdate({ctx:s,value:I,rawValue:E,previousValue:O,previousRawValue:i,db:this});}}return {data:u,acceptedValues:l}}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 i=await this.db.savepoint(s).execute(),d=false,l=false;try{return await e({trx:this,commit:async()=>{await i.releaseSavepoint(s).execute(),d=!0,o.push(...a);},rollback:async()=>{await i.rollbackToSavepoint(s).execute(),l=!0,a.length=0;}}).then(u=>i.isCommitted||i.isRolledBack||d||l?u:i.releaseSavepoint(s).execute().then(()=>(o.push(...a),u)))}catch(u){throw l||await i.rollbackToSavepoint(s).execute().catch(()=>{}),a.length=0,u}finally{this.mutationStack=o;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let s=new c(r,this.schema,this.logger,this.server);return s.mutationStack=t,await e({trx:s,commit:async()=>{var o,a;await r.commit().execute(),(a=(o=this.logger)==null?void 0:o.debug)==null||a.call(o,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:i})=>{var d;return {id:i.id,resource:i.resource,resourceId:i.resourceId,op:i.op,hasMeta:!!i.meta,originMutationId:((d=i.meta)==null?void 0:d.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(o=>r.isCommitted||r.isRolledBack?o:r.commit().execute().then(()=>{var a,i;return (i=(a=this.logger)==null?void 0:a.debug)==null||i.call(a,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:d})=>{var l;return {id:d.id,resource:d.resource,resourceId:d.resourceId,op:d.op,hasMeta:!!d.meta,originMutationId:((l=d.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t),o}))}catch(s){throw await r.rollback().execute(),t.length=0,s}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var s,o;if(j(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(a=>this.parseRelationalJsonStrings(a,t));let r={};for(let[a,i]of Object.entries(e))if(a==="_meta"&&typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{r[a]=JSON.parse(i);}catch{r[a]=i;}else r[a]=i;else if(this.isRelationalField(t,a))if(typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let d=JSON.parse(i);if(this.schema){let l=this.schema[t],u=(s=l==null?void 0:l.relations)==null?void 0:s[a];if(u){let y=u.entity.name;r[a]=this.parseRelationalJsonStrings(d,y);}else r[a]=d;}else r[a]=d;}catch{r[a]=i;}else r[a]=i;else if(typeof i=="object"&&i!==null&&!Array.isArray(i))if(this.schema){let d=this.schema[t],l=(o=d==null?void 0:d.relations)==null?void 0:o[a];if(l){let u=l.entity.name;r[a]=this.parseRelationalJsonStrings(i,u);}else r[a]=i;}else r[a]=i;else Array.isArray(i)?r[a]=i.map(d=>{var l,u;if(typeof d=="string")try{let y=JSON.parse(d);if(this.schema){let f=this.schema[t],h=(l=f==null?void 0:f.relations)==null?void 0:l[a];if(h){let p=h.entity.name;return this.parseRelationalJsonStrings(y,p)}}return y}catch{return d}if(typeof d=="object"&&d!==null&&this.schema){let y=this.schema[t],f=(u=y==null?void 0:y.relations)==null?void 0:u[a];if(f){let h=f.entity.name;return this.parseRelationalJsonStrings(d,h)}}return d}):r[a]=i;else r[a]=i;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((s,[o,a])=>{var u,y,f,h,p,m,g,w,b;if(o==="_meta")return s;let i=(y=(u=n==null?void 0:n.fields[o])==null?void 0:u.getStorageFieldType)==null?void 0:y.call(u),d=(i==null?void 0:i.type)==="jsonb"||(i==null?void 0:i.type)==="json",l=(n==null?void 0:n.relations)&&o in n.relations;if(o==="id")s[o]={value:a};else if(d)s[o]={value:a,_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[o]}};else if(l){let S=n.relations[o].entity,C=(S==null?void 0:S.name)??t;Array.isArray(a)?s[o]={value:a.map(A=>this.convertToMaterializedLiveType(A,C)),_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[o],relation:true}}:a!==null&&typeof a=="object"?s[o]={...this.convertToMaterializedLiveType(a,C),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[o],relation:true}}:s[o]={value:a,_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[o],relation:true}};}else Array.isArray(a)?s[o]={value:a,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[o]}}:typeof a=="object"&&a!==null&&!(a instanceof Date)?s[o]={value:a,_meta:{timestamp:(w=e==null?void 0:e._meta)==null?void 0:w[o]}}:s[o]={value:a,_meta:{timestamp:(b=e==null?void 0:e._meta)==null?void 0:b[o]}};return s},{})}}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",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,o){var i;let a={};for(let[d,l]of Object.entries(r.value)){if(d==="id")continue;let u=(i=l._meta)==null?void 0:i.timestamp;u&&(a[d]={value:l.value,_meta:{timestamp:u}});}return Object.keys(a).length===0?null:{id:s??ee(),type:"SYNC",resource:e,resourceId:t,op:n,payload:a,meta:o?{originMutationId:o}:void 0}}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 Me=class c{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var t;if(this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=G$1({level:e.logLevel??F$1.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),e.hooks)for(let[n,r]of Object.entries(e.hooks)){let s=le([r]);s&&this.hooksRegistry.set(n,s);}this.initPromise=this.storage.init(this.schema,this.logger,this).catch(n=>{this.initError=n;}),this.contextProvider=e.contextProvider,this.queryEngine=new re({storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleMutation(e){return await this.ensureInitialized(),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)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async y=>{let f=this.router.routes[y.resource];if(!f)throw new Error("Invalid resource");return f.handleCustomQuery({req:y,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:r,cookies:s,queryParams:o,context:a}=e.req,i={headers:r,cookies:s,queryParams:o,context:a},d=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(d,y=>{var f;(f=e.subscription)==null||f.call(e,y);},i):void 0,u=await this.queryEngine.get(d,{context:i});return e.subscription?{data:u,unsubscribe:l,query:d}:u.map(y=>z$2(y))}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)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},_r=Me.create;export{z as QueryBuilder,we as Route,xe as RouteFactory,Se as Router,Ce as SQLStorage,Me as Server,J as Storage,sr as createMiddleware,K as createServerDB,bn as defineHooks,Zn as expressAdapter,le as mergeEntityHooks,vn as mergeHooks,or as routeFactory,ir as router,_r as server};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@live-state/sync",
3
- "version": "1.0.0-canary-1",
3
+ "version": "1.0.0-canary-2",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"