@live-state/sync 0.0.7-canary-2 → 0.0.7-canary-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import {xxHash32}from'js-xxhash';var w=Object.create;var A=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var K=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of S(e))!E.call(t,a)&&a!==i&&A(t,a,{get:()=>e[a],enumerable:!(n=N(e,a))||n.enumerable});return t};var X=(t,e,i)=>(i=t!=null?w(F(t)):{},K(e||!t||!t.__esModule?A(i,"default",{value:t,enumerable:true}):i,t));var s=class{_value;_meta;_encodeInput;_decodeInput};var y=class t extends s{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,i,n){return this.inner.encodeMutation(e,i,n)}mergeMutation(e,i,n){return this.inner.mergeMutation(e,i,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}unique(){return new t(this.inner.unique())}index(){return new t(this.inner.index())}default(e){let i=new u(this.inner.storageType,this.inner.convertFunc,this.inner.isIndex,this.inner.isUnique,e,this.inner.foreignReference,this.inner.isPrimary);return new t(i)}primary(){return new t(this.inner.primary())}},u=class t extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,i,n,a,r,o,l){super(),this.storageType=e,this.convertFunc=i,this.isIndex=n??false,this.isUnique=a??false,this.defaultValue=r,this.foreignReference=o,this.isPrimary=l??false;}encodeMutation(e,i,n){return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){return n&&n._meta.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>0?[n,null]:[{value:this.convertFunc?this.convertFunc(i.value):i.value,_meta:i._meta},i]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new t(this.storageType,this.convertFunc,this.isIndex,true,void 0,this.foreignReference,this.isPrimary)}index(){return new t(this.storageType,this.convertFunc,true,this.isUnique,void 0,this.foreignReference,this.isPrimary)}default(e){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,void 0,this.foreignReference,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,null,this.foreignReference,this.isPrimary);return new y(e)}return new y(this)}withMeta(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}},x=class t extends u{constructor(){super("integer",e=>Number(e));}static create(){return new t}},D=x.create,T=class t extends u{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new t}static createId(){return new t().index().unique().primary()}static createReference(e){return new t(e)}},O=T.create,q=T.createId,j=T.createReference,L=class t extends u{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},$=L.create,h=class t extends u{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},_=h.create,R=class t extends u{enumValues;enumName;constructor(e,i,n,a,r){super("varchar",void 0,i,n,a,void 0,r),this.enumValues=e,this.enumName=`enum_${e.slice(0,5).join("_").slice(0,50)}`;}getStorageFieldType(){return {type:"varchar",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,primary:this.isPrimary,enumValues:this.enumValues,enumName:this.enumName}}unique(){return new t(this.enumValues,this.isIndex,true,void 0,this.isPrimary)}index(){return new t(this.enumValues,true,this.isUnique,void 0,this.isPrimary)}default(e){return new t(this.enumValues,this.isIndex,this.isUnique,e,this.isPrimary)}primary(){return new t(this.enumValues,this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.enumValues,this.isIndex,this.isUnique,null,this.isPrimary);return new y(e)}return new y(this)}static create(e){return new t(e)}},P=R.create,g=class t extends u{constructor(e,i,n,a){super("jsonb",r=>typeof r=="string"?JSON.parse(r):r,e,i,n,void 0,a);}getStorageFieldType(){return {type:"jsonb",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue!==void 0?JSON.stringify(this.defaultValue):void 0,primary:this.isPrimary}}unique(){return new t(this.isIndex,true,void 0,this.isPrimary)}index(){return new t(true,this.isUnique,void 0,this.isPrimary)}default(e){return new t(this.isIndex,this.isUnique,e,this.isPrimary)}primary(){return new t(this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.isIndex,this.isUnique,null,this.isPrimary);return new y(e)}return new y(this)}static create(){return new t}},W=g.create;var c=class t extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,i,n,a,r){super(),this.entity=e,this.type=i,this.required=r??false,this.relationalColumn=n,this.foreignColumn=a;}encodeMutation(e,i,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){var a;return this.type==="many"?n?[n,null]:[i,i]:(a=n==null?void 0:n._meta)!=null&&a.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[i,i]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (e,i,n)=>new t(e,"one",i,void 0,n??false)}static createManyFactory(){return (e,i,n)=>new t(e,"many",void 0,i,n??false)}},U=(t,e)=>({$type:"relations",collectionName:t.name,objectName:t.name,relations:e({one:c.createOneFactory(),many:c.createManyFactory()})});var v=class t extends s{name;fields;relations;constructor(e,i,n){super(),this.name=e,this.fields=i,this.relations=n??{};}encodeMutation(e,i,n){return Object.fromEntries(Object.entries(i).map(([a,r])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",r,n)]))}mergeMutation(e,i,n){let a={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(i).map(([r,o])=>{let l=this.fields[r]??this.relations[r];if(!l)return [r,o];let[d,m]=l.mergeMutation(e,o,n==null?void 0:n.value[r]);return m&&(a[r]=m),[r,d]}))}},a]}setRelations(e){return new t(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,i){if(B(i)){let n=i,a=new t(e,n.fields);if(n.relations){let r=n.relations({one:c.createOneFactory(),many:c.createManyFactory()});return new t(e,n.fields,r)}return a}return new t(e,i,void 0)}};function B(t){return typeof t=="object"&&t!==null&&"fields"in t&&typeof t.fields=="object"}var b=v.create,k=b,J=v;var V=t=>typeof t=="object"&&t!==null&&"value"in t&&!Array.isArray(t),C=t=>t?Array.isArray(t.value)?t.value.map(i=>V(i)?C(i):i):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([i,n])=>Array.isArray(n)?[i,n.map(a=>V(a)?C(a):a)]:V(n)?[i,C(n)]:[i,n])):void 0;var z=t=>Object.fromEntries(Object.entries(t).flatMap(([e,i])=>{if(i.$type==="relations")return [];let n=i,a=Object.values(t).find(r=>r.$type==="relations"&&r.collectionName===i.name);return a&&(n=n.setRelations(a.relations)),[[n.name,n]]}));var ve=t=>xxHash32(JSON.stringify(t)).toString(32),H=(t,e,i)=>{let n={},a=i[e];if(!a)return n;let r=o=>{o.$and?o.$and.forEach(r):o.$or?o.$or.forEach(r):Object.entries(o).forEach(([l,d])=>{var m;if((m=a.relations)!=null&&m[l]&&(n[l]=true,typeof d=="object"&&d!==null&&!Array.isArray(d))){let I=H(d,a.relations[l].entity.name,i);Object.keys(I).length>0&&(n[l]={include:I});}});};return r(t),n},p=(t,e,i=false)=>Object.entries(e).every(([n,a])=>{if(n==="$and")return a.every(o=>p(t,o,i));if(n==="$or")return a.some(o=>p(t,o,i));let r=(a==null?void 0:a.$eq)!==void 0?a==null?void 0:a.$eq:a;if(typeof a=="object"&&a!==null&&(a==null?void 0:a.$eq)===void 0){if(a.$in!==void 0){let l=t[n];return l===void 0?false:i?!a.$in.includes(l):a.$in.includes(l)}if(a.$not!==void 0&&!i)return p(t,{[n]:a.$not},true);if(a.$gt!==void 0){let l=t[n];return typeof l!="number"?false:i?l<=a.$gt:l>a.$gt}if(a.$gte!==void 0){let l=t[n];return typeof l!="number"?false:i?l<a.$gte:l>=a.$gte}if(a.$lt!==void 0){let l=t[n];return typeof l!="number"?false:i?l>=a.$lt:l<a.$lt}if(a.$lte!==void 0){let l=t[n];return typeof l!="number"?false:i?l>a.$lte:l<=a.$lte}let o=t[n];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?i?!o.some(l=>p(l,a,false)):o.some(l=>p(l,a,false)):p(o,a,i)}return i?t[n]!==r:t[n]===r}),f={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},M=class{level;prefix;constructor(e={}){this.level=e.level??f.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=f.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=f.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=f.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=f.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=f.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},xe=t=>new M(t);export{z as A,ve as B,H as C,p as D,f as E,xe as F,Q as a,X as b,s as c,y as d,u as e,x as f,D as g,T as h,O as i,q as j,j as k,L as l,$ as m,h as n,_ as o,R as p,P as q,g as r,W as s,c as t,U as u,v,b as w,k as x,J as y,C as z};
1
+ import {xxHash32}from'js-xxhash';var w=Object.create;var A=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var H=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var K=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of N(e))!E.call(t,a)&&a!==i&&A(t,a,{get:()=>e[a],enumerable:!(n=S(e,a))||n.enumerable});return t};var X=(t,e,i)=>(i=t!=null?w(F(t)):{},K(e||!t||!t.__esModule?A(i,"default",{value:t,enumerable:true}):i,t));var s=class{_value;_meta;_encodeInput;_decodeInput};var c=class t extends s{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,i,n){return this.inner.encodeMutation(e,i,n)}mergeMutation(e,i,n){return this.inner.mergeMutation(e,i,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}unique(){return new t(this.inner.unique())}index(){return new t(this.inner.index())}default(e){let i=new u(this.inner.storageType,this.inner.convertFunc,this.inner.isIndex,this.inner.isUnique,e,this.inner.foreignReference,this.inner.isPrimary);return new t(i)}primary(){return new t(this.inner.primary())}},u=class t extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,i,n,a,r,o,l){super(),this.storageType=e,this.convertFunc=i,this.isIndex=n??false,this.isUnique=a??false,this.defaultValue=r,this.foreignReference=o,this.isPrimary=l??false;}encodeMutation(e,i,n){return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){return n&&n._meta.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>0?[n,null]:[{value:this.convertFunc?this.convertFunc(i.value):i.value,_meta:i._meta},i]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new t(this.storageType,this.convertFunc,this.isIndex,true,void 0,this.foreignReference,this.isPrimary)}index(){return new t(this.storageType,this.convertFunc,true,this.isUnique,void 0,this.foreignReference,this.isPrimary)}default(e){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,void 0,this.foreignReference,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,null,this.foreignReference,this.isPrimary);return new c(e)}return new c(this)}withMeta(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}},x=class t extends u{constructor(){super("integer",e=>Number(e));}static create(){return new t}},D=x.create,T=class t extends u{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new t}static createId(){return new t().index().unique().primary()}static createReference(e){return new t(e)}},O=T.create,q=T.createId,j=T.createReference,L=class t extends u{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},$=L.create,h=class t extends u{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},_=h.create,R=class t extends u{enumValues;enumName;constructor(e,i,n,a,r){super("varchar",void 0,i,n,a,void 0,r),this.enumValues=e,this.enumName=`enum_${e.slice(0,5).join("_").slice(0,50)}`;}getStorageFieldType(){return {type:"varchar",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,primary:this.isPrimary,enumValues:this.enumValues,enumName:this.enumName}}unique(){return new t(this.enumValues,this.isIndex,true,void 0,this.isPrimary)}index(){return new t(this.enumValues,true,this.isUnique,void 0,this.isPrimary)}default(e){return new t(this.enumValues,this.isIndex,this.isUnique,e,this.isPrimary)}primary(){return new t(this.enumValues,this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.enumValues,this.isIndex,this.isUnique,null,this.isPrimary);return new c(e)}return new c(this)}static create(e){return new t(e)}},P=R.create,g=class t extends u{constructor(e,i,n,a){super("jsonb",r=>typeof r=="string"?JSON.parse(r):r,e,i,n,void 0,a);}getStorageFieldType(){return {type:"jsonb",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue!==void 0?JSON.stringify(this.defaultValue):void 0,primary:this.isPrimary}}unique(){return new t(this.isIndex,true,void 0,this.isPrimary)}index(){return new t(true,this.isUnique,void 0,this.isPrimary)}default(e){return new t(this.isIndex,this.isUnique,e,this.isPrimary)}primary(){return new t(this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let e=new t(this.isIndex,this.isUnique,null,this.isPrimary);return new c(e)}return new c(this)}static create(){return new t}},W=g.create;var y=class t extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,i,n,a,r){super(),this.entity=e,this.type=i,this.required=r??false,this.relationalColumn=n,this.foreignColumn=a;}encodeMutation(e,i,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){var a;return this.type==="many"?n?[n,null]:[i,i]:(a=n==null?void 0:n._meta)!=null&&a.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[i,i]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (e,i,n)=>new t(e,"one",i,void 0,n??false)}static createManyFactory(){return (e,i,n)=>new t(e,"many",void 0,i,n??false)}},U=(t,e)=>({$type:"relations",collectionName:t.name,objectName:t.name,relations:e({one:y.createOneFactory(),many:y.createManyFactory()})});var v=class t extends s{name;fields;relations;constructor(e,i,n){super(),this.name=e,this.fields=i,this.relations=n??{};}encodeMutation(e,i,n){return Object.fromEntries(Object.entries(i).map(([a,r])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",r,n)]))}mergeMutation(e,i,n){let a={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(i).map(([r,o])=>{let l=this.fields[r]??this.relations[r];if(!l)return [r,o];let[d,m]=l.mergeMutation(e,o,n==null?void 0:n.value[r]);return m&&(a[r]=m),[r,d]}))}},a]}setRelations(e){return new t(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,i){if(B(i)){let n=i,a=new t(e,n.fields);if(n.relations){let r=n.relations({one:y.createOneFactory(),many:y.createManyFactory()});return new t(e,n.fields,r)}return a}return new t(e,i,void 0)}};function B(t){return typeof t=="object"&&t!==null&&"fields"in t&&typeof t.fields=="object"}var b=v.create,k=b,J=v;var V=t=>typeof t=="object"&&t!==null&&"value"in t&&!Array.isArray(t),C=t=>t?Array.isArray(t.value)?t.value.map(i=>V(i)?C(i):i):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([i,n])=>Array.isArray(n)?[i,n.map(a=>V(a)?C(a):a)]:V(n)?[i,C(n)]:[i,n])):void 0;var z=t=>Object.fromEntries(Object.entries(t).flatMap(([e,i])=>{if(i.$type==="relations")return [];let n=i,a=Object.values(t).find(r=>r.$type==="relations"&&r.collectionName===i.name);return a&&(n=n.setRelations(a.relations)),[[n.name,n]]}));var ve=t=>xxHash32(JSON.stringify(t)).toString(32),Q=(t,e,i)=>{let n={},a=i[e];if(!a)return n;let r=o=>{o.$and?o.$and.forEach(r):o.$or?o.$or.forEach(r):Object.entries(o).forEach(([l,d])=>{var m;if((m=a.relations)!=null&&m[l]&&(n[l]=true,typeof d=="object"&&d!==null&&!Array.isArray(d))){let I=Q(d,a.relations[l].entity.name,i);Object.keys(I).length>0&&(n[l]={include:I});}});};return r(t),n},p=(t,e,i=false)=>Object.entries(e).every(([n,a])=>{if(n==="$and")return a.every(o=>p(t,o,i));if(n==="$or")return a.some(o=>p(t,o,i));let r=(a==null?void 0:a.$eq)!==void 0?a==null?void 0:a.$eq:a;if(typeof a=="object"&&a!==null&&(a==null?void 0:a.$eq)===void 0){if(a.$in!==void 0){let l=t[n];return l===void 0?false:i?!a.$in.includes(l):a.$in.includes(l)}if(a.$not!==void 0&&!i)return p(t,{[n]:a.$not},true);if(a.$gt!==void 0){let l=t[n];return typeof l!="number"?false:i?l<=a.$gt:l>a.$gt}if(a.$gte!==void 0){let l=t[n];return typeof l!="number"?false:i?l<a.$gte:l>=a.$gte}if(a.$lt!==void 0){let l=t[n];return typeof l!="number"?false:i?l>=a.$lt:l<a.$lt}if(a.$lte!==void 0){let l=t[n];return typeof l!="number"?false:i?l>a.$lte:l<=a.$lte}let o=t[n];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?i?!o.some(l=>p(l,a,false)):o.some(l=>p(l,a,false)):p(o,a,i)}return i?t[n]!==r:t[n]===r}),xe=t=>{if(typeof t!="object"||t===null)return false;let e=t;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},f={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},M=class{level;prefix;constructor(e={}){this.level=e.level??f.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=f.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=f.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=f.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=f.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=f.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},Le=t=>new M(t);export{z as A,ve as B,Q as C,p as D,xe as E,f as F,Le as G,H as a,X as b,s as c,c as d,u as e,x as f,D as g,T as h,O as i,q as j,j as k,L as l,$ as m,h as n,_ as o,R as p,P as q,g as r,W as s,y as t,U as u,v,b as w,k as x,J as y,C as z};
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import {d,a,b,f as f$1,e,c}from'./chunk-LSAVBBUS.js';import {a as a$1}from'./chunk-RSSRYEM3.js';export{b as defineOptimisticMutations}from'./chunk-RSSRYEM3.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z as z$1}from'zod';import {stringify}from'qs';import ge from'fast-deep-equal';import {openDB}from'idb';var f=h=>xxHash32(JSON.stringify(h)).toString(32);var M=(h,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>M(h,n,t));if(i==="$or")return s.some(n=>M(h,n,t));let o=(s==null?void 0:s.$eq)!==void 0?s==null?void 0:s.$eq:s;if(typeof s=="object"&&s!==null&&(s==null?void 0:s.$eq)===void 0){if(s.$in!==void 0){let r=h[i];return r===void 0?false:t?!s.$in.includes(r):s.$in.includes(r)}if(s.$not!==void 0&&!t)return M(h,{[i]:s.$not},true);if(s.$gt!==void 0){let r=h[i];return typeof r!="number"?false:t?r<=s.$gt:r>s.$gt}if(s.$gte!==void 0){let r=h[i];return typeof r!="number"?false:t?r<s.$gte:r>=s.$gte}if(s.$lt!==void 0){let r=h[i];return typeof r!="number"?false:t?r>=s.$lt:r<s.$lt}if(s.$lte!==void 0){let r=h[i];return typeof r!="number"?false:t?r>s.$lte:r<=s.$lte}let n=h[i];return !n||typeof n!="object"&&!Array.isArray(n)?false:Array.isArray(n)?t?!n.some(r=>M(r,s,false)):n.some(r=>M(r,s,false)):M(n,s,t)}return t?h[i]!==o:h[i]===o}),v={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},A=class{level;prefix;constructor(e={}){this.level=e.level??v.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=v.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=v.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=v.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=v.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=v.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},B=h=>new A(h);var x=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=f(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let s={subscribe:o=>{let n=this.subscriptions.get(i);return n.callbacks.add(o),n.unsubscribe||(n.unsubscribe=()=>{},n.unsubscribe=e.subscribe(()=>{n.callbacks.forEach(r=>{r();});})),()=>{var r;(r=this.subscriptions.get(i))==null||r.callbacks.delete(o),setTimeout(()=>{var c;let a=this.subscriptions.get(i);a&&a.callbacks.size===0&&((c=a.unsubscribe)==null||c.call(a),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,s),this.subscriptions.get(i).subscribe}},re=new x,Se=h=>useSyncExternalStore(re.getOrStoreSubscription(h),h.get),Ee=(h,e)=>{useEffect(()=>{let t=h.load(e.buildQueryRequest());return ()=>{t();}},[e,h.load]);};var G=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),L=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),oe=L.superRefine((h,e)=>{h.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),H=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),z=z$1.object({timestamp:z$1.string().optional()}).optional(),j=H.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:z}),k=H.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:oe,meta:z});z$1.union([k,j]);var K=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var S=z$1.string(),D=z$1.union([K,G]),ae=z$1.object({id:S,type:z$1.literal("SUBSCRIBE")}).and(D),ce=z$1.object({id:S,type:z$1.literal("UNSUBSCRIBE")}).and(D),ue=z$1.object({id:S,type:z$1.literal("QUERY")}).and(D),le=z$1.object({id:S,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),Y=k.extend({id:S}),pe=j.extend({id:S}),de=z$1.union([pe,Y]);z$1.union([ae,ue,le,de,ce]);var he=z$1.object({id:S,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),ye=z$1.object({id:S,type:z$1.literal("REPLY"),data:z$1.any()}),V=z$1.union([he,ye,Y]),F=z$1.object({resource:z$1.string(),data:z$1.array(L)});var T=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;credentials;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.credentials=e.credentials,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}async connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.intentionallyDisconnected=false;let e=await c(this.credentials);this.ws=new WebSocket(this.url+(e?`?${stringify(e)}`:"")),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t);}removeEventListener(e,t){var i;this.eventListeners.has(e)&&((i=this.eventListeners.get(e))==null||i.delete(t));}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){var t,i;this.dispatchEvent("error",e),this.dispatchEvent("connectionChange",{open:false}),(i=(t=e.error)==null?void 0:t.message)!=null&&i.includes("non-101")&&(this.ws&&(this.ws.close(),this.ws=null),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect());}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){var i;(i=this.eventListeners.get(e))==null||i.forEach(s=>{s(t);});}};var O=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(o=>[o,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,s),s}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),s=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);i.references.set(s.type,t);let o=s.referencedBy.get(i.type);o&&o instanceof Set?o.add(e):s.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let s=i.references.get(t);if(!s)return;i.references.delete(t);let o=this.nodes.get(s);if(!o)return;let n=o.referencedBy.get(i.type);n&&(n instanceof Set?n.delete(e):o.referencedBy.delete(i.type),this.notifySubscribers(s)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,s])=>{(s instanceof Set?Array.from(s.values()):[s]).forEach(n=>{let r=this.nodes.get(n);!r||!r.references.get(i)||(r.references.delete(i),this.notifySubscribers(n));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(o){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,o);}});}getAllNodes(){return Array.from(this.nodes.values())}};var P="__meta",R="databases",C=class{db;async init(e,t){var c,l;if(typeof window>"u")return;let s=((c=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:c.version)??1,o=await f(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,p])=>[u,await f(p)]))),r=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(R)||u.createObjectStore(R);}}),a=(l=await this.getAll(r,R))==null?void 0:l[t];(a==null?void 0:a.schemaHash)!==o&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),P].forEach(p=>{(a==null?void 0:a.objectHashes[p])!==n[p]&&u.objectStoreNames.contains(p)&&u.deleteObjectStore(p),u.objectStoreNames.contains(p)||u.createObjectStore(p);}),await r.put(R,{schemaHash:o,objectHashes:n},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var s;return (s=this.db)==null?void 0:s.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(P,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(P,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((o,n)=>[s[n],o]))}};var w=class{constructor(e,t,i,s,o,n){this.schema=e;this.logger=i,this.optimisticObjGraph=new O(i),this.kvStorage=new C,this.onQuerySubscriptionTriggered=n,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{Promise.all([this.kvStorage.getMeta("mutationStack"),this.kvStorage.getMeta("customMutationStack"),this.kvStorage.getMeta("customMutationIndex")]).then(([r,a,c])=>{r&&Object.keys(r).length>0&&(this.optimisticMutationStack=r),a&&a.length>0&&(this.customMutationStack=a),c&&Object.keys(c).length>0&&(this.customMutationIndex=c),s==null||s(this.optimisticMutationStack,this.customMutationStack,this.customMutationIndex);}).then(()=>{Object.entries(this.schema).forEach(([r])=>{this.kvStorage.get(r).then(a=>{if(!a||Object.keys(a).length===0){o==null||o(r,0);return}let c=Object.entries(a).map(([l,u])=>({...u,id:{value:l}}));o==null||o(r,c.length),this.loadConsolidatedState(r,c);});});}).catch(r=>{i.debug("Storage initialization failed (may not be available in this environment):",r);});});}rawObjPool={};optimisticMutationStack={};customMutationStack=[];optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;customMutationIndex={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var a;let s=t??f(e$1);if(this.querySnapshots[s]&&!i){let c=this.querySnapshots[s];if(c)return c}let o,n=(a=e$1.where)==null?void 0:a.id;n===void 0?o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):typeof n=="string"?o=[n]:typeof n=="object"&&n!==null?"$in"in n&&Array.isArray(n.$in)?o=n.$in:"$eq"in n&&typeof n.$eq=="string"?o=[n.$eq]:o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{});let r=o.flatMap(c=>{let l=f$1(this.materializeOneWithInclude(c,e$1.include));return l?[l]:[]});if(e$1.sort&&e$1.sort.length>0){let c=(l,u)=>{for(let p of e$1.sort){let m=l[p.key],g=u[p.key];if(m<g)return p.direction==="asc"?-1:1;if(m>g)return p.direction==="asc"?1:-1}return 0};r.sort(c);}if(e$1.where||e$1.limit){let c=e$1.where?l=>M(l,e$1.where):()=>true;r=e(r,c,e$1.limit);}return !i&&this.collectionSubscriptions.has(s)&&(this.querySnapshots[s]=r),r}subscribe(e,t){var o;let i=f(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(o=this.collectionSubscriptions.get(i))==null||o.callbacks.add(t),()=>{var n,r;(n=this.collectionSubscriptions.get(i))==null||n.callbacks.delete(t),((r=this.collectionSubscriptions.get(i))==null?void 0:r.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var n,r,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let o=(n=this.optimisticRawObjPool[e])==null?void 0:n[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(r=this.optimisticMutationStack)==null?void 0:r[e])==null?void 0:a.filter(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let c={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=c;let l=c.value;delete l.id,this.kvStorage.set(e,t.resourceId,l);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,o);}undoMutation(e,t){var n,r;if(!this.optimisticMutationStack[e])return;let i=(n=this.optimisticMutationStack[e])==null?void 0:n.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let o=(r=this.optimisticRawObjPool[e])==null?void 0:r[s.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,s.resourceId,Object.fromEntries(Object.entries(s.payload).map(([a])=>[a,{value:null,_meta:{}}])),o);}addCustomMutationMessage(e){this.customMutationStack.push(e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}registerCustomMutation(e,t){this.customMutationIndex[e]=t,this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex);}confirmCustomMutation(e){let t=this.customMutationIndex[e];if(t){for(let{resource:i,mutationId:s}of t)this.undoMutation(i,s);delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(i=>i.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}}undoCustomMutation(e){var s;let t=this.customMutationIndex[e];if(!t)return [];let i=[];for(let{resource:o,mutationId:n}of t){let r=(s=this.optimisticMutationStack[o])==null?void 0:s.find(a=>a.id===n);this.undoMutation(o,n),r&&i.push({resource:o,mutationId:n,resourceId:r.resourceId});}return delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(o=>o.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack),i}getCustomMutationMutationIds(){let e=new Set;for(let t of Object.values(this.customMutationIndex))for(let{mutationId:i}of t)e.add(i);return e}loadConsolidatedState(e,t){t.forEach(i=>{var r;let s=(r=i.id)==null?void 0:r.value;if(!s)return;let{cleanedPayload:o,nestedMutations:n}=this.extractNestedRelations(e,i);n.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:o});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},o=[];return i!=null&&i.relations?(Object.entries(t).forEach(([n,r])=>{var u;let a=i.relations[n];if(!a)return;let c=a.entity.name,l=r==null?void 0:r.value;if(a.type==="one"){if(l&&typeof l=="object"&&!Array.isArray(l)&&((u=l.id)!=null&&u.value)){let p=l.id.value,m={...l},{cleanedPayload:g,nestedMutations:E}=this.extractNestedRelations(c,m);o.push(...E),o.push({id:p,type:"MUTATE",resource:c,resourceId:p,procedure:"INSERT",payload:g}),delete s[n];}}else a.type==="many"&&Array.isArray(l)&&(l.forEach(p=>{var m,g;if(p&&typeof p=="object"&&!Array.isArray(p)&&((g=(m=p.value)==null?void 0:m.id)!=null&&g.value)){let E=p.value.id.value,X={...p.value},{cleanedPayload:Z,nestedMutations:ee}=this.extractNestedRelations(c,X);o.push(...ee),o.push({id:E,type:"MUTATE",resource:c,resourceId:E,procedure:"INSERT",payload:Z});}}),delete s[n]);}),{cleanedPayload:s,nestedMutations:o}):{cleanedPayload:s,nestedMutations:o}}updateRawObjPool(e,t,i,s){var r;if(!this.schema[e])return;let o=(r=this.rawObjPool[e])==null?void 0:r[t],n=(this.optimisticMutationStack[e]??[]).reduce((a,c)=>c.resourceId!==t?a:this.schema[e].mergeMutation("set",c.payload,a)[0],o);if(this.optimisticRawObjPool[e]??={},n?this.optimisticRawObjPool[e][t]={value:{...n.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!n)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(a=>a.type==="many"?[a.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let a=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([c,l])=>l.type==="one"?[[l.relationalColumn,c]]:[]));Object.entries(i).forEach(([c,l])=>{let u=this.schema[e].relations[a[c]];if(!a[c])return;let p=s==null?void 0:s.value[c],[,m]=u.mergeMutation("set",l,p);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let g=u.entity.name;this.optimisticObjGraph.createNode(m.value,g,Object.values(this.schema[g].relations).flatMap(E=>E.type==="many"?[E.entity.name]:[]));}p!=null&&p.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,m.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var a;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let s=i.type,o=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!o)return;let[n,r]=Object.entries(t).reduce((c,[l,u])=>{let p=this.schema[s].relations[l];return p&&(p.type==="one"?c[0].push([l,p.entity.name,u??true]):p.type==="many"&&c[1].push([l,p.entity.name,u??true])),c},[[],[]]);return {value:{...o.value,...Object.fromEntries(n.map(([c,l,u])=>[c,this.materializeOneWithInclude(i.references.get(l),typeof u=="object"&&u!==null?u:{})])),...Object.fromEntries(r.map(([c,l,u])=>{let p=i.referencedBy.get(l),m=p instanceof Set;return [c,m?{value:Array.from(p.values()).map(g=>this.materializeOneWithInclude(g,typeof u=="object"&&u!==null?u:{}))}:this.materializeOneWithInclude(p,typeof u=="object"&&u!==null?u:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,s;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let o=f(t.query),n=this.querySnapshots[o],r=this.get(t.query,void 0,true);if(ge(r,n))return;this.querySnapshots[o]=r,(s=this.onQuerySubscriptionTriggered)==null||s.call(this,t.query),t.callbacks.forEach(a=>{a(r);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,o])=>{var a;let n=(a=this.schema[t])==null?void 0:a.relations[s];if(!n)return;let r=n.entity.name;i.push(r),typeof o=="object"&&o!==null&&i.push(...this.flattenIncludes(o,r));}),Array.from(new Set(i))}};var I=class{constructor(e,t){this.client=e;this.query=t;}buildQueryRequest(){return this.query}then(e,t){return this.client.genericQuery(this.query.resource,this.query.procedure,this.query.input).then(e,t)}},U=class{url;ws;store;logger;optimisticMutations;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,o;this.url=e.url,this.logger=B({level:e.logLevel??v.INFO}),this.optimisticMutations=e.optimisticMutations,this.store=new w(e.schema,e.storage,this.logger,(n,r,a)=>{var l,u;let c=new Set;if(a)for(let p of Object.values(a))for(let{mutationId:m}of p)c.add(m);(u=(l=Object.values(n))==null?void 0:l.flat())==null||u.forEach(p=>{c.has(p.id)||this.sendWsMessage(p);}),this.replayCustomMutationStack();},(n,r)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:n,itemCount:r});},n=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:n});}),this.ws=new T({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(o=e.connection)==null?void 0:o.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",n=>{this.handleServerMessage(n.data);}),this.ws.addEventListener("connectionChange",n=>{if(this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:n.open}),n.open){Array.from(this.remoteSubscriptions.values()).forEach(({query:a})=>{this.sendWsMessage({id:b(),type:"SUBSCRIBE",...a});});let r=this.store.getCustomMutationMutationIds();Object.values(this.store.optimisticMutationStack).forEach(a=>{a&&a.forEach(c=>{r.has(c.id)||(this.emitEvent({type:"MUTATION_SENT",mutationId:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure??"UNKNOWN",optimistic:true}),this.sendWsMessage(c));});}),this.replayCustomMutationStack();}});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i,s,o;try{this.logger.debug("Message received from the server:",e);let n=V.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",n),this.emitEvent({type:"MESSAGE_RECEIVED",message:n}),n.type==="MUTATE"){let{resource:r,id:a,resourceId:c,procedure:l}=n;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:a,resource:r,resourceId:c,procedure:l??"UNKNOWN"});try{this.store.addMutation(r,n);}catch(u){this.logger.error("Error merging mutation from the server:",u);}}else if(n.type==="REJECT"){if(this.replyHandlers[n.id]){clearTimeout(this.replyHandlers[n.id].timeoutHandle),this.emitUndoEvents(this.store.undoCustomMutation(n.id));let c=n.message??"Mutation rejected";(i=(t=this.replyHandlers[n.id]).reject)==null||i.call(t,new Error(c)),delete this.replyHandlers[n.id];}let r=((s=this.store.optimisticMutationStack[n.resource])==null?void 0:s.length)??0,a=(o=this.store.optimisticMutationStack[n.resource])==null?void 0:o.find(c=>c.id===n.id);this.store.undoMutation(n.resource,n.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:n.id,resource:n.resource}),a&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:n.id,resource:n.resource,resourceId:a.resourceId,pendingMutations:r-1});}else if(n.type==="REPLY"){let{id:r,data:a}=n;if(this.replyHandlers[r]){clearTimeout(this.replyHandlers[r].timeoutHandle),this.replyHandlers[r].handler(a);return}let c=F.parse(a);this.emitEvent({type:"DATA_LOAD_REPLY",resource:c.resource,itemCount:c.data.length}),this.store.loadConsolidatedState(c.resource,c.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:c.resource,itemCount:c.data.length});}}catch(n){this.logger.error("Error parsing message from the server:",n);}}load(e){let t=b(),i=f(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let s=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),s&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let o=this.remoteSubscriptions.get(i);o.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:b(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var r,a;let o={id:b(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i},n=(((r=this.store.optimisticMutationStack[e])==null?void 0:r.length)??0)+1;(a=this.store)==null||a.addMutation(e,o,true),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:o.id,resource:e,resourceId:t,procedure:i,pendingMutations:n}),this.emitEvent({type:"MUTATION_SENT",mutationId:o.id,resource:e,resourceId:t,procedure:i,optimistic:true}),this.sendWsMessage(o);}genericMutate(e,t,i){var r,a;let s=(r=this.ws)==null?void 0:r.connected(),o=(a=this.optimisticMutations)==null?void 0:a.getHandler(e,t);if(!s&&!o)throw new Error("WebSocket not connected");let n={id:b(),type:"MUTATE",resource:e,procedure:t,payload:i,meta:{timestamp:new Date().toISOString()}};if(o)try{let{proxy:c,getOperations:l}=a$1(this.store,this.store.schema);o({input:i,storage:c});let u=l(),p=this.applyOptimisticOperations(u);this.store.registerCustomMutation(n.id,p),this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:!0});}catch(c){throw this.logger.error("Error executing optimistic handler:",c),this.emitUndoEvents(this.store.undoCustomMutation(n.id)),c}else this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:false});return s?(this.sendWsMessage(n),new Promise((c,l)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],this.emitUndoEvents(this.store.undoCustomMutation(n.id)),l(new Error("Reply timeout"));},5e3),handler:u=>{delete this.replyHandlers[n.id],this.store.confirmCustomMutation(n.id),c(u);},reject:l};})):(this.store.addCustomMutationMessage(n),Promise.resolve(void 0))}applyOptimisticOperations(e){var i;let t=[];try{for(let s of e){let o=b(),n=new Date().toISOString(),r={id:o,type:"MUTATE",resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",payload:this.store.schema[s.resource].encodeMutation("set",s.data,n)},a=(((i=this.store.optimisticMutationStack[s.resource])==null?void 0:i.length)??0)+1;this.store.addMutation(s.resource,r,!0),t.push({resource:s.resource,mutationId:o}),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:o,resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",pendingMutations:a});}return t}catch(s){for(let{resource:o,mutationId:n}of t)this.store.undoMutation(o,n);throw s}}emitUndoEvents(e){var t;for(let{resource:i,mutationId:s,resourceId:o}of e){let n=((t=this.store.optimisticMutationStack[i])==null?void 0:t.length)??0;this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s,resource:i,resourceId:o,pendingMutations:n});}}genericQuery(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let s={id:b(),type:"CUSTOM_QUERY",resource:e,procedure:t,input:i};return this.sendWsMessage(s),new Promise((o,n)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],n(new Error("Reply timeout"));},5e3),handler:r=>{delete this.replyHandlers[s.id],o(r);},reject:n};})}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}replayCustomMutationStack(){var e;if((e=this.ws)!=null&&e.connected())for(let t of this.store.customMutationStack)this.sendWsMessage(t),!this.replyHandlers[t.id]&&(this.replyHandlers[t.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[t.id],this.emitUndoEvents(this.store.undoCustomMutation(t.id));},5e3),handler:()=>{delete this.replyHandlers[t.id],this.store.confirmCustomMutation(t.id);}});}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},Ze=h=>{let e=new U(h),t=(i,s)=>new Proxy(s,{get(o,n,r){if(n in o)return Reflect.get(o,n,r);if(typeof n=="string")return a=>new I(e,{resource:i,procedure:n,input:a})}});return {client:{ws:e.ws,load:i=>e.load(i),addEventListener:i=>e.addEventListener(i)},store:{query:new Proxy({},{get(i,s){if(typeof s=="string")return Object.hasOwn(h.schema,s)?t(s,a._init(h.schema[s],e)):new Proxy({},{get(o,n){if(typeof n=="string")return r=>new I(e,{resource:s,procedure:n,input:r})}})},has(i,s){return typeof s=="string"}}),mutate:d(()=>{},{apply:(i,s,o)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[n,r]=s;if(r==="insert"){let{id:a,...c}=o[0];return e.mutate(n,a,"INSERT",c)}if(r==="update"){let[a,c]=o;return e.mutate(n,a,"UPDATE",c)}return e.genericMutate(n,r,o[0])}})}}};export{Ze as createClient,Se as useLiveQuery,Ee as useLoadData};
1
+ import {d,a,b,f as f$1,e,c}from'./chunk-LSAVBBUS.js';import {a as a$1}from'./chunk-RSSRYEM3.js';export{b as defineOptimisticMutations}from'./chunk-RSSRYEM3.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z as z$1}from'zod';import {stringify}from'qs';import fe from'fast-deep-equal';import {openDB}from'idb';var f=d=>xxHash32(JSON.stringify(d)).toString(32);var M=(d,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>M(d,n,t));if(i==="$or")return s.some(n=>M(d,n,t));let o=(s==null?void 0:s.$eq)!==void 0?s==null?void 0:s.$eq:s;if(typeof s=="object"&&s!==null&&(s==null?void 0:s.$eq)===void 0){if(s.$in!==void 0){let r=d[i];return r===void 0?false:t?!s.$in.includes(r):s.$in.includes(r)}if(s.$not!==void 0&&!t)return M(d,{[i]:s.$not},true);if(s.$gt!==void 0){let r=d[i];return typeof r!="number"?false:t?r<=s.$gt:r>s.$gt}if(s.$gte!==void 0){let r=d[i];return typeof r!="number"?false:t?r<s.$gte:r>=s.$gte}if(s.$lt!==void 0){let r=d[i];return typeof r!="number"?false:t?r>=s.$lt:r<s.$lt}if(s.$lte!==void 0){let r=d[i];return typeof r!="number"?false:t?r>s.$lte:r<=s.$lte}let n=d[i];return !n||typeof n!="object"&&!Array.isArray(n)?false:Array.isArray(n)?t?!n.some(r=>M(r,s,false)):n.some(r=>M(r,s,false)):M(n,s,t)}return t?d[i]!==o:d[i]===o}),O=d=>{if(typeof d!="object"||d===null)return false;let e=d;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},v={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},x=class{level;prefix;constructor(e={}){this.level=e.level??v.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=v.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=v.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=v.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=v.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=v.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},G=d=>new x(d);var L=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=f(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let s={subscribe:o=>{let n=this.subscriptions.get(i);return n.callbacks.add(o),n.unsubscribe||(n.unsubscribe=()=>{},n.unsubscribe=e.subscribe(()=>{n.callbacks.forEach(r=>{r();});})),()=>{var r;(r=this.subscriptions.get(i))==null||r.callbacks.delete(o),setTimeout(()=>{var c;let a=this.subscriptions.get(i);a&&a.callbacks.size===0&&((c=a.unsubscribe)==null||c.call(a),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,s),this.subscriptions.get(i).subscribe}},oe=new L,Ee=d=>useSyncExternalStore(oe.getOrStoreSubscription(d),d.get),Oe=(d,e)=>{useEffect(()=>{let t=d.load(e.buildQueryRequest());return ()=>{t();}},[e,d.load]);};var H=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),j=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()})),ae=j.superRefine((d,e)=>{d.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),z=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),K=z$1.object({timestamp:z$1.string().optional()}).optional(),k=z.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:K}),D=z.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:ae,meta:K});z$1.union([D,k]);var Y=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var S=z$1.string(),P=z$1.union([Y,H]),ce=z$1.object({id:S,type:z$1.literal("SUBSCRIBE")}).and(P),ue=z$1.object({id:S,type:z$1.literal("UNSUBSCRIBE")}).and(P),le=z$1.object({id:S,type:z$1.literal("QUERY")}).and(P),pe=z$1.object({id:S,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),V=D.extend({id:S}),de=k.extend({id:S}),he=z$1.union([de,V]);z$1.union([ce,le,pe,he,ue]);var ye=z$1.object({id:S,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),me=z$1.object({id:S,type:z$1.literal("REPLY"),data:z$1.any()}),F=z$1.union([ye,me,V]),J=z$1.object({resource:z$1.string(),data:z$1.array(j)});var R=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;credentials;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.credentials=e.credentials,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}async connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.intentionallyDisconnected=false;let e=await c(this.credentials);this.ws=new WebSocket(this.url+(e?`?${stringify(e)}`:"")),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t);}removeEventListener(e,t){var i;this.eventListeners.has(e)&&((i=this.eventListeners.get(e))==null||i.delete(t));}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){var t,i;this.dispatchEvent("error",e),this.dispatchEvent("connectionChange",{open:false}),(i=(t=e.error)==null?void 0:t.message)!=null&&i.includes("non-101")&&(this.ws&&(this.ws.close(),this.ws=null),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect());}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){var i;(i=this.eventListeners.get(e))==null||i.forEach(s=>{s(t);});}};var T=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(o=>[o,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,s),s}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),s=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);i.references.set(s.type,t);let o=s.referencedBy.get(i.type);o&&o instanceof Set?o.add(e):s.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let s=i.references.get(t);if(!s)return;i.references.delete(t);let o=this.nodes.get(s);if(!o)return;let n=o.referencedBy.get(i.type);n&&(n instanceof Set?n.delete(e):o.referencedBy.delete(i.type),this.notifySubscribers(s)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,s])=>{(s instanceof Set?Array.from(s.values()):[s]).forEach(n=>{let r=this.nodes.get(n);!r||!r.references.get(i)||(r.references.delete(i),this.notifySubscribers(n));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(o){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,o);}});}getAllNodes(){return Array.from(this.nodes.values())}};var U="__meta",C="databases",w=class{db;async init(e,t){var c,l;if(typeof window>"u")return;let s=((c=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:c.version)??1,o=await f(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,p])=>[u,await f(p)]))),r=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(C)||u.createObjectStore(C);}}),a=(l=await this.getAll(r,C))==null?void 0:l[t];(a==null?void 0:a.schemaHash)!==o&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),U].forEach(p=>{(a==null?void 0:a.objectHashes[p])!==n[p]&&u.objectStoreNames.contains(p)&&u.deleteObjectStore(p),u.objectStoreNames.contains(p)||u.createObjectStore(p);}),await r.put(C,{schemaHash:o,objectHashes:n},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var s;return (s=this.db)==null?void 0:s.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(U,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(U,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((o,n)=>[s[n],o]))}};var I=class{constructor(e,t,i,s,o,n){this.schema=e;this.logger=i,this.optimisticObjGraph=new T(i),this.kvStorage=new w,this.onQuerySubscriptionTriggered=n,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{Promise.all([this.kvStorage.getMeta("mutationStack"),this.kvStorage.getMeta("customMutationStack"),this.kvStorage.getMeta("customMutationIndex")]).then(([r,a,c])=>{r&&Object.keys(r).length>0&&(this.optimisticMutationStack=r),a&&a.length>0&&(this.customMutationStack=a),c&&Object.keys(c).length>0&&(this.customMutationIndex=c),s==null||s(this.optimisticMutationStack,this.customMutationStack,this.customMutationIndex);}).then(()=>{Object.entries(this.schema).forEach(([r])=>{this.kvStorage.get(r).then(a=>{if(!a||Object.keys(a).length===0){o==null||o(r,0);return}let c=Object.entries(a).map(([l,u])=>({...u,id:{value:l}}));o==null||o(r,c.length),this.loadConsolidatedState(r,c);});});}).catch(r=>{i.debug("Storage initialization failed (may not be available in this environment):",r);});});}rawObjPool={};optimisticMutationStack={};customMutationStack=[];optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;customMutationIndex={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var a;let s=t??f(e$1);if(this.querySnapshots[s]&&!i){let c=this.querySnapshots[s];if(c)return c}let o,n=(a=e$1.where)==null?void 0:a.id;n===void 0?o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):typeof n=="string"?o=[n]:typeof n=="object"&&n!==null?"$in"in n&&Array.isArray(n.$in)?o=n.$in:"$eq"in n&&typeof n.$eq=="string"?o=[n.$eq]:o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):o=Object.keys(this.optimisticRawObjPool[e$1.resource]??{});let r=o.flatMap(c=>{let l=f$1(this.materializeOneWithInclude(c,e$1.include));return l?[l]:[]});if(e$1.sort&&e$1.sort.length>0){let c=(l,u)=>{for(let p of e$1.sort){let m=l[p.key],g=u[p.key];if(m<g)return p.direction==="asc"?-1:1;if(m>g)return p.direction==="asc"?1:-1}return 0};r.sort(c);}if(e$1.where||e$1.limit){let c=e$1.where?l=>M(l,e$1.where):()=>true;r=e(r,c,e$1.limit);}return !i&&this.collectionSubscriptions.has(s)&&(this.querySnapshots[s]=r),r}subscribe(e,t){var o;let i=f(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(o=this.collectionSubscriptions.get(i))==null||o.callbacks.add(t),()=>{var n,r;(n=this.collectionSubscriptions.get(i))==null||n.callbacks.delete(t),((r=this.collectionSubscriptions.get(i))==null?void 0:r.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var n,r,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let o=(n=this.optimisticRawObjPool[e])==null?void 0:n[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(r=this.optimisticMutationStack)==null?void 0:r[e])==null?void 0:a.filter(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let c={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=c;let l=c.value;delete l.id,this.kvStorage.set(e,t.resourceId,l);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,o);}undoMutation(e,t){var n,r;if(!this.optimisticMutationStack[e])return;let i=(n=this.optimisticMutationStack[e])==null?void 0:n.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let o=(r=this.optimisticRawObjPool[e])==null?void 0:r[s.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,s.resourceId,Object.fromEntries(Object.entries(s.payload).map(([a])=>[a,{value:null,_meta:{}}])),o);}addCustomMutationMessage(e){this.customMutationStack.push(e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}registerCustomMutation(e,t){this.customMutationIndex[e]=t,this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex);}confirmCustomMutation(e){let t=this.customMutationIndex[e];if(t){for(let{resource:i,mutationId:s}of t)this.undoMutation(i,s);delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(i=>i.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}}undoCustomMutation(e){var s;let t=this.customMutationIndex[e];if(!t)return [];let i=[];for(let{resource:o,mutationId:n}of t){let r=(s=this.optimisticMutationStack[o])==null?void 0:s.find(a=>a.id===n);this.undoMutation(o,n),r&&i.push({resource:o,mutationId:n,resourceId:r.resourceId});}return delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(o=>o.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack),i}getCustomMutationMutationIds(){let e=new Set;for(let t of Object.values(this.customMutationIndex))for(let{mutationId:i}of t)e.add(i);return e}loadConsolidatedState(e,t){t.forEach(i=>{var r;let s=(r=i.id)==null?void 0:r.value;if(!s)return;let{cleanedPayload:o,nestedMutations:n}=this.extractNestedRelations(e,i);n.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:o});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},o=[];return i!=null&&i.relations?(Object.entries(t).forEach(([n,r])=>{var u;let a=i.relations[n];if(!a)return;let c=a.entity.name,l=r==null?void 0:r.value;if(a.type==="one"){if(l&&typeof l=="object"&&!Array.isArray(l)&&((u=l.id)!=null&&u.value)){let p=l.id.value,m={...l},{cleanedPayload:g,nestedMutations:E}=this.extractNestedRelations(c,m);o.push(...E),o.push({id:p,type:"MUTATE",resource:c,resourceId:p,procedure:"INSERT",payload:g}),delete s[n];}}else a.type==="many"&&Array.isArray(l)&&(l.forEach(p=>{var m,g;if(p&&typeof p=="object"&&!Array.isArray(p)&&((g=(m=p.value)==null?void 0:m.id)!=null&&g.value)){let E=p.value.id.value,Z={...p.value},{cleanedPayload:ee,nestedMutations:te}=this.extractNestedRelations(c,Z);o.push(...te),o.push({id:E,type:"MUTATE",resource:c,resourceId:E,procedure:"INSERT",payload:ee});}}),delete s[n]);}),{cleanedPayload:s,nestedMutations:o}):{cleanedPayload:s,nestedMutations:o}}updateRawObjPool(e,t,i,s){var r;if(!this.schema[e])return;let o=(r=this.rawObjPool[e])==null?void 0:r[t],n=(this.optimisticMutationStack[e]??[]).reduce((a,c)=>c.resourceId!==t?a:this.schema[e].mergeMutation("set",c.payload,a)[0],o);if(this.optimisticRawObjPool[e]??={},n?this.optimisticRawObjPool[e][t]={value:{...n.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!n)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(a=>a.type==="many"?[a.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let a=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([c,l])=>l.type==="one"?[[l.relationalColumn,c]]:[]));Object.entries(i).forEach(([c,l])=>{let u=this.schema[e].relations[a[c]];if(!a[c])return;let p=s==null?void 0:s.value[c],[,m]=u.mergeMutation("set",l,p);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let g=u.entity.name;this.optimisticObjGraph.createNode(m.value,g,Object.values(this.schema[g].relations).flatMap(E=>E.type==="many"?[E.entity.name]:[]));}p!=null&&p.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,m.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var a;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let s=i.type,o=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!o)return;let[n,r]=Object.entries(t).reduce((c,[l,u])=>{let p=this.schema[s].relations[l];return p&&(p.type==="one"?c[0].push([l,p.entity.name,u??true]):p.type==="many"&&c[1].push([l,p.entity.name,u??true])),c},[[],[]]);return {value:{...o.value,...Object.fromEntries(n.map(([c,l,u])=>[c,this.materializeOneWithInclude(i.references.get(l),O(u)?u.include??{}:typeof u=="object"&&u!==null?u:{})])),...Object.fromEntries(r.map(([c,l,u])=>{let p=i.referencedBy.get(l),m=p instanceof Set;return [c,m?{value:Array.from(p.values()).map(g=>this.materializeOneWithInclude(g,O(u)?u.include??{}:typeof u=="object"&&u!==null?u:{}))}:this.materializeOneWithInclude(p,O(u)?u.include??{}:typeof u=="object"&&u!==null?u:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,s;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let o=f(t.query),n=this.querySnapshots[o],r=this.get(t.query,void 0,true);if(fe(r,n))return;this.querySnapshots[o]=r,(s=this.onQuerySubscriptionTriggered)==null||s.call(this,t.query),t.callbacks.forEach(a=>{a(r);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,o])=>{var a;let n=(a=this.schema[t])==null?void 0:a.relations[s];if(!n)return;let r=n.entity.name;if(i.push(r),typeof o=="object"&&o!==null){let c=O(o)?o.include??{}:o;i.push(...this.flattenIncludes(c,r));}}),Array.from(new Set(i))}};var A=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)}},Q=class{url;ws;store;logger;optimisticMutations;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,o;this.url=e.url,this.logger=G({level:e.logLevel??v.INFO}),this.optimisticMutations=e.optimisticMutations,this.store=new I(e.schema,e.storage,this.logger,(n,r,a)=>{var l,u;let c=new Set;if(a)for(let p of Object.values(a))for(let{mutationId:m}of p)c.add(m);(u=(l=Object.values(n))==null?void 0:l.flat())==null||u.forEach(p=>{c.has(p.id)||this.sendWsMessage(p);}),this.replayCustomMutationStack();},(n,r)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:n,itemCount:r});},n=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:n});}),this.ws=new R({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(o=e.connection)==null?void 0:o.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",n=>{this.handleServerMessage(n.data);}),this.ws.addEventListener("connectionChange",n=>{if(this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:n.open}),n.open){Array.from(this.remoteSubscriptions.values()).forEach(({query:a})=>{this.sendWsMessage({id:b(),type:"SUBSCRIBE",...a});});let r=this.store.getCustomMutationMutationIds();Object.values(this.store.optimisticMutationStack).forEach(a=>{a&&a.forEach(c=>{r.has(c.id)||(this.emitEvent({type:"MUTATION_SENT",mutationId:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure??"UNKNOWN",optimistic:true}),this.sendWsMessage(c));});}),this.replayCustomMutationStack();}});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i,s,o;try{this.logger.debug("Message received from the server:",e);let n=F.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",n),this.emitEvent({type:"MESSAGE_RECEIVED",message:n}),n.type==="MUTATE"){let{resource:r,id:a,resourceId:c,procedure:l}=n;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:a,resource:r,resourceId:c,procedure:l??"UNKNOWN"});try{this.store.addMutation(r,n);}catch(u){this.logger.error("Error merging mutation from the server:",u);}}else if(n.type==="REJECT"){if(this.replyHandlers[n.id]){clearTimeout(this.replyHandlers[n.id].timeoutHandle),this.emitUndoEvents(this.store.undoCustomMutation(n.id));let c=n.message??"Mutation rejected";(i=(t=this.replyHandlers[n.id]).reject)==null||i.call(t,new Error(c)),delete this.replyHandlers[n.id];}let r=((s=this.store.optimisticMutationStack[n.resource])==null?void 0:s.length)??0,a=(o=this.store.optimisticMutationStack[n.resource])==null?void 0:o.find(c=>c.id===n.id);this.store.undoMutation(n.resource,n.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:n.id,resource:n.resource}),a&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:n.id,resource:n.resource,resourceId:a.resourceId,pendingMutations:r-1});}else if(n.type==="REPLY"){let{id:r,data:a}=n;if(this.replyHandlers[r]){clearTimeout(this.replyHandlers[r].timeoutHandle),this.replyHandlers[r].handler(a);return}let c=J.parse(a);this.emitEvent({type:"DATA_LOAD_REPLY",resource:c.resource,itemCount:c.data.length}),this.store.loadConsolidatedState(c.resource,c.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:c.resource,itemCount:c.data.length});}}catch(n){this.logger.error("Error parsing message from the server:",n);}}load(e){let t=b(),i=f(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let s=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),s&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let o=this.remoteSubscriptions.get(i);o.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:b(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var r,a;let o={id:b(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i},n=(((r=this.store.optimisticMutationStack[e])==null?void 0:r.length)??0)+1;(a=this.store)==null||a.addMutation(e,o,true),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:o.id,resource:e,resourceId:t,procedure:i,pendingMutations:n}),this.emitEvent({type:"MUTATION_SENT",mutationId:o.id,resource:e,resourceId:t,procedure:i,optimistic:true}),this.sendWsMessage(o);}genericMutate(e,t,i){var r,a;let s=(r=this.ws)==null?void 0:r.connected(),o=(a=this.optimisticMutations)==null?void 0:a.getHandler(e,t);if(!s&&!o)throw new Error("WebSocket not connected");let n={id:b(),type:"MUTATE",resource:e,procedure:t,payload:i,meta:{timestamp:new Date().toISOString()}};if(o)try{let{proxy:c,getOperations:l}=a$1(this.store,this.store.schema);o({input:i,storage:c});let u=l(),p=this.applyOptimisticOperations(u);this.store.registerCustomMutation(n.id,p),this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:!0});}catch(c){throw this.logger.error("Error executing optimistic handler:",c),this.emitUndoEvents(this.store.undoCustomMutation(n.id)),c}else this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:false});return s?(this.sendWsMessage(n),new Promise((c,l)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],this.emitUndoEvents(this.store.undoCustomMutation(n.id)),l(new Error("Reply timeout"));},5e3),handler:u=>{delete this.replyHandlers[n.id],this.store.confirmCustomMutation(n.id),c(u);},reject:l};})):(this.store.addCustomMutationMessage(n),Promise.resolve(void 0))}applyOptimisticOperations(e){var i;let t=[];try{for(let s of e){let o=b(),n=new Date().toISOString(),r={id:o,type:"MUTATE",resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",payload:this.store.schema[s.resource].encodeMutation("set",s.data,n)},a=(((i=this.store.optimisticMutationStack[s.resource])==null?void 0:i.length)??0)+1;this.store.addMutation(s.resource,r,!0),t.push({resource:s.resource,mutationId:o}),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:o,resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",pendingMutations:a});}return t}catch(s){for(let{resource:o,mutationId:n}of t)this.store.undoMutation(o,n);throw s}}emitUndoEvents(e){var t;for(let{resource:i,mutationId:s,resourceId:o}of e){let n=((t=this.store.optimisticMutationStack[i])==null?void 0:t.length)??0;this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s,resource:i,resourceId:o,pendingMutations:n});}}genericQuery(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let s={id:b(),type:"CUSTOM_QUERY",resource:e,procedure:t,input:i};return this.sendWsMessage(s),new Promise((o,n)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],n(new Error("Reply timeout"));},5e3),handler:r=>{delete this.replyHandlers[s.id],o(r);},reject:n};})}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}replayCustomMutationStack(){var e;if((e=this.ws)!=null&&e.connected())for(let t of this.store.customMutationStack)this.sendWsMessage(t),!this.replyHandlers[t.id]&&(this.replyHandlers[t.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[t.id],this.emitUndoEvents(this.store.undoCustomMutation(t.id));},5e3),handler:()=>{delete this.replyHandlers[t.id],this.store.confirmCustomMutation(t.id);}});}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},et=d$1=>{let e=new Q(d$1),t=(i,s)=>new Proxy(s,{get(o,n,r){if(n in o)return Reflect.get(o,n,r);if(typeof n=="string")return a=>new A(e,{resource:i,procedure:n,input:a})}});return {client:{ws:e.ws,load:i=>e.load(i),addEventListener:i=>e.addEventListener(i)},store:{query:new Proxy({},{get(i,s){if(typeof s=="string")return Object.hasOwn(d$1.schema,s)?t(s,a._init(d$1.schema[s],e)):new Proxy({},{get(o,n){if(typeof n=="string")return r=>new A(e,{resource:s,procedure:n,input:r})}})},has(i,s){return typeof s=="string"}}),mutate:d(()=>{},{apply:(i,s,o)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[n,r]=s;if(r==="insert"){let{id:a,...c}=o[0];return e.mutate(n,a,"INSERT",c)}if(r==="update"){let[a,c]=o;return e.mutate(n,a,"UPDATE",c)}return e.genericMutate(n,r,o[0])}})}}};export{et as createClient,Ee as useLiveQuery,Oe as useLoadData};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';require('js-xxhash');var r=class{_value;_meta;_encodeInput;_decodeInput};var s=class e extends r{inner;constructor(t){super(),this.inner=t;}encodeMutation(t,i,n){return this.inner.encodeMutation(t,i,n)}mergeMutation(t,i,n){return this.inner.mergeMutation(t,i,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}unique(){return new e(this.inner.unique())}index(){return new e(this.inner.index())}default(t){let i=new o(this.inner.storageType,this.inner.convertFunc,this.inner.isIndex,this.inner.isUnique,t,this.inner.foreignReference,this.inner.isPrimary);return new e(i)}primary(){return new e(this.inner.primary())}},o=class e extends r{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(t,i,n,a,l,d,T){super(),this.storageType=t,this.convertFunc=i,this.isIndex=n??false,this.isUnique=a??false,this.defaultValue=l,this.foreignReference=d,this.isPrimary=T??false;}encodeMutation(t,i,n){return {value:i,_meta:{timestamp:n}}}mergeMutation(t,i,n){return n&&n._meta.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>0?[n,null]:[{value:this.convertFunc?this.convertFunc(i.value):i.value,_meta:i._meta},i]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new e(this.storageType,this.convertFunc,this.isIndex,true,void 0,this.foreignReference,this.isPrimary)}index(){return new e(this.storageType,this.convertFunc,true,this.isUnique,void 0,this.foreignReference,this.isPrimary)}default(t){return new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,t,this.foreignReference,this.isPrimary)}primary(){return new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,void 0,this.foreignReference,true)}nullable(){if(this.defaultValue===void 0){let t=new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,null,this.foreignReference,this.isPrimary);return new s(t)}return new s(this)}withMeta(){return new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}},p=class e extends o{constructor(){super("integer",t=>Number(t));}static create(){return new e}},V=p.create,y=class e extends o{constructor(t){super("varchar",void 0,void 0,void 0,void 0,t);}static create(){return new e}static createId(){return new e().index().unique().primary()}static createReference(t){return new e(t)}},M=y.create,I=y.createId,A=y.createReference,f=class e extends o{constructor(){super("boolean",t=>typeof t=="string"?t.toLowerCase()==="true":!!t);}static create(){return new e}},b=f.create,m=class e extends o{constructor(){super("timestamp",t=>typeof t=="string"?new Date(t):t);}static create(){return new e}},w=m.create,v=class e extends o{enumValues;enumName;constructor(t,i,n,a,l){super("varchar",void 0,i,n,a,void 0,l),this.enumValues=t,this.enumName=`enum_${t.slice(0,5).join("_").slice(0,50)}`;}getStorageFieldType(){return {type:"varchar",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,primary:this.isPrimary,enumValues:this.enumValues,enumName:this.enumName}}unique(){return new e(this.enumValues,this.isIndex,true,void 0,this.isPrimary)}index(){return new e(this.enumValues,true,this.isUnique,void 0,this.isPrimary)}default(t){return new e(this.enumValues,this.isIndex,this.isUnique,t,this.isPrimary)}primary(){return new e(this.enumValues,this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let t=new e(this.enumValues,this.isIndex,this.isUnique,null,this.isPrimary);return new s(t)}return new s(this)}static create(t){return new e(t)}},N=v.create,x=class e extends o{constructor(t,i,n,a){super("jsonb",l=>typeof l=="string"?JSON.parse(l):l,t,i,n,void 0,a);}getStorageFieldType(){return {type:"jsonb",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue!==void 0?JSON.stringify(this.defaultValue):void 0,primary:this.isPrimary}}unique(){return new e(this.isIndex,true,void 0,this.isPrimary)}index(){return new e(true,this.isUnique,void 0,this.isPrimary)}default(t){return new e(this.isIndex,this.isUnique,t,this.isPrimary)}primary(){return new e(this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let t=new e(this.isIndex,this.isUnique,null,this.isPrimary);return new s(t)}return new s(this)}static create(){return new e}},S=x.create;var u=class e extends r{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(t,i,n,a,l){super(),this.entity=t,this.type=i,this.required=l??false,this.relationalColumn=n,this.foreignColumn=a;}encodeMutation(t,i,n){if(t!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:i,_meta:{timestamp:n}}}mergeMutation(t,i,n){var a;return this.type==="many"?n?[n,null]:[i,i]:(a=n==null?void 0:n._meta)!=null&&a.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[i,i]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (t,i,n)=>new e(t,"one",i,void 0,n??false)}static createManyFactory(){return (t,i,n)=>new e(t,"many",void 0,i,n??false)}},F=(e,t)=>({$type:"relations",collectionName:e.name,objectName:e.name,relations:t({one:u.createOneFactory(),many:u.createManyFactory()})});var c=class e extends r{name;fields;relations;constructor(t,i,n){super(),this.name=t,this.fields=i,this.relations=n??{};}encodeMutation(t,i,n){return Object.fromEntries(Object.entries(i).map(([a,l])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",l,n)]))}mergeMutation(t,i,n){let a={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(i).map(([l,d])=>{let T=this.fields[l]??this.relations[l];if(!T)return [l,d];let[C,R]=T.mergeMutation(t,d,n==null?void 0:n.value[l]);return R&&(a[l]=R),[l,C]}))}},a]}setRelations(t){return new e(this.name,this.fields,t)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(t,i){if(E(i)){let n=i,a=new e(t,n.fields);if(n.relations){let l=n.relations({one:u.createOneFactory(),many:u.createManyFactory()});return new e(t,n.fields,l)}return a}return new e(t,i,void 0)}};function E(e){return typeof e=="object"&&e!==null&&"fields"in e&&typeof e.fields=="object"}var g=c.create,K=g,D=c;var h=e=>typeof e=="object"&&e!==null&&"value"in e&&!Array.isArray(e),L=e=>e?Array.isArray(e.value)?e.value.map(i=>h(i)?L(i):i):typeof e.value!="object"||e.value===null||e.value instanceof Date?e.value:Object.fromEntries(Object.entries(e.value).map(([i,n])=>Array.isArray(n)?[i,n.map(a=>h(a)?L(a):a)]:h(n)?[i,L(n)]:[i,n])):void 0;var O=e=>Object.fromEntries(Object.entries(e).flatMap(([t,i])=>{if(i.$type==="relations")return [];let n=i,a=Object.values(e).find(l=>l.$type==="relations"&&l.collectionName===i.name);return a&&(n=n.setRelations(a.relations)),[[n.name,n]]}));var q={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4};exports.LiveAtomicType=o;exports.LiveBoolean=f;exports.LiveCollection=c;exports.LiveEnum=v;exports.LiveJson=x;exports.LiveNumber=p;exports.LiveObject=D;exports.LiveString=y;exports.LiveTimestamp=m;exports.LiveType=r;exports.LogLevel=q;exports.NullableLiveType=s;exports.Relation=u;exports.boolean=b;exports.collection=g;exports.createRelations=F;exports.createSchema=O;exports.enumType=N;exports.id=I;exports.inferValue=L;exports.json=S;exports.number=V;exports.object=K;exports.reference=A;exports.string=M;exports.timestamp=w;
1
+ 'use strict';require('js-xxhash');var r=class{_value;_meta;_encodeInput;_decodeInput};var s=class e extends r{inner;constructor(t){super(),this.inner=t;}encodeMutation(t,i,n){return this.inner.encodeMutation(t,i,n)}mergeMutation(t,i,n){return this.inner.mergeMutation(t,i,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}unique(){return new e(this.inner.unique())}index(){return new e(this.inner.index())}default(t){let i=new o(this.inner.storageType,this.inner.convertFunc,this.inner.isIndex,this.inner.isUnique,t,this.inner.foreignReference,this.inner.isPrimary);return new e(i)}primary(){return new e(this.inner.primary())}},o=class e extends r{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(t,i,n,a,l,d,T){super(),this.storageType=t,this.convertFunc=i,this.isIndex=n??false,this.isUnique=a??false,this.defaultValue=l,this.foreignReference=d,this.isPrimary=T??false;}encodeMutation(t,i,n){return {value:i,_meta:{timestamp:n}}}mergeMutation(t,i,n){return n&&n._meta.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>0?[n,null]:[{value:this.convertFunc?this.convertFunc(i.value):i.value,_meta:i._meta},i]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new e(this.storageType,this.convertFunc,this.isIndex,true,void 0,this.foreignReference,this.isPrimary)}index(){return new e(this.storageType,this.convertFunc,true,this.isUnique,void 0,this.foreignReference,this.isPrimary)}default(t){return new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,t,this.foreignReference,this.isPrimary)}primary(){return new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,void 0,this.foreignReference,true)}nullable(){if(this.defaultValue===void 0){let t=new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,null,this.foreignReference,this.isPrimary);return new s(t)}return new s(this)}withMeta(){return new e(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}},p=class e extends o{constructor(){super("integer",t=>Number(t));}static create(){return new e}},V=p.create,c=class e extends o{constructor(t){super("varchar",void 0,void 0,void 0,void 0,t);}static create(){return new e}static createId(){return new e().index().unique().primary()}static createReference(t){return new e(t)}},M=c.create,I=c.createId,A=c.createReference,f=class e extends o{constructor(){super("boolean",t=>typeof t=="string"?t.toLowerCase()==="true":!!t);}static create(){return new e}},b=f.create,m=class e extends o{constructor(){super("timestamp",t=>typeof t=="string"?new Date(t):t);}static create(){return new e}},w=m.create,v=class e extends o{enumValues;enumName;constructor(t,i,n,a,l){super("varchar",void 0,i,n,a,void 0,l),this.enumValues=t,this.enumName=`enum_${t.slice(0,5).join("_").slice(0,50)}`;}getStorageFieldType(){return {type:"varchar",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,primary:this.isPrimary,enumValues:this.enumValues,enumName:this.enumName}}unique(){return new e(this.enumValues,this.isIndex,true,void 0,this.isPrimary)}index(){return new e(this.enumValues,true,this.isUnique,void 0,this.isPrimary)}default(t){return new e(this.enumValues,this.isIndex,this.isUnique,t,this.isPrimary)}primary(){return new e(this.enumValues,this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let t=new e(this.enumValues,this.isIndex,this.isUnique,null,this.isPrimary);return new s(t)}return new s(this)}static create(t){return new e(t)}},S=v.create,x=class e extends o{constructor(t,i,n,a){super("jsonb",l=>typeof l=="string"?JSON.parse(l):l,t,i,n,void 0,a);}getStorageFieldType(){return {type:"jsonb",nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue!==void 0?JSON.stringify(this.defaultValue):void 0,primary:this.isPrimary}}unique(){return new e(this.isIndex,true,void 0,this.isPrimary)}index(){return new e(true,this.isUnique,void 0,this.isPrimary)}default(t){return new e(this.isIndex,this.isUnique,t,this.isPrimary)}primary(){return new e(this.isIndex,this.isUnique,void 0,true)}nullable(){if(this.defaultValue===void 0){let t=new e(this.isIndex,this.isUnique,null,this.isPrimary);return new s(t)}return new s(this)}static create(){return new e}},N=x.create;var u=class e extends r{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(t,i,n,a,l){super(),this.entity=t,this.type=i,this.required=l??false,this.relationalColumn=n,this.foreignColumn=a;}encodeMutation(t,i,n){if(t!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:i,_meta:{timestamp:n}}}mergeMutation(t,i,n){var a;return this.type==="many"?n?[n,null]:[i,i]:(a=n==null?void 0:n._meta)!=null&&a.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[i,i]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (t,i,n)=>new e(t,"one",i,void 0,n??false)}static createManyFactory(){return (t,i,n)=>new e(t,"many",void 0,i,n??false)}},F=(e,t)=>({$type:"relations",collectionName:e.name,objectName:e.name,relations:t({one:u.createOneFactory(),many:u.createManyFactory()})});var y=class e extends r{name;fields;relations;constructor(t,i,n){super(),this.name=t,this.fields=i,this.relations=n??{};}encodeMutation(t,i,n){return Object.fromEntries(Object.entries(i).map(([a,l])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",l,n)]))}mergeMutation(t,i,n){let a={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(i).map(([l,d])=>{let T=this.fields[l]??this.relations[l];if(!T)return [l,d];let[C,R]=T.mergeMutation(t,d,n==null?void 0:n.value[l]);return R&&(a[l]=R),[l,C]}))}},a]}setRelations(t){return new e(this.name,this.fields,t)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(t,i){if(E(i)){let n=i,a=new e(t,n.fields);if(n.relations){let l=n.relations({one:u.createOneFactory(),many:u.createManyFactory()});return new e(t,n.fields,l)}return a}return new e(t,i,void 0)}};function E(e){return typeof e=="object"&&e!==null&&"fields"in e&&typeof e.fields=="object"}var g=y.create,K=g,D=y;var h=e=>typeof e=="object"&&e!==null&&"value"in e&&!Array.isArray(e),L=e=>e?Array.isArray(e.value)?e.value.map(i=>h(i)?L(i):i):typeof e.value!="object"||e.value===null||e.value instanceof Date?e.value:Object.fromEntries(Object.entries(e.value).map(([i,n])=>Array.isArray(n)?[i,n.map(a=>h(a)?L(a):a)]:h(n)?[i,L(n)]:[i,n])):void 0;var O=e=>Object.fromEntries(Object.entries(e).flatMap(([t,i])=>{if(i.$type==="relations")return [];let n=i,a=Object.values(e).find(l=>l.$type==="relations"&&l.collectionName===i.name);return a&&(n=n.setRelations(a.relations)),[[n.name,n]]}));var q={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4};exports.LiveAtomicType=o;exports.LiveBoolean=f;exports.LiveCollection=y;exports.LiveEnum=v;exports.LiveJson=x;exports.LiveNumber=p;exports.LiveObject=D;exports.LiveString=c;exports.LiveTimestamp=m;exports.LiveType=r;exports.LogLevel=q;exports.NullableLiveType=s;exports.Relation=u;exports.boolean=b;exports.collection=g;exports.createRelations=F;exports.createSchema=O;exports.enumType=S;exports.id=I;exports.inferValue=L;exports.json=N;exports.number=V;exports.object=K;exports.reference=A;exports.string=M;exports.timestamp=w;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{e as LiveAtomicType,l as LiveBoolean,v as LiveCollection,p as LiveEnum,r as LiveJson,f as LiveNumber,y as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,E as LogLevel,d as NullableLiveType,t as Relation,m as boolean,w as collection,u as createRelations,A as createSchema,q as enumType,j as id,z as inferValue,s as json,g as number,x as object,k as reference,i as string,o as timestamp}from'./chunk-NKM6VWL7.js';
1
+ export{e as LiveAtomicType,l as LiveBoolean,v as LiveCollection,p as LiveEnum,r as LiveJson,f as LiveNumber,y as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,F as LogLevel,d as NullableLiveType,t as Relation,m as boolean,w as collection,u as createRelations,A as createSchema,q as enumType,j as id,z as inferValue,s as json,g as number,x as object,k as reference,i as string,o as timestamp}from'./chunk-3XEJ2M4E.js';
package/dist/server.cjs CHANGED
@@ -1,12 +1,12 @@
1
- 'use strict';var ie=require('crypto'),jsXxhash=require('js-xxhash'),Ht=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 ie__default=/*#__PURE__*/_interopDefault(ie);var Ht__default=/*#__PURE__*/_interopDefault(Ht);var dt=Object.create;var qe=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var ht=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Tt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pt(e))!mt.call(i,r)&&r!==t&&qe(i,r,{get:()=>e[r],enumerable:!(n=yt(e,r))||n.enumerable});return i};var Qe=(i,e,t)=>(t=i!=null?dt(ft(i)):{},Tt(qe(t,"default",{value:i,enumerable:true}),i));var be=ht(ce=>{Object.defineProperty(ce,"__esModule",{value:true});ce.parse=kt;ce.serialize=Bt;var qt=/^[\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,Dt=/^[\u0020-\u003A\u003D-\u007E]*$/,Ft=Object.prototype.toString,_t=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function kt(i,e){let t=new _t,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||zt,o=0;do{let u=i.indexOf("=",o);if(u===-1)break;let s=i.indexOf(";",o),a=s===-1?n:s;if(u>a){o=i.lastIndexOf(";",u-1)+1;continue}let c=Be(i,o,u),d=ze(i,u,c),l=i.slice(c,d);if(t[l]===void 0){let p=Be(i,u+1,a),y=ze(i,a,p),m=r(i.slice(p,y));t[l]=m;}o=a+1;}while(o<n);return t}function Be(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 Bt(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!qt.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(!Dt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);o+="; Path="+t.path;}if(t.expires){if(!Kt(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 zt(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Kt(i){return Ft.call(i)==="[object Date]"}});var he=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),x=i=>i?Array.isArray(i.value)?i.value.map(t=>he(t)?x(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=>he(r)?x(r):r)]:he(n)?[t,x(n)]:[t,n])):void 0;var De="0123456789ABCDEFGHJKMNPQRSTVWXYZ",W=32;var Ct=16,Fe=10,$e=0xffffffffffff;var D;(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";})(D||(D={}));var F=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function At(i){let e=Math.floor(i()*W);return e===W&&(e=W-1),De.charAt(e)}function jt(i){var n;let e=Et(),t=e&&(e.crypto||e.msCrypto)||(typeof ie__default.default<"u"?ie__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=ie__default.default)!=null&&n.randomBytes)return ()=>ie__default.default.randomBytes(1).readUInt8()/255;throw new F(D.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Et(){return Vt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ot(i,e){let t="";for(;i>0;i--)t=At(e)+t;return t}function Pt(i,e=Fe){if(isNaN(i))throw new F(D.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>$e)throw new F(D.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${$e}: ${i}`);if(i<0)throw new F(D.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new F(D.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%W,n=De.charAt(t)+n,i=(i-t)/W;return n}function Vt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function _e(i,e){let t=jt(),n=Date.now();return Pt(n,Fe)+Ot(Ct,t)}var se=()=>_e().toLowerCase(),ae=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ae(n)}return ae(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ae(r)}throw n}}}),Te=i=>i instanceof Promise?i:ae(i);var K=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var oe=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((o,u)=>{let s=this.getBatchKey({resource:e,commonWhere:t,...r}),a={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:o,reject:u};this.queue.has(s)||this.queue.set(s,[]);let c=this.queue.get(s);c&&c.push(a),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var p;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:o,sort:u}=t,s=e.length===1?t.limit:void 0,a=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),c=r,d=(p=Object.entries(a[0]??{})[0])==null?void 0:p[0];if(a.length>0){let y=a.map(m=>m[d]).filter(m=>m!=null);y.length>0&&(c=K(r,{[d]:{$in:y}}));}let l=await this.storage.get({resource:n,where:c,include:o,sort:u,limit:s});for(let y of e){let m=l;if(y.uniqueWhere){let[f,h]=Object.entries(y.uniqueWhere)[0];m=l.filter(g=>{var T;return ((T=g.value[f])==null?void 0:T.value)===h});}y.resolve(m);}}};var N=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),_=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let o=u=>{u.$and?u.$and.forEach(o):u.$or?u.$or.forEach(o):Object.entries(u).forEach(([s,a])=>{var c;if((c=r.relations)!=null&&c[s]&&(n[s]=true,typeof a=="object"&&a!==null&&!Array.isArray(a))){let d=_(a,r.relations[s].entity.name,t);Object.keys(d).length>0&&(n[s]={include:d});}});};return o(i),n},A=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(u=>A(i,u,t));if(n==="$or")return r.some(u=>A(i,u,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 A(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 u=i[n];return !u||typeof u!="object"&&!Array.isArray(u)?false:Array.isArray(u)?t?!u.some(s=>A(s,r,false)):u.some(s=>A(s,r,false)):A(u,r,t)}return t?i[n]!==o:i[n]===o}),Q={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},ge=class{level;prefix;constructor(e={}){this.level=e.level??Q.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=Q.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=Q.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=Q.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=Q.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=Q.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},ke=i=>new ge(i);function Re(i){return N({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}var ue=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,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),u=this.objectNodes.get(t);if(o&&o.referencesObjects.set(n,t),u&&r){let s=u.referencedByObjects.get(r);s||(s=new Set,u.referencedByObjects.set(r,s)),s.add(e);}}removeRelation(e,t,n,r){let o=this.objectNodes.get(e),u=this.objectNodes.get(t);if(o&&o.referencesObjects.delete(n),u&&r){let s=u.referencedByObjects.get(r);s&&(s.delete(e),s.size===0&&u.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 u=this.schema[t];if(u!=null&&u.relations){if(o.type==="many"&&o.foreignColumn){for(let[s,a]of Object.entries(u.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(u.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),u=this.objectNodes.get(t);if(u)for(let[s,{relationName:a,targetResource:c}]of Array.from(o)){if(!(r&&s in r))continue;let l=this.getInverseRelationName(e,c,a),p=u.referencesObjects.get(a),y=n[s];p!==y&&(p&&this.removeRelation(t,p,a,l),y&&(this.ensureObjectNode(y,c),this.storeRelation(t,y,a,l)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new oe(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),o={},u=[];for(let s of r){this.logger.debug("[QueryEngine] Subscribing to step",s.stepPath.join("."));let a=Re(s),c=o[s.stepPath.at(-2)??""],d=s.stepPath.at(-1)??"",l=this.queryNodes.get(a);if(l)l.subscriptions.add(t);else if(l={hash:a,queryStep:s,relationName:d,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:c,childQueries:new Set},this.queryNodes.set(l.hash,l),c){let p=this.queryNodes.get(c);p&&p.childQueries.add(l.hash);}o[d]=a,u.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 u)s();}}breakdownQuery(e){var h;let{query:t,stepPath:n=[],context:r={},parentResource:o}=e,{include:u}=t,s=n.length===0,a=n.at(-1),c,d,l;if(!s&&o&&a){let g=this.schema[o],T=(h=g==null?void 0:g.relations)==null?void 0:h[a];T&&(l=T.type==="many",T.type==="one"?(c=R=>({id:R}),d=R=>R.map(b=>{var S,I;return (I=(S=b.value)==null?void 0:S[T.relationalColumn])==null?void 0:I.value}).filter(b=>b!==void 0)):(c=R=>({[T.foreignColumn]:R}),d=R=>R.map(b=>{var S,I;return (I=(S=b.value)==null?void 0:S.id)==null?void 0:I.value}).filter(b=>b!==void 0)));}let{include:p,...y}=t,f=[this.router.incrementQueryStep({query:y,stepPath:[...n],getWhere:c,referenceGetter:d,isMany:l,relationName:a},r)];if(u&&typeof u=="object"&&Object.keys(u).length>0){let g=this.schema[t.resource];if(!g)throw new Error(`Resource ${t.resource} not found`);f.push(...Object.entries(u).flatMap(([T,R])=>{let b=g.relations[T];if(!b)throw new Error(`Relation ${T} not found for resource ${t.resource}`);let S=b.entity.name;return this.breakdownQuery({query:{resource:S,include:typeof R=="object"?R:void 0},stepPath:[...n,T],context:r,parentResource:t.resource})}));}return f}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(o=>o.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(o=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",o.length),n[e[0].stepPath.join(".")]=[{data:o}];});for(let o=1;o<e.length;o++){let u=e[o],s=u.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var c,d;let a=n[s];if(!a){n[u.stepPath.join(".")]=[];return}if(u.referenceGetter&&u.getWhere){let l=new Map;for(let m of a)for(let f of m.data){let h=(d=(c=f==null?void 0:f.value)==null?void 0:c.id)==null?void 0:d.value;if(!h)continue;let T=u.referenceGetter([f])[0];if(T){l.has(T)||l.set(T,new Set);let R=l.get(T);R&&R.add(h);}}let p=Array.from(l.keys());if(p.length===0){n[u.stepPath.join(".")]=[];return}let y=[];for(let m of p){let f=u.getWhere(m),h={...u,relationalWhere:f},g=await this.resolveStep(h,t),T=l.get(m);if(T)for(let R of Array.from(T))y.push({includedBy:R,data:g});}this.logger.debug("[QueryEngine] Resolved step",u.stepPath.join("."),"with results count:",y.reduce((m,f)=>m+f.data.length,0)),n[u.stepPath.join(".")]=y;}else {let l=await this.resolveStep(u,t);n[u.stepPath.join(".")]=[{data:l}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var u,s,a,c,d;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let n=new Map;for(let l of e){let p=l.stepPath.join("."),y=t[p]??[],m=Object.keys(l.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${p}"`,{resource:l.query.resource,includedRelations:m,resultGroups:y.length,isMany:l.isMany,relationName:l.relationName});for(let f of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${p}"`,{dataCount:f.data.length,includedBy:f.includedBy});for(let h of f.data){let g=(s=(u=h==null?void 0:h.value)==null?void 0:u.id)==null?void 0:s.value;if(!g){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${p}"`);continue}let T=p?`${p}.${g}`:g,R=[];if(l.stepPath.length>0&&f.includedBy){let S=l.stepPath.slice(0,-1).join(".");R=[S?`${S}.${f.includedBy}`:f.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${T}" has parent keys:`,R,{stepPath:p,parentStepPath:S,includedBy:f.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${T}" (no parent)`);let b=n.get(T);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${T}" already exists, adding parent keys:`,R);for(let S of R)b.includedBy.add(S);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${T}"`,{resource:l.query.resource,path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,includedRelations:m,parentKeys:R}),n.set(T,{data:h,includedBy:new Set(R),path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,resourceName:l.query.resource,includedRelations:m});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),o=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let l=r.length-1;l>=0;l--){let[p,y]=r[l],m=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${p}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let f of y.includedRelations){let h=(c=(a=m==null?void 0:m.relations)==null?void 0:a[f])==null?void 0:c.type,g=!!y.data.value[f];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${f}" for "${p}"`,{relationType:h,hasRelation:g,resourceHasRelation:!!((d=m==null?void 0:m.relations)!=null&&d[f])}),y.data.value[f])this.logger.debug(`[QueryEngine] assembleResults: Relation "${f}" already exists for "${p}"`,y.data.value[f]);else {let T=h==="many"?{value:[]}:{value:null};y.data.value[f]=T,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${f}" for "${p}" with`,T);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${p}" to resultData`),o.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to ${y.includedBy.size} parent(s)`);for(let f of Array.from(y.includedBy)){let h=n.get(f);if(!h){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${f}" not found in entriesMap for child "${p}"`);continue}let g=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to parent "${f}" via relation "${g}"`,{isMany:y.isMany,parentHasRelation:!!h.data.value[g]}),y.isMany?(h.data.value[g]??={value:[]},h.data.value[g].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${p}" to many relation "${g}" on parent "${f}"`,{arrayLength:h.data.value[g].value.length})):(h.data.value[g]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${g}" on parent "${f}" to "${p}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${o.length} root items`),o}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:n,relationalWhere:r}=e,o=n.where&&r?K(n.where,r):r??n.where,u=o?{...n,where:o}:n;return Te(this.router.get(u,t)).then(s=>(this.loadStepResults(e,s),s))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=Re(e),r=this.queryNodes.get(n),o=e.query.resource;if(!r)return;let u=this.getRelationalColumns(o);for(let s of t){let a=x(s),c=a.id;this.ensureObjectNode(c,o,n),r.trackedObjects.add(c);for(let[d,{relationName:l,targetResource:p}]of Array.from(u)){let y=a[d];if(y){this.ensureObjectNode(y,p);let m=this.getInverseRelationName(o,p,l);this.storeRelation(c,y,l,m);}}this.loadNestedRelations(o,c,a),this.logger.debug("[QueryEngine] Loaded nested relations for",c);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[o,u]of Object.entries(r.relations)){let s=n[o];if(!s)continue;let a=u.entity.name,c=this.getInverseRelationName(e,a,o);if(u.type==="one")s&&typeof s=="object"&&s.id&&(this.ensureObjectNode(s.id,a),this.storeRelation(t,s.id,o,c),this.loadNestedRelations(a,s.id,s));else if(u.type==="many"&&Array.isArray(s)){for(let d of s)if(d&&typeof d=="object"&&d.id){this.ensureObjectNode(d.id,a);let l=this.getInverseRelationName(a,e,o);l&&this.storeRelation(d.id,t,l,o),this.loadNestedRelations(a,d.id,d);}}}}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 u=this.buildIncludeFromChildQueries(r);n[o.relationName]=Object.keys(u).length>0?u:true;}return n}sendInsertsForTree(e,t,n){var s,a;let r=(a=(s=t==null?void 0:t.value)==null?void 0:s.id)==null?void 0:a.value;if(!r)return;let o={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let c of Array.from(e.subscriptions))try{c(o);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let c of Array.from(e.childQueries)){let d=this.queryNodes.get(c);if(!d||!d.relationName)continue;let l=d.relationName,p=d.queryStep.query.resource,y=t.value[l];if(!y)continue;let m=y.value;if(Array.isArray(m))for(let f of m)this.sendInsertsForTree(d,f,p);else m&&typeof m=="object"&&this.sendInsertsForTree(d,m,p);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=x(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:c}]of Array.from(o)){let d=n[s];if(d){this.ensureObjectNode(d,c);let l=this.getInverseRelationName(e.resource,c,a);this.storeRelation(e.resourceId,d,a,l);}}let u=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(s=>{for(let a of s){let c=this.queryNodes.get(a);if(c){c.trackedObjects.add(e.resourceId),u&&u.matchedQueries.add(a);for(let d of Array.from(c.subscriptions))try{d(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(".")});}}}});return}if(e.procedure==="UPDATE"){let n=x(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.getMatchingQueries(e,n).then(u=>{let s=new Set(u),a=[],c=[],d=[];for(let p of u)o.has(p)?d.push(p):a.push(p);for(let p of Array.from(o))s.has(p)||c.push(p);for(let p of a){let y=this.queryNodes.get(p);y&&y.trackedObjects.add(e.resourceId);}for(let p of c){let y=this.queryNodes.get(p);y&&y.trackedObjects.delete(e.resourceId);}let l=this.objectNodes.get(e.resourceId);if(l){for(let p of a)l.matchedQueries.add(p);for(let p of c)l.matchedQueries.delete(p);}for(let p of [...c,...d]){let y=this.queryNodes.get(p);if(y)for(let m of Array.from(y.subscriptions))try{m(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 p of a){let y=this.queryNodes.get(p);if(!y)continue;let m=this.buildIncludeFromChildQueries(p);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(m).length>0?m:void 0}).then(f=>{!f||f.length===0||this.sendInsertsForTree(y,f[0],e.resource);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?Te([]):Promise.all(n.map(async r=>{let o=r.queryStep.query.where,u=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,m=y==null?void 0:y.queryStep.query.resource,f=m?this.getInverseRelationName(m,u,r.relationName):void 0,h=f?a.referencesObjects.get(f):void 0;if(!h)return {hash:r.hash,matches:false};let g=this.objectNodes.get(h);return !g||!y||!g.matchedQueries.has(y.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!o)return {hash:r.hash,matches:true};let c=_(o,u,this.schema),d=Object.keys(c).length>0;if(!d&&t!==void 0)return {hash:r.hash,matches:A(t,o)};let l=await this.storage.get({resource:u,where:{id:s},include:d?c:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let p=x(l[0]);return p?{hash:r.hash,matches:A(p,o)}:{hash:r.hash,matches:false}})).then(r=>r.filter(o=>o.matches).map(o=>o.hash))}};var Je=Qe(be());var 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(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),Se=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()})),Ut=Se.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ke=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),Ue=zod.z.object({timestamp:zod.z.string().optional()}).optional(),U=Ke.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:Ue}),H=Ke.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:Ut,meta:Ue});zod.z.union([H,U]);var We=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var He=le.omit({resource:true}),ve=U.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:U.shape.meta}),xe=H.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([xe,ve]);var we=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(we);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=we(n);return e}return i},Ge=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?Je.default.parse(r.cookie):{}},u=new URL(t.url),s=u.pathname.split("/"),a=u.searchParams,c=we(Ht__default.default.parse(a.toString())),d=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:o.headers,cookies:o.cookies,queryParams:c}))??{};if(t.method==="GET"){let l=s[s.length-1],{success:p,data:y,error:m}=He.safeParse(c);if(!p)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:m},{status:400});let f=await i.handleQuery({req:{...o,...y,type:"QUERY",resource:l,context:d,queryParams:c}});return !f||!f.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(f.data)}if(t.method==="POST")try{let l=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 g=s[s.length-3],T=t.body?await t.json():{};if(!g||g.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let R=await i.handleCustomQuery({req:{...o,type:"CUSTOM_QUERY",resource:g,procedure:l,input:T.input,context:d,queryParams:c}});return Response.json(R)}let y=p,m=t.body?await t.json():{},f;if(l==="insert"||l==="update"){let{success:g,data:T,error:R}=xe.safeParse(m);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});f=T;}else {let{success:g,data:T,error:R}=ve.safeParse(m);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});f=T;}let h=await i.handleMutation({req:{...o,type:"MUTATE",resource:y,input:f.payload,context:d,resourceId:f.resourceId,procedure:l==="insert"||l==="update"?l.toUpperCase():l,queryParams:{},meta:f.meta}});return Response.json(h)}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 Xe=Qe(be());var $=zod.z.string(),Me=zod.z.union([We,le]),Jt=zod.z.object({id:$,type:zod.z.literal("SUBSCRIBE")}).and(Me),Gt=zod.z.object({id:$,type:zod.z.literal("UNSUBSCRIBE")}).and(Me),Zt=zod.z.object({id:$,type:zod.z.literal("QUERY")}).and(Me),Yt=zod.z.object({id:$,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),Ze=H.extend({id:$}),Xt=U.extend({id:$}),en=zod.z.union([Xt,Ze]),Ye=zod.z.union([Jt,Zt,Yt,en,Gt]),tn=zod.z.object({id:$,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),nn=zod.z.object({id:$,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([tn,nn,Ze]);zod.z.object({resource:zod.z.string(),data:zod.z.array(Se)});var et=i=>{let e={},t=i.logger;return (n,r)=>{var l;let o=p=>{n.send(JSON.stringify(p));},u=se(),s=new Map,a={headers:r.headers,cookies:typeof r.headers.cookie=="string"?Xe.default.parse(r.headers.cookie):{}},c=Ht.parse(r.url.split("?")[1]),d=(l=i.contextProvider)==null?void 0:l.call(i,{transport:"WEBSOCKET",headers:a.headers,cookies:a.cookies,queryParams:c});e[u]=n,t.info("Client connected:",u),n.on("message",async p=>{try{t.debug("Message received from the client:",p);let y=Ye.parse(JSON.parse(p.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:m,id:f,...h}=y,g=m==="SUBSCRIBE";if("procedure"in h){let T=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h.resource,procedure:h.procedure,input:h.input,context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(g){if(!T||!T.data||!T.query)throw new Error("Invalid resource");T.unsubscribe&&s.set(N(h),T.unsubscribe),o({id:f,type:"REPLY",data:{resource:T.query.resource,data:(T.data??[]).map(R=>R.value)}});}else o({id:f,type:"REPLY",data:T});}else {let T=await i.handleQuery({req:{...a,...h,type:"QUERY",context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(!T||!T.data)throw new Error("Invalid resource");g&&T.unsubscribe&&s.set(N(h),T.unsubscribe),o({id:f,type:"REPLY",data:{resource:h.resource,data:(T.data??[]).map(R=>R.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:m,id:f,...h}=y,g=s.get(N(h));g&&(g(),s.delete(N(h)));}else if(y.type==="CUSTOM_QUERY"){let{resource:m,procedure:f,input:h,id:g}=y;t.debug("Received custom query from client:",y);try{let T=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:m,procedure:f,input:h,context:await d??{},queryParams:c}});o({id:g,type:"REPLY",data:T});}catch(T){o({id:g,type:"REJECT",resource:m,message:T.message}),t.error("Error handling custom query from the client:",T);}}else if(y.type==="MUTATE"){let{resource:m}=y;t.debug("Received mutation from client:",y);try{let f=await i.handleMutation({req:{...a,type:"MUTATE",resource:m,input:y.payload,context:{messageId:y.id,...await d??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:c,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&o({id:y.id,type:"REPLY",data:f});}catch(f){o({id:y.id,type:"REJECT",resource:m,message:f.message}),t.error("Error parsing mutation from the client:",f);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",u),delete e[u];for(let p of Array.from(s.values()))p();});}};function tt(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 Nr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,et(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{Ge(e)(tt(n)).then(u=>u.json().then(s=>r.status(u.status).send(s)));});};var de=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,o,u,s,a){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=o,this._single=u,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 an=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Ie=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>an(n)?x(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function k(i,e){let t=new Ie(i),n=o=>{let u=de._init(o,t,true);return Object.assign(Object.create(u),{insert:a=>i.insert(o,a),update:(a,c)=>i.update(o,a,c)})},r={get(o,u){if(u==="findOne")return i.findOne.bind(i);if(u==="find")return i.find.bind(i);if(u==="insert")return i.insert.bind(i);if(u==="update")return i.update.bind(i);if(u==="transaction")return async s=>i.transaction(async({trx:a,commit:c,rollback:d})=>{let l=k(a,e);return s({trx:l,commit:c,rollback:d})});if(u in e){let s=e[u];return n(s)}}};return new Proxy({},r)}var Le=class i{routes;hooksRegistry=new Map;constructor(e){this.routes=e.routes;for(let t of Object.values(e.routes)){if(t.resourceSchema===void 0)continue;let n=t;n.hooks&&this.hooksRegistry.set(n.resourceSchema.name,n.hooks);}}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}},Kr=i=>Le.create({...i}),rt=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),it=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),Ce=class i{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,n,r,o){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=n??{},this.authorization=r,this.hooks=o;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:it,query:rt}),n={},r={};for(let[o,u]of Object.entries(t))u._type==="mutation"?n[o]=u:r[o]=u;return new i(this.resourceSchema,n,r,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new i(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},o=N(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:o}})(e);handleMutation=async({req:e,db:t,schema:n})=>{var s;let r=((s=e.meta)==null?void 0:s.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r),u=k(o,n);return await this.wrapInMiddlewares(async a=>{if(!a.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[a.procedure];if(c){let d=c.inputValidator["~standard"].validate(a.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.issues.map(y=>{var f;let m=(f=y.path)==null?void 0:f.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}return a.input=l.value,c.handler({req:a,db:u})}else {if(a.procedure==="INSERT"||a.procedure==="UPDATE")return this.handleSet({req:a,db:o,operation:a.procedure,schema:n});throw new Error(`Unknown procedure: ${a.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=k(t,n);return await this.wrapInMiddlewares(async o=>{let u=this.customQueries[o.procedure];if(!u)throw new Error(`Unknown query procedure: ${o.procedure}`);let s=u.inputValidator["~standard"].validate(o.input),a=s instanceof Promise?await s:s;if(a.issues){let c=a.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return o.input=a.value,u.handler({req:o,db:r})})(e)};getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let o=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&o)throw new Error("Resource already exists");if(n==="UPDATE"&&!o)throw new Error("Resource not found");let u={value:e.input};return t.transaction(async({trx:s})=>{var d,l,p,y,m,f,h;if(n==="INSERT"){let{data:g,acceptedValues:T}=await s.rawInsert(e.resource,e.resourceId,u,(d=e.context)==null?void 0:d.messageId,e.context);if(!T)throw new Error("Mutation rejected");let R=x(g);if(R.id=R.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let S=_(b,e.resource,r),I=Object.keys(S).length>0?await s.rawFindById(e.resource,e.resourceId,S):g,w=x(I);if(w.id=w.id??e.resourceId,!A(w,b))throw new Error("Not authorized")}}return {data:g,acceptedValues:T}}if((y=(p=this.authorization)==null?void 0:p.update)!=null&&y.preMutation){let g=x(o);g.id=g.id??e.resourceId;let T=this.authorization.update.preMutation({ctx:e.context,value:g});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let R=_(T,e.resource,r),b=Object.keys(R).length>0?await s.rawFindById(e.resource,e.resourceId,R):o,S=x(b);if(S.id=S.id??e.resourceId,!A(S,T))throw new Error("Not authorized")}}let{data:a,acceptedValues:c}=await s.rawUpdate(e.resource,e.resourceId,u,(m=e.context)==null?void 0:m.messageId,e.context);if(!c)throw new Error("Mutation rejected");if((h=(f=this.authorization)==null?void 0:f.update)!=null&&h.postMutation){let g=x(a);g.id=g.id??e.resourceId;let T=this.authorization.update.postMutation({ctx:e.context,value:g});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let R=_(T,e.resource,r),b=Object.keys(R).length>0?await s.rawFindById(e.resource,e.resourceId,R):a,S=x(b);if(S.id=S.id??e.resourceId,!A(S,T))throw new Error("Not authorized")}}return {data:a,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}},Ae=class{resourceSchema=void 0;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 s;let r=((s=e.meta)==null?void 0:s.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r),u=k(o,n);return await this.wrapInMiddlewares(async a=>{if(!a.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[a.procedure];if(c){let d=c.inputValidator["~standard"].validate(a.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.issues.map(y=>{var f;let m=(f=y.path)==null?void 0:f.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}return a.input=l.value,c.handler({req:a,db:u})}throw new Error(`Unknown procedure: ${a.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=k(t,n);return await this.wrapInMiddlewares(async o=>{let u=this.customQueries[o.procedure];if(!u)throw new Error(`Unknown query procedure: ${o.procedure}`);let s=u.inputValidator["~standard"].validate(o.input),a=s instanceof Promise?await s:s;if(a.issues){let c=a.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return o.input=a.value,u.handler({req:o,db:r})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}},je=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Ce(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:it,query:rt}),n={},r={};for(let[o,u]of Object.entries(t))u._type==="mutation"?n[o]=u:r[o]=u;return new Ae(n,r).use(...this.middlewares)}use(...e){return new i([...this.middlewares,...e])}static create(){return new i}},Ur=je.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(([o,u])=>[o,{value:u,_meta:{timestamp:n}}]))});return x(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:o,...u}=n,s=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(u).map(([d,l])=>[d,{value:l,_meta:{timestamp:r}}]))}),a=x(s.data),c={};for(let d of Object.keys(u))d in a&&(c[d]=a[d]);return c}};var yn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function q(i){var r,o,u;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((u=(o=t.constructor)==null?void 0:o.name)==null?void 0:u.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function at(i){let e=q(i);return yn[e]}var pn="42701";function G(i){var t;if(i.code===pn)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 Oe(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 fn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let o of Object.values(e))for(let u of Object.values(o.fields)){let s=u.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:u,values:s}=o;try{let a=s.map(c=>`'${c}'`).join(", ");await kysely.sql`
1
+ 'use strict';var ie=require('crypto'),jsXxhash=require('js-xxhash'),Jt=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 ie__default=/*#__PURE__*/_interopDefault(ie);var Jt__default=/*#__PURE__*/_interopDefault(Jt);var yt=Object.create;var Qe=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var Tt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var gt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mt(e))!ht.call(i,r)&&r!==t&&Qe(i,r,{get:()=>e[r],enumerable:!(n=pt(e,r))||n.enumerable});return i};var $e=(i,e,t)=>(t=i!=null?yt(ft(i)):{},gt(Qe(t,"default",{value:i,enumerable:true}),i));var Se=Tt(le=>{Object.defineProperty(le,"__esModule",{value:true});le.parse=Bt;le.serialize=zt;var Qt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,$t=/^[\u0021-\u003A\u003C-\u007E]*$/,Dt=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Ft=/^[\u0020-\u003A\u003D-\u007E]*$/,_t=Object.prototype.toString,kt=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Bt(i,e){let t=new kt,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Kt,o=0;do{let u=i.indexOf("=",o);if(u===-1)break;let s=i.indexOf(";",o),a=s===-1?n:s;if(u>a){o=i.lastIndexOf(";",u-1)+1;continue}let c=ze(i,o,u),d=Ke(i,u,c),l=i.slice(c,d);if(t[l]===void 0){let p=ze(i,u+1,a),y=Ke(i,a,p),f=r(i.slice(p,y));t[l]=f;}o=a+1;}while(o<n);return t}function ze(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function Ke(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function zt(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Qt.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!$t.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(!Dt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);o+="; Domain="+t.domain;}if(t.path){if(!Ft.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);o+="; Path="+t.path;}if(t.expires){if(!Ut(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 Kt(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Ut(i){return _t.call(i)==="[object Date]"}});var Te=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),w=i=>i?Array.isArray(i.value)?i.value.map(t=>Te(t)?w(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=>Te(r)?w(r):r)]:Te(n)?[t,w(n)]:[t,n])):void 0;var Fe="0123456789ABCDEFGHJKMNPQRSTVWXYZ",W=32;var At=16,_e=10,De=0xffffffffffff;var D;(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";})(D||(D={}));var F=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function jt(i){let e=Math.floor(i()*W);return e===W&&(e=W-1),Fe.charAt(e)}function Et(i){var n;let e=Ot(),t=e&&(e.crypto||e.msCrypto)||(typeof ie__default.default<"u"?ie__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=ie__default.default)!=null&&n.randomBytes)return ()=>ie__default.default.randomBytes(1).readUInt8()/255;throw new F(D.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ot(){return Nt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Pt(i,e){let t="";for(;i>0;i--)t=jt(e)+t;return t}function Vt(i,e=_e){if(isNaN(i))throw new F(D.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>De)throw new F(D.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${De}: ${i}`);if(i<0)throw new F(D.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new F(D.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%W,n=Fe.charAt(t)+n,i=(i-t)/W;return n}function Nt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ke(i,e){let t=Et(),n=Date.now();return Vt(n,_e)+Pt(At,t)}var se=()=>ke().toLowerCase(),ae=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ae(n)}return ae(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ae(r)}throw n}}}),ge=i=>i instanceof Promise?i:ae(i);var K=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var oe=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((o,u)=>{let s=this.getBatchKey({resource:e,commonWhere:t,...r}),a={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:o,reject:u};this.queue.has(s)||this.queue.set(s,[]);let c=this.queue.get(s);c&&c.push(a),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var p;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:o,sort:u}=t,s=e.length===1?t.limit:void 0,a=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),c=r,d=(p=Object.entries(a[0]??{})[0])==null?void 0:p[0];if(a.length>0){let y=a.map(f=>f[d]).filter(f=>f!=null);y.length>0&&(c=K(r,{[d]:{$in:y}}));}let l=await this.storage.get({resource:n,where:c,include:o,sort:u,limit:s});for(let y of e){let f=l;if(y.uniqueWhere){let[m,h]=Object.entries(y.uniqueWhere)[0];f=l.filter(g=>{var T;return ((T=g.value[m])==null?void 0:T.value)===h});}y.resolve(f);}}};var N=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),_=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let o=u=>{u.$and?u.$and.forEach(o):u.$or?u.$or.forEach(o):Object.entries(u).forEach(([s,a])=>{var c;if((c=r.relations)!=null&&c[s]&&(n[s]=true,typeof a=="object"&&a!==null&&!Array.isArray(a))){let d=_(a,r.relations[s].entity.name,t);Object.keys(d).length>0&&(n[s]={include:d});}});};return o(i),n},A=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(u=>A(i,u,t));if(n==="$or")return r.some(u=>A(i,u,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 A(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 u=i[n];return !u||typeof u!="object"&&!Array.isArray(u)?false:Array.isArray(u)?t?!u.some(s=>A(s,r,false)):u.some(s=>A(s,r,false)):A(u,r,t)}return t?i[n]!==o:i[n]===o}),ue=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},Q={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},Re=class{level;prefix;constructor(e={}){this.level=e.level??Q.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=Q.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=Q.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=Q.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=Q.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=Q.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},Be=i=>new Re(i);function be(i){return N({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}var ce=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,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),u=this.objectNodes.get(t);if(o&&o.referencesObjects.set(n,t),u&&r){let s=u.referencedByObjects.get(r);s||(s=new Set,u.referencedByObjects.set(r,s)),s.add(e);}}removeRelation(e,t,n,r){let o=this.objectNodes.get(e),u=this.objectNodes.get(t);if(o&&o.referencesObjects.delete(n),u&&r){let s=u.referencedByObjects.get(r);s&&(s.delete(e),s.size===0&&u.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 u=this.schema[t];if(u!=null&&u.relations){if(o.type==="many"&&o.foreignColumn){for(let[s,a]of Object.entries(u.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(u.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),u=this.objectNodes.get(t);if(u)for(let[s,{relationName:a,targetResource:c}]of Array.from(o)){if(!(r&&s in r))continue;let l=this.getInverseRelationName(e,c,a),p=u.referencesObjects.get(a),y=n[s];p!==y&&(p&&this.removeRelation(t,p,a,l),y&&(this.ensureObjectNode(y,c),this.storeRelation(t,y,a,l)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new oe(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),o={},u=[];for(let s of r){this.logger.debug("[QueryEngine] Subscribing to step",s.stepPath.join("."));let a=be(s),c=o[s.stepPath.at(-2)??""],d=s.stepPath.at(-1)??"",l=this.queryNodes.get(a);if(l)l.subscriptions.add(t);else if(l={hash:a,queryStep:s,relationName:d,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:c,childQueries:new Set},this.queryNodes.set(l.hash,l),c){let p=this.queryNodes.get(c);p&&p.childQueries.add(l.hash);}o[d]=a,u.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 u)s();}}breakdownQuery(e){var h;let{query:t,stepPath:n=[],context:r={},parentResource:o}=e,{include:u}=t,s=n.length===0,a=n.at(-1),c,d,l;if(!s&&o&&a){let g=this.schema[o],T=(h=g==null?void 0:g.relations)==null?void 0:h[a];T&&(l=T.type==="many",T.type==="one"?(c=R=>({id:R}),d=R=>R.map(b=>{var S,v;return (v=(S=b.value)==null?void 0:S[T.relationalColumn])==null?void 0:v.value}).filter(b=>b!==void 0)):(c=R=>({[T.foreignColumn]:R}),d=R=>R.map(b=>{var S,v;return (v=(S=b.value)==null?void 0:S.id)==null?void 0:v.value}).filter(b=>b!==void 0)));}let{include:p,...y}=t,m=[this.router.incrementQueryStep({query:y,stepPath:[...n],getWhere:c,referenceGetter:d,isMany:l,relationName:a},r)];if(u&&typeof u=="object"&&Object.keys(u).length>0){let g=this.schema[t.resource];if(!g)throw new Error(`Resource ${t.resource} not found`);m.push(...Object.entries(u).flatMap(([T,R])=>{let b=g.relations[T];if(!b)throw new Error(`Relation ${T} not found for resource ${t.resource}`);let S=b.entity.name,v=ue(R)?R:null;return this.breakdownQuery({query:{resource:S,include:v?v.include:typeof R=="object"?R:void 0,where:v==null?void 0:v.where,limit:v==null?void 0:v.limit,sort:v==null?void 0:v.orderBy},stepPath:[...n,T],context:r,parentResource:t.resource})}));}return m}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(o=>o.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(o=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",o.length),n[e[0].stepPath.join(".")]=[{data:o}];});for(let o=1;o<e.length;o++){let u=e[o],s=u.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var c,d;let a=n[s];if(!a){n[u.stepPath.join(".")]=[];return}if(u.referenceGetter&&u.getWhere){let l=new Map;for(let f of a)for(let m of f.data){let h=(d=(c=m==null?void 0:m.value)==null?void 0:c.id)==null?void 0:d.value;if(!h)continue;let T=u.referenceGetter([m])[0];if(T){l.has(T)||l.set(T,new Set);let R=l.get(T);R&&R.add(h);}}let p=Array.from(l.keys());if(p.length===0){n[u.stepPath.join(".")]=[];return}let y=[];for(let f of p){let m=u.getWhere(f),h={...u,relationalWhere:m},g=await this.resolveStep(h,t),T=l.get(f);if(T)for(let R of Array.from(T))y.push({includedBy:R,data:g});}this.logger.debug("[QueryEngine] Resolved step",u.stepPath.join("."),"with results count:",y.reduce((f,m)=>f+m.data.length,0)),n[u.stepPath.join(".")]=y;}else {let l=await this.resolveStep(u,t);n[u.stepPath.join(".")]=[{data:l}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var u,s,a,c,d;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let n=new Map;for(let l of e){let p=l.stepPath.join("."),y=t[p]??[],f=Object.keys(l.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${p}"`,{resource:l.query.resource,includedRelations:f,resultGroups:y.length,isMany:l.isMany,relationName:l.relationName});for(let m of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${p}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let h of m.data){let g=(s=(u=h==null?void 0:h.value)==null?void 0:u.id)==null?void 0:s.value;if(!g){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${p}"`);continue}let T=p?`${p}.${g}`:g,R=[];if(l.stepPath.length>0&&m.includedBy){let S=l.stepPath.slice(0,-1).join(".");R=[S?`${S}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${T}" has parent keys:`,R,{stepPath:p,parentStepPath:S,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${T}" (no parent)`);let b=n.get(T);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${T}" already exists, adding parent keys:`,R);for(let S of R)b.includedBy.add(S);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${T}"`,{resource:l.query.resource,path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,includedRelations:f,parentKeys:R}),n.set(T,{data:h,includedBy:new Set(R),path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,resourceName:l.query.resource,includedRelations:f});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),o=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let l=r.length-1;l>=0;l--){let[p,y]=r[l],f=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${p}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let m of y.includedRelations){let h=(c=(a=f==null?void 0:f.relations)==null?void 0:a[m])==null?void 0:c.type,g=!!y.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${p}"`,{relationType:h,hasRelation:g,resourceHasRelation:!!((d=f==null?void 0:f.relations)!=null&&d[m])}),y.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${p}"`,y.data.value[m]);else {let T=h==="many"?{value:[]}:{value:null};y.data.value[m]=T,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${p}" with`,T);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${p}" to resultData`),o.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to ${y.includedBy.size} parent(s)`);for(let m of Array.from(y.includedBy)){let h=n.get(m);if(!h){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${p}"`);continue}let g=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to parent "${m}" via relation "${g}"`,{isMany:y.isMany,parentHasRelation:!!h.data.value[g]}),y.isMany?(h.data.value[g]??={value:[]},h.data.value[g].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${p}" to many relation "${g}" on parent "${m}"`,{arrayLength:h.data.value[g].value.length})):(h.data.value[g]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${g}" on parent "${m}" to "${p}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${o.length} root items`),o}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:n,relationalWhere:r}=e,o=n.where&&r?K(n.where,r):r??n.where,u=o?{...n,where:o}:n;return ge(this.router.get(u,t)).then(s=>(this.loadStepResults(e,s),s))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=be(e),r=this.queryNodes.get(n),o=e.query.resource;if(!r)return;let u=this.getRelationalColumns(o);for(let s of t){let a=w(s),c=a.id;this.ensureObjectNode(c,o,n),r.trackedObjects.add(c);for(let[d,{relationName:l,targetResource:p}]of Array.from(u)){let y=a[d];if(y){this.ensureObjectNode(y,p);let f=this.getInverseRelationName(o,p,l);this.storeRelation(c,y,l,f);}}this.loadNestedRelations(o,c,a),this.logger.debug("[QueryEngine] Loaded nested relations for",c);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[o,u]of Object.entries(r.relations)){let s=n[o];if(!s)continue;let a=u.entity.name,c=this.getInverseRelationName(e,a,o);if(u.type==="one")s&&typeof s=="object"&&s.id&&(this.ensureObjectNode(s.id,a),this.storeRelation(t,s.id,o,c),this.loadNestedRelations(a,s.id,s));else if(u.type==="many"&&Array.isArray(s)){for(let d of s)if(d&&typeof d=="object"&&d.id){this.ensureObjectNode(d.id,a);let l=this.getInverseRelationName(a,e,o);l&&this.storeRelation(d.id,t,l,o),this.loadNestedRelations(a,d.id,d);}}}}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 u=this.buildIncludeFromChildQueries(r);n[o.relationName]=Object.keys(u).length>0?u:true;}return n}sendInsertsForTree(e,t,n){var s,a;let r=(a=(s=t==null?void 0:t.value)==null?void 0:s.id)==null?void 0:a.value;if(!r)return;let o={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let c of Array.from(e.subscriptions))try{c(o);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let c of Array.from(e.childQueries)){let d=this.queryNodes.get(c);if(!d||!d.relationName)continue;let l=d.relationName,p=d.queryStep.query.resource,y=t.value[l];if(!y)continue;let f=y.value;if(Array.isArray(f))for(let m of f)this.sendInsertsForTree(d,m,p);else f&&typeof f=="object"&&this.sendInsertsForTree(d,f,p);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=w(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:c}]of Array.from(o)){let d=n[s];if(d){this.ensureObjectNode(d,c);let l=this.getInverseRelationName(e.resource,c,a);this.storeRelation(e.resourceId,d,a,l);}}let u=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(s=>{for(let a of s){let c=this.queryNodes.get(a);if(c){c.trackedObjects.add(e.resourceId),u&&u.matchedQueries.add(a);for(let d of Array.from(c.subscriptions))try{d(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(".")});}}}});return}if(e.procedure==="UPDATE"){let n=w(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.getMatchingQueries(e,n).then(u=>{let s=new Set(u),a=[],c=[],d=[];for(let p of u)o.has(p)?d.push(p):a.push(p);for(let p of Array.from(o))s.has(p)||c.push(p);for(let p of a){let y=this.queryNodes.get(p);y&&y.trackedObjects.add(e.resourceId);}for(let p of c){let y=this.queryNodes.get(p);y&&y.trackedObjects.delete(e.resourceId);}let l=this.objectNodes.get(e.resourceId);if(l){for(let p of a)l.matchedQueries.add(p);for(let p of c)l.matchedQueries.delete(p);}for(let p of [...c,...d]){let y=this.queryNodes.get(p);if(y)for(let f of Array.from(y.subscriptions))try{f(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(a.length>0)for(let p of a){let y=this.queryNodes.get(p);if(!y)continue;let f=this.buildIncludeFromChildQueries(p);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(y,m[0],e.resource);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?ge([]):Promise.all(n.map(async r=>{let o=r.queryStep.query.where,u=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,u,r.relationName):void 0,h=m?a.referencesObjects.get(m):void 0;if(!h)return {hash:r.hash,matches:false};let g=this.objectNodes.get(h);return !g||!y||!g.matchedQueries.has(y.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!o)return {hash:r.hash,matches:true};let c=_(o,u,this.schema),d=Object.keys(c).length>0;if(!d&&t!==void 0)return {hash:r.hash,matches:A(t,o)};let l=await this.storage.get({resource:u,where:{id:s},include:d?c:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let p=w(l[0]);return p?{hash:r.hash,matches:A(p,o)}:{hash:r.hash,matches:false}})).then(r=>r.filter(o=>o.matches).map(o=>o.hash))}};var Ge=$e(Se());var de=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),ve=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()})),Wt=ve.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ue=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),We=zod.z.object({timestamp:zod.z.string().optional()}).optional(),U=Ue.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:We}),H=Ue.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:Wt,meta:We});zod.z.union([H,U]);var He=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var Je=de.omit({resource:true}),xe=U.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:U.shape.meta}),we=H.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([we,xe]);var Me=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(Me);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=Me(n);return e}return i},Ze=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?Ge.default.parse(r.cookie):{}},u=new URL(t.url),s=u.pathname.split("/"),a=u.searchParams,c=Me(Jt__default.default.parse(a.toString())),d=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:o.headers,cookies:o.cookies,queryParams:c}))??{};if(t.method==="GET"){let l=s[s.length-1],{success:p,data:y,error:f}=Je.safeParse(c);if(!p)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:f},{status:400});let m=await i.handleQuery({req:{...o,...y,type:"QUERY",resource:l,context:d,queryParams:c}});return !m||!m.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(m.data)}if(t.method==="POST")try{let l=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 g=s[s.length-3],T=t.body?await t.json():{};if(!g||g.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let R=await i.handleCustomQuery({req:{...o,type:"CUSTOM_QUERY",resource:g,procedure:l,input:T.input,context:d,queryParams:c}});return Response.json(R)}let y=p,f=t.body?await t.json():{},m;if(l==="insert"||l==="update"){let{success:g,data:T,error:R}=we.safeParse(f);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});m=T;}else {let{success:g,data:T,error:R}=xe.safeParse(f);if(!g)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});m=T;}let h=await i.handleMutation({req:{...o,type:"MUTATE",resource:y,input:m.payload,context:d,resourceId:m.resourceId,procedure:l==="insert"||l==="update"?l.toUpperCase():l,queryParams:{},meta:m.meta}});return Response.json(h)}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 et=$e(Se());var $=zod.z.string(),Ie=zod.z.union([He,de]),Gt=zod.z.object({id:$,type:zod.z.literal("SUBSCRIBE")}).and(Ie),Zt=zod.z.object({id:$,type:zod.z.literal("UNSUBSCRIBE")}).and(Ie),Yt=zod.z.object({id:$,type:zod.z.literal("QUERY")}).and(Ie),Xt=zod.z.object({id:$,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),Ye=H.extend({id:$}),en=U.extend({id:$}),tn=zod.z.union([en,Ye]),Xe=zod.z.union([Gt,Yt,Xt,tn,Zt]),nn=zod.z.object({id:$,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),rn=zod.z.object({id:$,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([nn,rn,Ye]);zod.z.object({resource:zod.z.string(),data:zod.z.array(ve)});var tt=i=>{let e={},t=i.logger;return (n,r)=>{var l;let o=p=>{n.send(JSON.stringify(p));},u=se(),s=new Map,a={headers:r.headers,cookies:typeof r.headers.cookie=="string"?et.default.parse(r.headers.cookie):{}},c=Jt.parse(r.url.split("?")[1]),d=(l=i.contextProvider)==null?void 0:l.call(i,{transport:"WEBSOCKET",headers:a.headers,cookies:a.cookies,queryParams:c});e[u]=n,t.info("Client connected:",u),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,g=f==="SUBSCRIBE";if("procedure"in h){let T=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h.resource,procedure:h.procedure,input:h.input,context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(g){if(!T||!T.data||!T.query)throw new Error("Invalid resource");T.unsubscribe&&s.set(N(h),T.unsubscribe),o({id:m,type:"REPLY",data:{resource:T.query.resource,data:(T.data??[]).map(R=>R.value)}});}else o({id:m,type:"REPLY",data:T});}else {let T=await i.handleQuery({req:{...a,...h,type:"QUERY",context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(!T||!T.data)throw new Error("Invalid resource");g&&T.unsubscribe&&s.set(N(h),T.unsubscribe),o({id:m,type:"REPLY",data:{resource:h.resource,data:(T.data??[]).map(R=>R.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:f,id:m,...h}=y,g=s.get(N(h));g&&(g(),s.delete(N(h)));}else if(y.type==="CUSTOM_QUERY"){let{resource:f,procedure:m,input:h,id:g}=y;t.debug("Received custom query from client:",y);try{let T=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:f,procedure:m,input:h,context:await d??{},queryParams:c}});o({id:g,type:"REPLY",data:T});}catch(T){o({id:g,type:"REJECT",resource:f,message:T.message}),t.error("Error handling custom query from the client:",T);}}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 d??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:c,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&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",u),delete e[u];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 Nr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,tt(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{Ze(e)(nt(n)).then(u=>u.json().then(s=>r.status(u.status).send(s)));});};var ye=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,o,u,s,a){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=o,this._single=u,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 sn=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Le=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>sn(n)?w(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function k(i,e){let t=new Le(i),n=o=>{let u=ye._init(o,t,true);return Object.assign(Object.create(u),{insert:a=>i.insert(o,a),update:(a,c)=>i.update(o,a,c)})},r={get(o,u){if(u==="findOne")return i.findOne.bind(i);if(u==="find")return i.find.bind(i);if(u==="insert")return i.insert.bind(i);if(u==="update")return i.update.bind(i);if(u==="transaction")return async s=>i.transaction(async({trx:a,commit:c,rollback:d})=>{let l=k(a,e);return s({trx:l,commit:c,rollback:d})});if(u in e){let s=e[u];return n(s)}}};return new Proxy({},r)}var Ce=class i{routes;hooksRegistry=new Map;constructor(e){this.routes=e.routes;for(let t of Object.values(e.routes)){if(t.resourceSchema===void 0)continue;let n=t;n.hooks&&this.hooksRegistry.set(n.resourceSchema.name,n.hooks);}}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}},Kr=i=>Ce.create({...i}),it=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),at=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),Ae=class i{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,n,r,o){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=n??{},this.authorization=r,this.hooks=o;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:at,query:it}),n={},r={};for(let[o,u]of Object.entries(t))u._type==="mutation"?n[o]=u:r[o]=u;return new i(this.resourceSchema,n,r,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new i(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},o=N(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:o}})(e);handleMutation=async({req:e,db:t,schema:n})=>{var s;let r=((s=e.meta)==null?void 0:s.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r),u=k(o,n);return await this.wrapInMiddlewares(async a=>{if(!a.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[a.procedure];if(c){let d=c.inputValidator["~standard"].validate(a.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.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}`)}return a.input=l.value,c.handler({req:a,db:u})}else {if(a.procedure==="INSERT"||a.procedure==="UPDATE")return this.handleSet({req:a,db:o,operation:a.procedure,schema:n});throw new Error(`Unknown procedure: ${a.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=k(t,n);return await this.wrapInMiddlewares(async o=>{let u=this.customQueries[o.procedure];if(!u)throw new Error(`Unknown query procedure: ${o.procedure}`);let s=u.inputValidator["~standard"].validate(o.input),a=s instanceof Promise?await s:s;if(a.issues){let c=a.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return o.input=a.value,u.handler({req:o,db:r})})(e)};getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let o=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&o)throw new Error("Resource already exists");if(n==="UPDATE"&&!o)throw new Error("Resource not found");let u={value:e.input};return t.transaction(async({trx:s})=>{var d,l,p,y,f,m,h;if(n==="INSERT"){let{data:g,acceptedValues:T}=await s.rawInsert(e.resource,e.resourceId,u,(d=e.context)==null?void 0:d.messageId,e.context);if(!T)throw new Error("Mutation rejected");let R=w(g);if(R.id=R.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let S=_(b,e.resource,r),v=Object.keys(S).length>0?await s.rawFindById(e.resource,e.resourceId,S):g,M=w(v);if(M.id=M.id??e.resourceId,!A(M,b))throw new Error("Not authorized")}}return {data:g,acceptedValues:T}}if((y=(p=this.authorization)==null?void 0:p.update)!=null&&y.preMutation){let g=w(o);g.id=g.id??e.resourceId;let T=this.authorization.update.preMutation({ctx:e.context,value:g});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let R=_(T,e.resource,r),b=Object.keys(R).length>0?await s.rawFindById(e.resource,e.resourceId,R):o,S=w(b);if(S.id=S.id??e.resourceId,!A(S,T))throw new Error("Not authorized")}}let{data:a,acceptedValues:c}=await s.rawUpdate(e.resource,e.resourceId,u,(f=e.context)==null?void 0:f.messageId,e.context);if(!c)throw new Error("Mutation rejected");if((h=(m=this.authorization)==null?void 0:m.update)!=null&&h.postMutation){let g=w(a);g.id=g.id??e.resourceId;let T=this.authorization.update.postMutation({ctx:e.context,value:g});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let R=_(T,e.resource,r),b=Object.keys(R).length>0?await s.rawFindById(e.resource,e.resourceId,R):a,S=w(b);if(S.id=S.id??e.resourceId,!A(S,T))throw new Error("Not authorized")}}return {data:a,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}},je=class{resourceSchema=void 0;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 s;let r=((s=e.meta)==null?void 0:s.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r),u=k(o,n);return await this.wrapInMiddlewares(async a=>{if(!a.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[a.procedure];if(c){let d=c.inputValidator["~standard"].validate(a.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.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}`)}return a.input=l.value,c.handler({req:a,db:u})}throw new Error(`Unknown procedure: ${a.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=k(t,n);return await this.wrapInMiddlewares(async o=>{let u=this.customQueries[o.procedure];if(!u)throw new Error(`Unknown query procedure: ${o.procedure}`);let s=u.inputValidator["~standard"].validate(o.input),a=s instanceof Promise?await s:s;if(a.issues){let c=a.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return o.input=a.value,u.handler({req:o,db:r})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}},Ee=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Ae(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:at,query:it}),n={},r={};for(let[o,u]of Object.entries(t))u._type==="mutation"?n[o]=u:r[o]=u;return new je(n,r).use(...this.middlewares)}use(...e){return new i([...this.middlewares,...e])}static create(){return new i}},Ur=Ee.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(([o,u])=>[o,{value:u,_meta:{timestamp:n}}]))});return w(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:o,...u}=n,s=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(u).map(([d,l])=>[d,{value:l,_meta:{timestamp:r}}]))}),a=w(s.data),c={};for(let d of Object.keys(u))d in a&&(c[d]=a[d]);return c}};var pn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function q(i){var r,o,u;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((u=(o=t.constructor)==null?void 0:o.name)==null?void 0:u.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function st(i){let e=q(i);return pn[e]}var mn="42701";function G(i){var t;if(i.code===mn)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 Pe(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 fn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let o of Object.values(e))for(let u of Object.values(o.fields)){let s=u.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:u,values:s}=o;try{let a=s.map(c=>`'${c}'`).join(", ");await kysely.sql`
2
2
  DO $$ BEGIN
3
3
  CREATE TYPE ${kysely.sql.id(u)} 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",u,a);}}}function Z(i,e){return i.some(t=>t.name===e)}function mn(i,e){return (i==null?void 0:i.columns.some(t=>t.name===e))??false}function Pe(i,e){let[t]=e.split(".");return Z(i,t)}function Ee(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&&Pe(t,e.references)&&(r=r.references(e.references)),r}function hn(i,e,t,n,r){let o=[];for(let[u,s]of Object.entries(i.fields)){let a=e==null?void 0:e.columns.find(d=>d.name===u),c=s.getStorageFieldType();a?(a.dataType,c.type):(o.push({name:u,storageFieldType:c}),c.references&&!Pe(t,c.references)&&n.push({tableName:r,columnName:u,references:c.references}));}return o}function st(i,e){return e==="postgres"&&!!i.enumValues&&i.enumValues.length>0&&!!i.enumName}async function Tn(i,e,t,n,r,o){if(t.length===0)return;let u=i.schema.createTable(e);for(let{name:s,storageFieldType:a}of t)if(st(a,r))u=u.addColumn(s,kysely.sql.raw(a.enumName),c=>Ee(c,a,n));else {let c=Oe(a,r);u=u.addColumn(s,c,d=>Ee(d,a,n));}await u.execute().catch(s=>{if(!G(s))throw o==null||o.error("Error creating table",e,s),s});}async function gn(i,e,t,n,r,o,u){for(let{name:s,storageFieldType:a}of t){let c=a.references?Pe(n,a.references):false,d=st(a,o)?kysely.sql.raw(a.enumName):Oe(a,o);await i.schema.alterTable(e).addColumn(s,d,l=>Ee(l,a,n,!c)).execute().catch(l=>{if(!G(l))throw u==null||u.error("Error adding column",s,l),l}),a.references&&!c&&!r.some(l=>l.tableName===e&&l.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 Rn(i,e,t,n,r,o){let u=`${e}_meta`,s=[];for(let[a,c]of Object.entries(t.fields)){let d=c.getStorageFieldType();mn(n,a)||s.push({name:a,storageFieldType:d});}if(!n&&s.length>0){let a=i.schema.createTable(u);for(let{name:c,storageFieldType:d}of s)a=a.addColumn(c,"varchar",l=>{let p=l;return d.primary&&(p=p.primaryKey(),Z(r,e)&&(p=p.references(`${e}.${c}`))),p});await a.execute().catch(c=>{if(!G(c))throw o==null||o.error("Error creating meta table",u,c),c});}else if(n)for(let{name:a,storageFieldType:c}of s)await i.schema.alterTable(u).addColumn(a,"varchar",d=>{let l=d;return c.primary&&(l=l.primaryKey(),Z(r,e)&&(l=l.references(`${e}.${a}`))),l}).execute().catch(d=>{if(!G(d))throw o==null||o.error("Error adding meta column",a,d),d});}async function ot(i,e,t,n,r){let[o,u]=n.split("."),s=`${e}_${t}_fk`;try{await kysely.sql`
7
+ `.execute(i);}catch(a){n==null||n.warn("Could not create enum type",u,a);}}}function Z(i,e){return i.some(t=>t.name===e)}function hn(i,e){return (i==null?void 0:i.columns.some(t=>t.name===e))??false}function Ve(i,e){let[t]=e.split(".");return Z(i,t)}function Oe(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 Tn(i,e,t,n,r){let o=[];for(let[u,s]of Object.entries(i.fields)){let a=e==null?void 0:e.columns.find(d=>d.name===u),c=s.getStorageFieldType();a?(a.dataType,c.type):(o.push({name:u,storageFieldType:c}),c.references&&!Ve(t,c.references)&&n.push({tableName:r,columnName:u,references:c.references}));}return o}function ot(i,e){return e==="postgres"&&!!i.enumValues&&i.enumValues.length>0&&!!i.enumName}async function gn(i,e,t,n,r,o){if(t.length===0)return;let u=i.schema.createTable(e);for(let{name:s,storageFieldType:a}of t)if(ot(a,r))u=u.addColumn(s,kysely.sql.raw(a.enumName),c=>Oe(c,a,n));else {let c=Pe(a,r);u=u.addColumn(s,c,d=>Oe(d,a,n));}await u.execute().catch(s=>{if(!G(s))throw o==null||o.error("Error creating table",e,s),s});}async function Rn(i,e,t,n,r,o,u){for(let{name:s,storageFieldType:a}of t){let c=a.references?Ve(n,a.references):false,d=ot(a,o)?kysely.sql.raw(a.enumName):Pe(a,o);await i.schema.alterTable(e).addColumn(s,d,l=>Oe(l,a,n,!c)).execute().catch(l=>{if(!G(l))throw u==null||u.error("Error adding column",s,l),l}),a.references&&!c&&!r.some(l=>l.tableName===e&&l.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 bn(i,e,t,n,r,o){let u=`${e}_meta`,s=[];for(let[a,c]of Object.entries(t.fields)){let d=c.getStorageFieldType();hn(n,a)||s.push({name:a,storageFieldType:d});}if(!n&&s.length>0){let a=i.schema.createTable(u);for(let{name:c,storageFieldType:d}of s)a=a.addColumn(c,"varchar",l=>{let p=l;return d.primary&&(p=p.primaryKey(),Z(r,e)&&(p=p.references(`${e}.${c}`))),p});await a.execute().catch(c=>{if(!G(c))throw o==null||o.error("Error creating meta table",u,c),c});}else if(n)for(let{name:a,storageFieldType:c}of s)await i.schema.alterTable(u).addColumn(a,"varchar",d=>{let l=d;return c.primary&&(l=l.primaryKey(),Z(r,e)&&(l=l.references(`${e}.${a}`))),l}).execute().catch(d=>{if(!G(d))throw o==null||o.error("Error adding meta column",a,d),d});}async function ut(i,e,t,n,r){let[o,u]=n.split("."),s=`${e}_${t}_fk`;try{await kysely.sql`
8
8
  ALTER TABLE ${kysely.sql.id(e)}
9
9
  ADD CONSTRAINT ${kysely.sql.id(s)}
10
10
  FOREIGN KEY (${kysely.sql.id(t)})
11
11
  REFERENCES ${kysely.sql.id(o)} (${kysely.sql.id(u)})
12
- `.execute(i);}catch(a){G(a)||r==null||r.warn("Could not add foreign key constraint",e,t,n,a);}}async function bn(i,e,t,n){for(let{tableName:r,columnName:o,references:u}of e){let s=t.find(d=>d.name===r),a=s==null?void 0:s.columns.find(d=>d.name===o),[c]=u.split(".");s&&a&&Z(t,c)&&await ot(i,r,o,u,n);}}async function Sn(i,e,t,n){for(let[r,o]of Object.entries(e)){let u=`${r}_meta`,s=t.find(a=>a.name===u);if(s)for(let[a,c]of Object.entries(o.fields)){let d=c.getStorageFieldType(),l=s.columns.find(p=>p.name===a);d.primary&&l&&Z(t,r)&&await ot(i,u,a,`${r}.${a}`,n);}}}async function ut(i,e,t){let n=q(i),r=await i.introspection.getTables(),o=[];await fn(i,e,n,t);for(let[s,a]of Object.entries(e)){let c=r.find(p=>p.name===s),d=r.find(p=>p.name===`${s}_meta`),l=hn(a,c,r,o,s);if(c)for(let[p,y]of Object.entries(a.fields)){let m=c.columns.find(g=>g.name===p),f=y.getStorageFieldType(),h=Oe(f,n);m&&m.dataType!==h&&(t==null||t.warn("Column type mismatch:",p,"expected to have type:",h,"but has type:",m.dataType));}!c&&l.length>0?await Tn(i,s,l,r,n,t):c&&await gn(i,s,l,r,o,n,t),await Rn(i,s,a,d,r,t);}let u=await i.introspection.getTables();await bn(i,o,u,t),await Sn(i,e,u,t);}function ye(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,u=n.$and;return (o?t.or:t.and)(o?n.$or.map(s=>ye(i,e,t,s)):u?n.$and.map(s=>ye(i,e,t,s)):Object.entries(n).map(([s,a])=>{var c,d;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?((c=a==null?void 0:a.$not)==null?void 0:c.$in)!==void 0?t(`${e}.${s}`,"not in",a.$not.$in):((d=a==null?void 0:a.$not)==null?void 0:d.$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 l=r.relations[s],p=l.entity.name;return l.type==="many"?t.exists(fe(i,p,t.selectFrom(p).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),a)):ye(i,p,t,a)}return null}).filter(Boolean))}function pe(i,e,t,n){let r=i[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let o of n.$and)t=pe(i,e,t,o);return t}else if(n.$or){for(let o of n.$or)t=pe(i,e,t,o);return t}for(let[o,u]of Object.entries(n)){if(!r.relations[o])continue;let s=r.relations[o],a=s.entity.name,c=s.type==="one"?"id":s.foreignColumn,d=s.type==="one"?s.relationalColumn:"id";t=t.leftJoin(a,`${a}.${c}`,`${e}.${d}`),u instanceof Object&&!Array.isArray(u)&&u!==null&&(t=pe(i,a,t,u));}return t}function fe(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=pe(i,e,t,n),t.where(r=>ye(i,e,r,n)))}function vn(i,e,t,n,r){let o=q(r),u=e[t];if(o==="sqlite"&&(u!=null&&u.fields)){let s=Object.keys(u.fields),a=i.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);return a}return i.selectFrom(n).selectAll(n)}function xn(i,e,t,n,r){let o=q(r),u=e[t];if(o==="sqlite"&&(u!=null&&u.fields)){let s=Object.keys(u.fields),a=i.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);return a}return i.selectFrom(n).selectAll(n)}function wn(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}function me(i,e,t,n,r,o){if(!n)return t;if(!i)throw new Error("Schema not initialized");let u=i[e];if(!u)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:s,jsonArrayFrom:a}=r;for(let c of Object.keys(n)){if(!u.relations[c])throw new Error(`Relation ${c} not found in resource ${e}`);let d=u.relations[c],l=d.entity.name,p=n[c],y=d.type==="one"?"id":d.foreignColumn,m=d.type==="one"?d.relationalColumn:"id",f=d.type==="one"?s:a,h=wn(p)?p:null,g=h==null?void 0:h.include;t=t.select(T=>{let R=`${l}_meta`,b=xn(T,i,l,l,o).whereRef(`${l}.${y}`,"=",`${e}.${m}`).select(S=>s(vn(S,i,l,R,o).whereRef(`${R}.id`,"=",`${l}.id`)).as("_meta"));if(h!=null&&h.where&&(b=fe(i,l,b,h.where)),h!=null&&h.orderBy)for(let S of h.orderBy)b=b.orderBy(`${l}.${S.key}`,S.direction);return (h==null?void 0:h.limit)!==void 0&&(b=b.limit(h.limit)),g&&Object.keys(g).length>0&&(b=me(i,l,b,g,r,o)),f(b).as(c)});}return t}var Ve=class i extends J{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=at(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 ut(this.db,e,t);}selectMetaColumns(e,t,n){var u;let r=q(this.db),o=(u=this.schema)==null?void 0:u[t];if(r==="sqlite"&&(o!=null&&o.fields)){let s=Object.keys(o.fields),a=e.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);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=me(this.schema,e,o,n,this.dialectHelpers,this.db);let u=await o.executeTakeFirst();if(!u)return;let s=this.parseRelationalJsonStrings(u,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 x(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:o,sort:u}=e,s=`${t}_meta`,a=this.db.selectFrom(t).selectAll(t).select(d=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(d,t,s).whereRef(`${s}.id`,"=",`${t}.id`)).as("_meta"));a=fe(this.schema,t,a,n),a=me(this.schema,t,a,r,this.dialectHelpers,this.db),o!==void 0&&(a=a.limit(o)),u!==void 0&&u.forEach(d=>{a=a.orderBy(d.key,d.direction);});let c=await a.execute();return c.length===0?[]:c.map(d=>{let l=this.parseRelationalJsonStrings(d,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=>x(r))}async rawInsert(e,t,n,r,o){var f,h,g,T,R,b,S;let u=(h=(f=this.server)==null?void 0:f.router)==null?void 0:h.getHooks(e),s=(g=this.schema)==null?void 0:g[e],[a,c]=((T=s==null?void 0:s.mergeMutation)==null?void 0:T.call(s,"set",n.value,void 0))??[n,n.value];if(!c)return {data:n,acceptedValues:null};let d=a,l={...d,value:{...d.value,id:{value:t}}};if(u!=null&&u.beforeInsert){let I=x(l);I.id=t;let w=await u.beforeInsert({ctx:o,value:I,rawValue:l,db:this});w&&(d=w);}let p={},y={};for(let[I,w]of Object.entries(d.value)){let C=(R=w._meta)==null?void 0:R.timestamp;if(!C)continue;let L=(S=(b=s==null?void 0:s.fields[I])==null?void 0:b.getStorageFieldType)==null?void 0:S.call(b);(L==null?void 0:L.type)==="jsonb"||(L==null?void 0:L.type)==="json"?p[I]=JSON.stringify(w.value):p[I]=w.value,y[I]=C;}await this.db.insertInto(e).values({...p,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute();let m=this.buildMutation(e,t,"INSERT",d,r);if(m&&this.trackMutation(m,d),u!=null&&u.afterInsert){let I={...d,value:{...d.value,id:{value:t}}},w=x(I);w.id=t,await u.afterInsert({ctx:o,value:w,rawValue:I,db:this});}return {data:d,acceptedValues:c}}async rawUpdate(e,t,n,r,o){var h,g,T,R,b,S,I;let u=(g=(h=this.server)==null?void 0:h.router)==null?void 0:g.getHooks(e),s=(T=this.schema)==null?void 0:T[e],a=await this.rawFindById(e,t),[c,d]=((R=s==null?void 0:s.mergeMutation)==null?void 0:R.call(s,"set",n.value,a))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let l=c,p={...l,value:{...l.value,id:{value:t}}};if(u!=null&&u.beforeUpdate){let w=x(p);w.id=t;let C;if(a){let j={...a,value:{...a.value,id:{value:t}}};C=x(j),C.id=t;}let L=await u.beforeUpdate({ctx:o,value:w,rawValue:p,previousValue:C,previousRawValue:a,db:this});L&&(l=L);}let y={},m={};for(let[w,C]of Object.entries(l.value)){let L=(b=C._meta)==null?void 0:b.timestamp;if(!L)continue;let j=(I=(S=s==null?void 0:s.fields[w])==null?void 0:S.getStorageFieldType)==null?void 0:I.call(S);(j==null?void 0:j.type)==="jsonb"||(j==null?void 0:j.type)==="json"?y[w]=JSON.stringify(C.value):y[w]=C.value,m[w]=L;}if(Object.keys(y).length===0)return {data:l,acceptedValues:d};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...m,id:t}).onConflict(w=>w.column("id").doUpdateSet(m)).execute()]);let f=this.buildMutation(e,t,"UPDATE",l,r);if(f){let w=await this.rawFindById(e,t);w&&this.trackMutation(f,w);}if(u!=null&&u.afterUpdate){let w=await this.rawFindById(e,t);if(w){let C={...w,value:{...w.value,id:{value:t}}},L=x(C);L.id=t;let j;if(a){let lt={...a,value:{...a.value,id:{value:t}}};j=x(lt),j.id=t;}await u.afterUpdate({ctx:o,value:L,rawValue:C,previousValue:j,previousRawValue:a,db:this});}}return {data:l,acceptedValues:d}}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),u=this.mutationStack,s=[];this.mutationStack=s;let a=await this.db.savepoint(o).execute(),c=false,d=false;try{return await e({trx:this,commit:async()=>{await a.releaseSavepoint(o).execute(),c=!0,u.push(...s);},rollback:async()=>{await a.rollbackToSavepoint(o).execute(),d=!0,s.length=0;}}).then(l=>a.isCommitted||a.isRolledBack||c||d?l:a.releaseSavepoint(o).execute().then(()=>(u.push(...s),l)))}catch(l){throw d||await a.rollbackToSavepoint(o).execute().catch(()=>{}),s.length=0,l}finally{this.mutationStack=u;}}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()=>{await r.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(u=>r.isCommitted||r.isRolledBack?u:r.commit().execute().then(()=>(this.notifyMutations(t),u)))}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,u;if(q(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 c=JSON.parse(a);if(this.schema){let d=this.schema[t],l=(o=d==null?void 0:d.relations)==null?void 0:o[s];if(l){let p=l.entity.name;r[s]=this.parseRelationalJsonStrings(c,p);}else r[s]=c;}else r[s]=c;}catch{r[s]=a;}else r[s]=a;else if(typeof a=="object"&&a!==null&&!Array.isArray(a))if(this.schema){let c=this.schema[t],d=(u=c==null?void 0:c.relations)==null?void 0:u[s];if(d){let l=d.entity.name;r[s]=this.parseRelationalJsonStrings(a,l);}else r[s]=a;}else r[s]=a;else Array.isArray(a)?r[s]=a.map(c=>{var d,l;if(typeof c=="string")try{let p=JSON.parse(c);if(this.schema){let y=this.schema[t],m=(d=y==null?void 0:y.relations)==null?void 0:d[s];if(m){let f=m.entity.name;return this.parseRelationalJsonStrings(p,f)}}return p}catch{return c}if(typeof c=="object"&&c!==null&&this.schema){let p=this.schema[t],y=(l=p==null?void 0:p.relations)==null?void 0:l[s];if(y){let m=y.entity.name;return this.parseRelationalJsonStrings(c,m)}}return c}):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,[u,s])=>{var l,p,y,m,f,h,g,T,R;if(u==="_meta")return o;let a=(p=(l=n==null?void 0:n.fields[u])==null?void 0:l.getStorageFieldType)==null?void 0:p.call(l),c=(a==null?void 0:a.type)==="jsonb"||(a==null?void 0:a.type)==="json",d=(n==null?void 0:n.relations)&&u in n.relations;if(u==="id")o[u]={value:s};else if(c)o[u]={value:s,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[u]}};else if(d){let b=n.relations[u].entity,S=(b==null?void 0:b.name)??t;Array.isArray(s)?o[u]={value:s.map(I=>this.convertToMaterializedLiveType(I,S)),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[u],relation:true}}:s!==null&&typeof s=="object"?o[u]={...this.convertToMaterializedLiveType(s,S),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[u],relation:true}}:o[u]={value:s,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[u],relation:true}};}else Array.isArray(s)?o[u]={value:s,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[u]}}:typeof s=="object"&&s!==null&&!(s instanceof Date)?o[u]={value:s,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[u]}}:o[u]={value:s,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[u]}};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",u=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||o&&u}buildMutation(e,t,n,r,o){var s;let u={};for(let[a,c]of Object.entries(r.value)){if(a==="id")continue;let d=(s=c._meta)==null?void 0:s.timestamp;d&&(u[a]={value:c.value,_meta:{timestamp:d}});}return Object.keys(u).length===0?null:{id:o??se(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:u}}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 Ne=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=ke({level:e.logLevel??Q.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new ue({router:{get:async(n,r)=>{var l;let{headers:o,cookies:u,queryParams:s,context:a}=(r==null?void 0:r.context)??{};if(!(r!=null&&r.batcher))throw new Error("Batcher is required");let c={...n,type:"QUERY",headers:o,cookies:u,queryParams:s,context:a},d=await((l=this.router.routes[n.resource])==null?void 0:l.handleQuery({req:c,batcher:r.batcher}));return (d==null?void 0:d.data)??[]},incrementQueryStep:(n,r={})=>{var s;let o=(s=this.router.routes[n.query.resource])==null?void 0:s.getAuthorizationClause({...n.query,type:"QUERY",headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context});if(typeof o=="boolean"&&!o)throw new Error("Not authorized");let u=K(n.query.where,typeof o=="object"?o:void 0);return {...n,query:{...n.query,where:u}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:o,context:u,...s}=t,a={headers:n,cookies:r,queryParams:o,context:u},c=e.subscription?this.queryEngine.subscribe(s,l=>{var p;(p=e.subscription)==null||p.call(e,l);},a):void 0;return {data:await this.queryEngine.get(s,{context:a}),unsubscribe:c}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){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:u,context:s}=e.req,a={headers:r,cookies:o,queryParams:u,context:s},c=t.buildQueryRequest(),d=e.subscription?this.queryEngine.subscribe(c,p=>{var y;(y=e.subscription)==null||y.call(e,p);},a):void 0,l=await this.queryEngine.get(c,{context:a});return e.subscription?{data:l,unsubscribe:d,query:c}:l.map(p=>x(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)}},Si=Ne.create;exports.ProcedureRoute=Ae;exports.Route=Ce;exports.RouteFactory=je;exports.Router=Le;exports.SQLStorage=Ve;exports.Server=Ne;exports.Storage=J;exports.createServerDB=k;exports.expressAdapter=Nr;exports.routeFactory=Ur;exports.router=Kr;exports.server=Si;
12
+ `.execute(i);}catch(a){G(a)||r==null||r.warn("Could not add foreign key constraint",e,t,n,a);}}async function Sn(i,e,t,n){for(let{tableName:r,columnName:o,references:u}of e){let s=t.find(d=>d.name===r),a=s==null?void 0:s.columns.find(d=>d.name===o),[c]=u.split(".");s&&a&&Z(t,c)&&await ut(i,r,o,u,n);}}async function vn(i,e,t,n){for(let[r,o]of Object.entries(e)){let u=`${r}_meta`,s=t.find(a=>a.name===u);if(s)for(let[a,c]of Object.entries(o.fields)){let d=c.getStorageFieldType(),l=s.columns.find(p=>p.name===a);d.primary&&l&&Z(t,r)&&await ut(i,u,a,`${r}.${a}`,n);}}}async function ct(i,e,t){let n=q(i),r=await i.introspection.getTables(),o=[];await fn(i,e,n,t);for(let[s,a]of Object.entries(e)){let c=r.find(p=>p.name===s),d=r.find(p=>p.name===`${s}_meta`),l=Tn(a,c,r,o,s);if(c)for(let[p,y]of Object.entries(a.fields)){let f=c.columns.find(g=>g.name===p),m=y.getStorageFieldType(),h=Pe(m,n);f&&f.dataType!==h&&(t==null||t.warn("Column type mismatch:",p,"expected to have type:",h,"but has type:",f.dataType));}!c&&l.length>0?await gn(i,s,l,r,n,t):c&&await Rn(i,s,l,r,o,n,t),await bn(i,s,a,d,r,t);}let u=await i.introspection.getTables();await Sn(i,o,u,t),await vn(i,e,u,t);}function pe(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,u=n.$and;return (o?t.or:t.and)(o?n.$or.map(s=>pe(i,e,t,s)):u?n.$and.map(s=>pe(i,e,t,s)):Object.entries(n).map(([s,a])=>{var c,d;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?((c=a==null?void 0:a.$not)==null?void 0:c.$in)!==void 0?t(`${e}.${s}`,"not in",a.$not.$in):((d=a==null?void 0:a.$not)==null?void 0:d.$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 l=r.relations[s],p=l.entity.name;return l.type==="many"?t.exists(fe(i,p,t.selectFrom(p).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),a)):pe(i,p,t,a)}return null}).filter(Boolean))}function me(i,e,t,n){let r=i[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let o of n.$and)t=me(i,e,t,o);return t}else if(n.$or){for(let o of n.$or)t=me(i,e,t,o);return t}for(let[o,u]of Object.entries(n)){if(!r.relations[o])continue;let s=r.relations[o],a=s.entity.name,c=s.type==="one"?"id":s.foreignColumn,d=s.type==="one"?s.relationalColumn:"id";t=t.leftJoin(a,`${a}.${c}`,`${e}.${d}`),u instanceof Object&&!Array.isArray(u)&&u!==null&&(t=me(i,a,t,u));}return t}function fe(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=me(i,e,t,n),t.where(r=>pe(i,e,r,n)))}function xn(i,e,t,n,r){let o=q(r),u=e[t];if(o==="sqlite"&&(u!=null&&u.fields)){let s=Object.keys(u.fields),a=i.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);return a}return i.selectFrom(n).selectAll(n)}function wn(i,e,t,n,r){let o=q(r),u=e[t];if(o==="sqlite"&&(u!=null&&u.fields)){let s=Object.keys(u.fields),a=i.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);return a}return i.selectFrom(n).selectAll(n)}function he(i,e,t,n,r,o){if(!n)return t;if(!i)throw new Error("Schema not initialized");let u=i[e];if(!u)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:s,jsonArrayFrom:a}=r;for(let c of Object.keys(n)){if(!u.relations[c])throw new Error(`Relation ${c} not found in resource ${e}`);let d=u.relations[c],l=d.entity.name,p=n[c],y=d.type==="one"?"id":d.foreignColumn,f=d.type==="one"?d.relationalColumn:"id",m=d.type==="one"?s:a,h=ue(p)?p:null,g=h==null?void 0:h.include;t=t.select(T=>{let R=`${l}_meta`,b=wn(T,i,l,l,o).whereRef(`${l}.${y}`,"=",`${e}.${f}`).select(S=>s(xn(S,i,l,R,o).whereRef(`${R}.id`,"=",`${l}.id`)).as("_meta"));if(h!=null&&h.where&&(b=fe(i,l,b,h.where)),h!=null&&h.orderBy)for(let S of h.orderBy)b=b.orderBy(`${l}.${S.key}`,S.direction);return (h==null?void 0:h.limit)!==void 0&&(b=b.limit(h.limit)),g&&Object.keys(g).length>0&&(b=he(i,l,b,g,r,o)),m(b).as(c)});}return t}var Ne=class i extends J{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=st(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 ct(this.db,e,t);}selectMetaColumns(e,t,n){var u;let r=q(this.db),o=(u=this.schema)==null?void 0:u[t];if(r==="sqlite"&&(o!=null&&o.fields)){let s=Object.keys(o.fields),a=e.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);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=he(this.schema,e,o,n,this.dialectHelpers,this.db);let u=await o.executeTakeFirst();if(!u)return;let s=this.parseRelationalJsonStrings(u,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 w(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:o,sort:u}=e,s=`${t}_meta`,a=this.db.selectFrom(t).selectAll(t).select(d=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(d,t,s).whereRef(`${s}.id`,"=",`${t}.id`)).as("_meta"));a=fe(this.schema,t,a,n),a=he(this.schema,t,a,r,this.dialectHelpers,this.db),o!==void 0&&(a=a.limit(o)),u!==void 0&&u.forEach(d=>{a=a.orderBy(d.key,d.direction);});let c=await a.execute();return c.length===0?[]:c.map(d=>{let l=this.parseRelationalJsonStrings(d,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=>w(r))}async rawInsert(e,t,n,r,o){var m,h,g,T,R,b,S;let u=(h=(m=this.server)==null?void 0:m.router)==null?void 0:h.getHooks(e),s=(g=this.schema)==null?void 0:g[e],[a,c]=((T=s==null?void 0:s.mergeMutation)==null?void 0:T.call(s,"set",n.value,void 0))??[n,n.value];if(!c)return {data:n,acceptedValues:null};let d=a,l={...d,value:{...d.value,id:{value:t}}};if(u!=null&&u.beforeInsert){let v=w(l);v.id=t;let M=await u.beforeInsert({ctx:o,value:v,rawValue:l,db:this});M&&(d=M);}let p={},y={};for(let[v,M]of Object.entries(d.value)){let C=(R=M._meta)==null?void 0:R.timestamp;if(!C)continue;let L=(S=(b=s==null?void 0:s.fields[v])==null?void 0:b.getStorageFieldType)==null?void 0:S.call(b);(L==null?void 0:L.type)==="jsonb"||(L==null?void 0:L.type)==="json"?p[v]=JSON.stringify(M.value):p[v]=M.value,y[v]=C;}await this.db.insertInto(e).values({...p,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute();let f=this.buildMutation(e,t,"INSERT",d,r);if(f&&this.trackMutation(f,d),u!=null&&u.afterInsert){let v={...d,value:{...d.value,id:{value:t}}},M=w(v);M.id=t,await u.afterInsert({ctx:o,value:M,rawValue:v,db:this});}return {data:d,acceptedValues:c}}async rawUpdate(e,t,n,r,o){var h,g,T,R,b,S,v;let u=(g=(h=this.server)==null?void 0:h.router)==null?void 0:g.getHooks(e),s=(T=this.schema)==null?void 0:T[e],a=await this.rawFindById(e,t),[c,d]=((R=s==null?void 0:s.mergeMutation)==null?void 0:R.call(s,"set",n.value,a))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let l=c,p={...l,value:{...l.value,id:{value:t}}};if(u!=null&&u.beforeUpdate){let M=w(p);M.id=t;let C;if(a){let j={...a,value:{...a.value,id:{value:t}}};C=w(j),C.id=t;}let L=await u.beforeUpdate({ctx:o,value:M,rawValue:p,previousValue:C,previousRawValue:a,db:this});L&&(l=L);}let y={},f={};for(let[M,C]of Object.entries(l.value)){let L=(b=C._meta)==null?void 0:b.timestamp;if(!L)continue;let j=(v=(S=s==null?void 0:s.fields[M])==null?void 0:S.getStorageFieldType)==null?void 0:v.call(S);(j==null?void 0:j.type)==="jsonb"||(j==null?void 0:j.type)==="json"?y[M]=JSON.stringify(C.value):y[M]=C.value,f[M]=L;}if(Object.keys(y).length===0)return {data:l,acceptedValues:d};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(M=>M.column("id").doUpdateSet(f)).execute()]);let m=this.buildMutation(e,t,"UPDATE",l,r);if(m){let M=await this.rawFindById(e,t);M&&this.trackMutation(m,M);}if(u!=null&&u.afterUpdate){let M=await this.rawFindById(e,t);if(M){let C={...M,value:{...M.value,id:{value:t}}},L=w(C);L.id=t;let j;if(a){let dt={...a,value:{...a.value,id:{value:t}}};j=w(dt),j.id=t;}await u.afterUpdate({ctx:o,value:L,rawValue:C,previousValue:j,previousRawValue:a,db:this});}}return {data:l,acceptedValues:d}}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),u=this.mutationStack,s=[];this.mutationStack=s;let a=await this.db.savepoint(o).execute(),c=false,d=false;try{return await e({trx:this,commit:async()=>{await a.releaseSavepoint(o).execute(),c=!0,u.push(...s);},rollback:async()=>{await a.rollbackToSavepoint(o).execute(),d=!0,s.length=0;}}).then(l=>a.isCommitted||a.isRolledBack||c||d?l:a.releaseSavepoint(o).execute().then(()=>(u.push(...s),l)))}catch(l){throw d||await a.rollbackToSavepoint(o).execute().catch(()=>{}),s.length=0,l}finally{this.mutationStack=u;}}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()=>{await r.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(u=>r.isCommitted||r.isRolledBack?u:r.commit().execute().then(()=>(this.notifyMutations(t),u)))}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,u;if(q(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 c=JSON.parse(a);if(this.schema){let d=this.schema[t],l=(o=d==null?void 0:d.relations)==null?void 0:o[s];if(l){let p=l.entity.name;r[s]=this.parseRelationalJsonStrings(c,p);}else r[s]=c;}else r[s]=c;}catch{r[s]=a;}else r[s]=a;else if(typeof a=="object"&&a!==null&&!Array.isArray(a))if(this.schema){let c=this.schema[t],d=(u=c==null?void 0:c.relations)==null?void 0:u[s];if(d){let l=d.entity.name;r[s]=this.parseRelationalJsonStrings(a,l);}else r[s]=a;}else r[s]=a;else Array.isArray(a)?r[s]=a.map(c=>{var d,l;if(typeof c=="string")try{let p=JSON.parse(c);if(this.schema){let y=this.schema[t],f=(d=y==null?void 0:y.relations)==null?void 0:d[s];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(p,m)}}return p}catch{return c}if(typeof c=="object"&&c!==null&&this.schema){let p=this.schema[t],y=(l=p==null?void 0:p.relations)==null?void 0:l[s];if(y){let f=y.entity.name;return this.parseRelationalJsonStrings(c,f)}}return c}):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,[u,s])=>{var l,p,y,f,m,h,g,T,R;if(u==="_meta")return o;let a=(p=(l=n==null?void 0:n.fields[u])==null?void 0:l.getStorageFieldType)==null?void 0:p.call(l),c=(a==null?void 0:a.type)==="jsonb"||(a==null?void 0:a.type)==="json",d=(n==null?void 0:n.relations)&&u in n.relations;if(u==="id")o[u]={value:s};else if(c)o[u]={value:s,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[u]}};else if(d){let b=n.relations[u].entity,S=(b==null?void 0:b.name)??t;Array.isArray(s)?o[u]={value:s.map(v=>this.convertToMaterializedLiveType(v,S)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[u],relation:true}}:s!==null&&typeof s=="object"?o[u]={...this.convertToMaterializedLiveType(s,S),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[u],relation:true}}:o[u]={value:s,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[u],relation:true}};}else Array.isArray(s)?o[u]={value:s,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[u]}}:typeof s=="object"&&s!==null&&!(s instanceof Date)?o[u]={value:s,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[u]}}:o[u]={value:s,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[u]}};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",u=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||o&&u}buildMutation(e,t,n,r,o){var s;let u={};for(let[a,c]of Object.entries(r.value)){if(a==="id")continue;let d=(s=c._meta)==null?void 0:s.timestamp;d&&(u[a]={value:c.value,_meta:{timestamp:d}});}return Object.keys(u).length===0?null:{id:o??se(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:u}}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 qe=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=Be({level:e.logLevel??Q.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new ce({router:{get:async(n,r)=>{var l;let{headers:o,cookies:u,queryParams:s,context:a}=(r==null?void 0:r.context)??{};if(!(r!=null&&r.batcher))throw new Error("Batcher is required");let c={...n,type:"QUERY",headers:o,cookies:u,queryParams:s,context:a},d=await((l=this.router.routes[n.resource])==null?void 0:l.handleQuery({req:c,batcher:r.batcher}));return (d==null?void 0:d.data)??[]},incrementQueryStep:(n,r={})=>{var s;let o=(s=this.router.routes[n.query.resource])==null?void 0:s.getAuthorizationClause({...n.query,type:"QUERY",headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context});if(typeof o=="boolean"&&!o)throw new Error("Not authorized");let u=K(n.query.where,typeof o=="object"?o:void 0);return {...n,query:{...n.query,where:u}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:o,context:u,...s}=t,a={headers:n,cookies:r,queryParams:o,context:u},c=e.subscription?this.queryEngine.subscribe(s,l=>{var p;(p=e.subscription)==null||p.call(e,l);},a):void 0;return {data:await this.queryEngine.get(s,{context:a}),unsubscribe:c}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){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:u,context:s}=e.req,a={headers:r,cookies:o,queryParams:u,context:s},c=t.buildQueryRequest(),d=e.subscription?this.queryEngine.subscribe(c,p=>{var y;(y=e.subscription)==null||y.call(e,p);},a):void 0,l=await this.queryEngine.get(c,{context:a});return e.subscription?{data:l,unsubscribe:d,query:c}:l.map(p=>w(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)}},vi=qe.create;exports.ProcedureRoute=je;exports.Route=Ae;exports.RouteFactory=Ee;exports.Router=Ce;exports.SQLStorage=Ne;exports.Server=qe;exports.Storage=J;exports.createServerDB=k;exports.expressAdapter=Nr;exports.routeFactory=Ur;exports.router=Kr;exports.server=vi;
package/dist/server.js CHANGED
@@ -1,12 +1,12 @@
1
- import {a,b,B as B$1,z as z$2,C as C$1,D as D$1,F as F$1,E}from'./chunk-NKM6VWL7.js';import W from'crypto';import gt,{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 ae=a(Z=>{Object.defineProperty(Z,"__esModule",{value:true});Z.parse=lt;Z.serialize=yt;var st=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,at=/^[\u0021-\u003A\u003C-\u007E]*$/,ot=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,ct=/^[\u0020-\u003A\u003D-\u007E]*$/,ut=Object.prototype.toString,dt=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function lt(c,e){let t=new dt,r=c.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||ht,s=0;do{let o=c.indexOf("=",s);if(o===-1)break;let a=c.indexOf(";",s),i=a===-1?r:a;if(o>i){s=c.lastIndexOf(";",o-1)+1;continue}let u=Ae(c,s,o),l=Ee(c,o,u),d=c.slice(u,l);if(t[d]===void 0){let h=Ae(c,o+1,i),y=Ee(c,i,h),m=n(c.slice(h,y));t[d]=m;}s=i+1;}while(s<r);return t}function Ae(c,e,t){do{let r=c.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Ee(c,e,t){for(;e>t;){let r=c.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function yt(c,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!st.test(c))throw new TypeError(`argument name is invalid: ${c}`);let n=r(e);if(!at.test(n))throw new TypeError(`argument val is invalid: ${e}`);let s=c+"="+n;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(!ot.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain;}if(t.path){if(!ct.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path;}if(t.expires){if(!pt(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 ht(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function pt(c){return ut.call(c)==="[object Date]"}});var Me="0123456789ABCDEFGHJKMNPQRSTVWXYZ",V=32;var Ye=16,je=10,Ie=0xffffffffffff;var N;(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";})(N||(N={}));var q=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Xe(c){let e=Math.floor(c()*V);return e===V&&(e=V-1),Me.charAt(e)}function et(c){var r;let e=tt(),t=e&&(e.crypto||e.msCrypto)||(typeof W<"u"?W:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=W)!=null&&r.randomBytes)return ()=>W.randomBytes(1).readUInt8()/255;throw new q(N.PRNGDetectFailure,"Failed to find a reliable PRNG")}function tt(){return it()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function rt(c,e){let t="";for(;c>0;c--)t=Xe(e)+t;return t}function nt(c,e=je){if(isNaN(c))throw new q(N.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>Ie)throw new q(N.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Ie}: ${c}`);if(c<0)throw new q(N.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new q(N.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,r="";for(let n=e;n>0;n--)t=c%V,r=Me.charAt(t)+r,c=(c-t)/V;return r}function it(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Oe(c,e){let t=et(),r=Date.now();return nt(r,je)+rt(Ye,t)}var K=()=>Oe().toLowerCase(),H=c=>({then(e,t){try{if(e){let r=e(c);return r instanceof Promise?r:H(r)}return H(c)}catch(r){if(t){let n=t(r);return n instanceof Promise?n:H(n)}throw r}}}),ie=c=>c instanceof Promise?c:H(c);var D=(...c)=>{let e=c.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var J=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...n}){return new Promise((s,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...n}),i={resource:e,commonWhere:t,uniqueWhere:r,...n,resolve:s,reject:o};this.queue.has(a)||this.queue.set(a,[]);let u=this.queue.get(a);u&&u.push(i),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...n}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(r){t.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:n,include:s,sort:o}=t,a=e.length===1?t.limit:void 0,i=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),u=n,l=(h=Object.entries(i[0]??{})[0])==null?void 0:h[0];if(i.length>0){let y=i.map(m=>m[l]).filter(m=>m!=null);y.length>0&&(u=D(n,{[l]:{$in:y}}));}let d=await this.storage.get({resource:r,where:u,include:s,sort:o,limit:a});for(let y of e){let m=d;if(y.uniqueWhere){let[p,f]=Object.entries(y.uniqueWhere)[0];m=d.filter(T=>{var g;return ((g=T.value[p])==null?void 0:g.value)===f});}y.resolve(m);}}};function se(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})}var G=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,r=this.schema[e];if(!(r!=null&&r.relations))return t;for(let[n,s]of Object.entries(r.relations))s.type==="one"&&s.relationalColumn&&t.set(String(s.relationalColumn),{relationName:n,targetResource:s.entity.name});return t}ensureObjectNode(e,t,r){let n=this.objectNodes.get(e);return n?r&&n.matchedQueries.add(r):(n={id:e,type:t,matchedQueries:new Set(r?[r]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,n)),n}storeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.set(r,t),o&&n){let a=o.referencedByObjects.get(n);a||(a=new Set,o.referencedByObjects.set(n,a)),a.add(e);}}removeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.delete(r),o&&n){let a=o.referencedByObjects.get(n);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(n));}}getInverseRelationName(e,t,r){let n=this.schema[e];if(!(n!=null&&n.relations))return;let s=n.relations[r];if(!s)return;let o=this.schema[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}}}updateRelationsFromMutation(e,t,r,n){let s=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){if(!(n&&a in n))continue;let d=this.getInverseRelationName(e,u,i),h=o.referencesObjects.get(i),y=r[a];h!==y&&(h&&this.removeRelation(t,h,i,d),y&&(this.ensureObjectNode(y,u),this.storeRelation(t,y,i,d)));}}get(e,t){let r=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(r,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new J(this.storage)})}subscribe(e,t,r={}){let n=this.breakdownQuery({query:e,context:r}),s={},o=[];for(let a of n){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let i=se(a),u=s[a.stepPath.at(-2)??""],l=a.stepPath.at(-1)??"",d=this.queryNodes.get(i);if(d)d.subscriptions.add(t);else if(d={hash:i,queryStep:a,relationName:l,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:u,childQueries:new Set},this.queryNodes.set(d.hash,d),u){let h=this.queryNodes.get(u);h&&h.childQueries.add(d.hash);}s[l]=i,o.push(()=>{let h=this.queryNodes.get(i);h&&(h.subscriptions.delete(t),h.subscriptions.size===0&&this.queryNodes.delete(i));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var f;let{query:t,stepPath:r=[],context:n={},parentResource:s}=e,{include:o}=t,a=r.length===0,i=r.at(-1),u,l,d;if(!a&&s&&i){let T=this.schema[s],g=(f=T==null?void 0:T.relations)==null?void 0:f[i];g&&(d=g.type==="many",g.type==="one"?(u=b=>({id:b}),l=b=>b.map(S=>{var R,M;return (M=(R=S.value)==null?void 0:R[g.relationalColumn])==null?void 0:M.value}).filter(S=>S!==void 0)):(u=b=>({[g.foreignColumn]:b}),l=b=>b.map(S=>{var R,M;return (M=(R=S.value)==null?void 0:R.id)==null?void 0:M.value}).filter(S=>S!==void 0)));}let{include:h,...y}=t,p=[this.router.incrementQueryStep({query:y,stepPath:[...r],getWhere:u,referenceGetter:l,isMany:d,relationName:i},n)];if(o&&typeof o=="object"&&Object.keys(o).length>0){let T=this.schema[t.resource];if(!T)throw new Error(`Resource ${t.resource} not found`);p.push(...Object.entries(o).flatMap(([g,b])=>{let S=T.relations[g];if(!S)throw new Error(`Relation ${g} not found for resource ${t.resource}`);let R=S.entity.name;return this.breakdownQuery({query:{resource:R,include:typeof b=="object"?b:void 0},stepPath:[...r,g],context:n,parentResource:t.resource})}));}return p}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(s=>s.stepPath.join(".")).join(" -> "));let r={},n=this.resolveStep(e[0],t).then(s=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",s.length),r[e[0].stepPath.join(".")]=[{data:s}];});for(let s=1;s<e.length;s++){let o=e[s],a=o.stepPath.slice(0,-1).join(".");n=n.then(async()=>{var u,l;let i=r[a];if(!i){r[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let d=new Map;for(let m of i)for(let p of m.data){let f=(l=(u=p==null?void 0:p.value)==null?void 0:u.id)==null?void 0:l.value;if(!f)continue;let g=o.referenceGetter([p])[0];if(g){d.has(g)||d.set(g,new Set);let b=d.get(g);b&&b.add(f);}}let h=Array.from(d.keys());if(h.length===0){r[o.stepPath.join(".")]=[];return}let y=[];for(let m of h){let p=o.getWhere(m),f={...o,relationalWhere:p},T=await this.resolveStep(f,t),g=d.get(m);if(g)for(let b of Array.from(g))y.push({includedBy:b,data:T});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",y.reduce((m,p)=>m+p.data.length,0)),r[o.stepPath.join(".")]=y;}else {let d=await this.resolveStep(o,t);r[o.stepPath.join(".")]=[{data:d}];}});}return n=n.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,r)))),n}assembleResults(e,t){var o,a,i,u,l;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let r=new Map;for(let d of e){let h=d.stepPath.join("."),y=t[h]??[],m=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${h}"`,{resource:d.query.resource,includedRelations:m,resultGroups:y.length,isMany:d.isMany,relationName:d.relationName});for(let p of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${h}"`,{dataCount:p.data.length,includedBy:p.includedBy});for(let f of p.data){let T=(a=(o=f==null?void 0:f.value)==null?void 0:o.id)==null?void 0:a.value;if(!T){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${h}"`);continue}let g=h?`${h}.${T}`:T,b=[];if(d.stepPath.length>0&&p.includedBy){let R=d.stepPath.slice(0,-1).join(".");b=[R?`${R}.${p.includedBy}`:p.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${g}" has parent keys:`,b,{stepPath:h,parentStepPath:R,includedBy:p.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${g}" (no parent)`);let S=r.get(g);if(S){this.logger.debug(`[QueryEngine] assembleResults: Entity "${g}" already exists, adding parent keys:`,b);for(let R of b)S.includedBy.add(R);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${g}"`,{resource:d.query.resource,path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,includedRelations:m,parentKeys:b}),r.set(g,{data:f,includedBy:new Set(b),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.query.resource,includedRelations:m});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${r.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(r.keys()));let n=Array.from(r.entries()),s=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${n.length} entries`);for(let d=n.length-1;d>=0;d--){let[h,y]=n[d],m=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${h}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let p of y.includedRelations){let f=(u=(i=m==null?void 0:m.relations)==null?void 0:i[p])==null?void 0:u.type,T=!!y.data.value[p];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${p}" for "${h}"`,{relationType:f,hasRelation:T,resourceHasRelation:!!((l=m==null?void 0:m.relations)!=null&&l[p])}),y.data.value[p])this.logger.debug(`[QueryEngine] assembleResults: Relation "${p}" already exists for "${h}"`,y.data.value[p]);else {let g=f==="many"?{value:[]}:{value:null};y.data.value[p]=g,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${p}" for "${h}" with`,g);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${h}" to resultData`),s.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to ${y.includedBy.size} parent(s)`);for(let p of Array.from(y.includedBy)){let f=r.get(p);if(!f){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${p}" not found in entriesMap for child "${h}"`);continue}let T=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to parent "${p}" via relation "${T}"`,{isMany:y.isMany,parentHasRelation:!!f.data.value[T]}),y.isMany?(f.data.value[T]??={value:[]},f.data.value[T].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${h}" to many relation "${T}" on parent "${p}"`,{arrayLength:f.data.value[T].value.length})):(f.data.value[T]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${T}" on parent "${p}" to "${h}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${s.length} root items`),s}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:r,relationalWhere:n}=e,s=r.where&&n?D(r.where,n):n??r.where,o=s?{...r,where:s}:r;return ie(this.router.get(o,t)).then(a=>(this.loadStepResults(e,a),a))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let r=se(e),n=this.queryNodes.get(r),s=e.query.resource;if(!n)return;let o=this.getRelationalColumns(s);for(let a of t){let i=z$2(a),u=i.id;this.ensureObjectNode(u,s,r),n.trackedObjects.add(u);for(let[l,{relationName:d,targetResource:h}]of Array.from(o)){let y=i[l];if(y){this.ensureObjectNode(y,h);let m=this.getInverseRelationName(s,h,d);this.storeRelation(u,y,d,m);}}this.loadNestedRelations(s,u,i),this.logger.debug("[QueryEngine] Loaded nested relations for",u);}}loadNestedRelations(e,t,r){let n=this.schema[e];if(n!=null&&n.relations)for(let[s,o]of Object.entries(n.relations)){let a=r[s];if(!a)continue;let i=o.entity.name,u=this.getInverseRelationName(e,i,s);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,i),this.storeRelation(t,a.id,s,u),this.loadNestedRelations(i,a.id,a));else if(o.type==="many"&&Array.isArray(a)){for(let l of a)if(l&&typeof l=="object"&&l.id){this.ensureObjectNode(l.id,i);let d=this.getInverseRelationName(i,e,s);d&&this.storeRelation(l.id,t,d,s),this.loadNestedRelations(i,l.id,l);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let r={};for(let n of Array.from(t.childQueries)){let s=this.queryNodes.get(n);if(!s||!s.relationName)continue;let o=this.buildIncludeFromChildQueries(n);r[s.relationName]=Object.keys(o).length>0?o:true;}return r}sendInsertsForTree(e,t,r){var a,i;let n=(i=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:i.value;if(!n)return;let s={procedure:"INSERT",resource:r,resourceId:n,type:"MUTATE",payload:t.value};for(let u of Array.from(e.subscriptions))try{u(s);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:r,resourceId:n,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(n),this.ensureObjectNode(n,r,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 d=l.relationName,h=l.queryStep.query.resource,y=t.value[d];if(!y)continue;let m=y.value;if(Array.isArray(m))for(let p of m)this.sendInsertsForTree(l,p,h);else m&&typeof m=="object"&&this.sendInsertsForTree(l,m,h);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let r=z$2(t);if(!r)return;let n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,n);let s=this.getRelationalColumns(e.resource);for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){let l=r[a];if(l){this.ensureObjectNode(l,u);let d=this.getInverseRelationName(e.resource,u,i);this.storeRelation(e.resourceId,l,i,d);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,r).then(a=>{for(let i of a){let u=this.queryNodes.get(i);if(u){u.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(i);for(let l of Array.from(u.subscriptions))try{l(e);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:d,queryHash:u.hash,resource:e.resource,resourceId:e.resourceId,stepPath:u.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let r=z$2(t);if(!r)return;let n=this.objectNodes.get(e.resourceId),s=new Set((n==null?void 0:n.matchedQueries)??[]);n||(n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,n)),this.updateRelationsFromMutation(e.resource,e.resourceId,r,e.payload),this.getMatchingQueries(e,r).then(o=>{let a=new Set(o),i=[],u=[],l=[];for(let h of o)s.has(h)?l.push(h):i.push(h);for(let h of Array.from(s))a.has(h)||u.push(h);for(let h of i){let y=this.queryNodes.get(h);y&&y.trackedObjects.add(e.resourceId);}for(let h of u){let y=this.queryNodes.get(h);y&&y.trackedObjects.delete(e.resourceId);}let d=this.objectNodes.get(e.resourceId);if(d){for(let h of i)d.matchedQueries.add(h);for(let h of u)d.matchedQueries.delete(h);}for(let h of [...u,...l]){let y=this.queryNodes.get(h);if(y)for(let m of Array.from(y.subscriptions))try{m(e);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:p,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(i.length>0)for(let h of i){let y=this.queryNodes.get(h);if(!y)continue;let m=this.buildIncludeFromChildQueries(h);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(m).length>0?m:void 0}).then(p=>{!p||p.length===0||this.sendInsertsForTree(y,p[0],e.resource);});}});return}}getMatchingQueries(e,t){let r=[];for(let n of Array.from(this.queryNodes.values()))n.queryStep.query.resource===e.resource&&r.push(n);return r.length===0?ie([]):Promise.all(r.map(async n=>{let s=n.queryStep.query.where,o=n.queryStep.query.resource,a=e.resourceId,i=this.objectNodes.get(a);if(!i)return {hash:n.hash,matches:false};if(n.relationName){let y=n.parentQuery?this.queryNodes.get(n.parentQuery):void 0,m=y==null?void 0:y.queryStep.query.resource,p=m?this.getInverseRelationName(m,o,n.relationName):void 0,f=p?i.referencesObjects.get(p):void 0;if(!f)return {hash:n.hash,matches:false};let T=this.objectNodes.get(f);return !T||!y||!T.matchedQueries.has(y.hash)?{hash:n.hash,matches:false}:{hash:n.hash,matches:true}}if(!s)return {hash:n.hash,matches:true};let u=C$1(s,o,this.schema),l=Object.keys(u).length>0;if(!l&&t!==void 0)return {hash:n.hash,matches:D$1(t,s)};let d=await this.storage.get({resource:o,where:{id:a},include:l?u:void 0});if(!d||d.length===0)return {hash:n.hash,matches:false};let h=z$2(d[0]);return h?{hash:n.hash,matches:D$1(h,s)}:{hash:n.hash,matches:false}})).then(n=>n.filter(s=>s.matches).map(s=>s.hash))}};var Ne=b(ae(),1);var Y=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),oe=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()})),mt=oe.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Pe=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),Ce=z$1.object({timestamp:z$1.string().optional()}).optional(),_=Pe.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:Ce}),B=Pe.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:mt,meta:Ce});z$1.union([B,_]);var Le=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var Qe=Y.omit({resource:true}),ce=_.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:_.shape.meta}),ue=B.omit({id:true,type:true,resource:true,procedure:true});z$1.union([ue,ce]);var de=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(de);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,r]of Object.entries(c))e[t]=de(r);return e}return c},qe=c=>{let e=c.logger;return async t=>{var r;try{let n=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,s={headers:n,cookies:n.cookie?Ne.default.parse(n.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),i=o.searchParams,u=de(gt.parse(i.toString())),l=await((r=c.contextProvider)==null?void 0:r.call(c,{transport:"HTTP",headers:s.headers,cookies:s.cookies,queryParams:u}))??{};if(t.method==="GET"){let d=a[a.length-1],{success:h,data:y,error:m}=Qe.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:m},{status:400});let p=await c.handleQuery({req:{...s,...y,type:"QUERY",resource:d,context:l,queryParams:u}});return !p||!p.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(p.data)}if(t.method==="POST")try{let d=a[a.length-1],h=a[a.length-2];if(h==="query"){if(a.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let T=a[a.length-3],g=t.body?await t.json():{};if(!T||T.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let b=await c.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:T,procedure:d,input:g.input,context:l,queryParams:u}});return Response.json(b)}let y=h,m=t.body?await t.json():{},p;if(d==="insert"||d==="update"){let{success:T,data:g,error:b}=ue.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=g;}else {let{success:T,data:g,error:b}=ce.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=g;}let f=await c.handleMutation({req:{...s,type:"MUTATE",resource:y,input:p.payload,context:l,resourceId:p.resourceId,procedure:d==="insert"||d==="update"?d.toUpperCase():d,queryParams:{},meta:p.meta}});return Response.json(f)}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(n){return e.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var De=b(ae(),1);var L=z$1.string(),le=z$1.union([Le,Y]),Tt=z$1.object({id:L,type:z$1.literal("SUBSCRIBE")}).and(le),bt=z$1.object({id:L,type:z$1.literal("UNSUBSCRIBE")}).and(le),St=z$1.object({id:L,type:z$1.literal("QUERY")}).and(le),Rt=z$1.object({id:L,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),$e=B.extend({id:L}),wt=_.extend({id:L}),vt=z$1.union([wt,$e]),ke=z$1.union([Tt,St,Rt,vt,bt]),xt=z$1.object({id:L,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),It=z$1.object({id:L,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([xt,It,$e]);z$1.object({resource:z$1.string(),data:z$1.array(oe)});var _e=c=>{let e={},t=c.logger;return (r,n)=>{var d;let s=h=>{r.send(JSON.stringify(h));},o=K(),a=new Map,i={headers:n.headers,cookies:typeof n.headers.cookie=="string"?De.default.parse(n.headers.cookie):{}},u=parse(n.url.split("?")[1]),l=(d=c.contextProvider)==null?void 0:d.call(c,{transport:"WEBSOCKET",headers:i.headers,cookies:i.cookies,queryParams:u});e[o]=r,t.info("Client connected:",o),r.on("message",async h=>{try{t.debug("Message received from the client:",h);let y=ke.parse(JSON.parse(h.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:m,id:p,...f}=y,T=m==="SUBSCRIBE";if("procedure"in f){let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:f.resource,procedure:f.procedure,input:f.input,context:await l??{},queryParams:u},subscription:T?b=>{var S;!b.resourceId||!b.payload||!Object.keys(b.payload).length||(S=e[o])==null||S.send(JSON.stringify(b));}:void 0});if(T){if(!g||!g.data||!g.query)throw new Error("Invalid resource");g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:g.query.resource,data:(g.data??[]).map(b=>b.value)}});}else s({id:p,type:"REPLY",data:g});}else {let g=await c.handleQuery({req:{...i,...f,type:"QUERY",context:await l??{},queryParams:u},subscription:T?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||!g.data)throw new Error("Invalid resource");T&&g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:f.resource,data:(g.data??[]).map(b=>b.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:m,id:p,...f}=y,T=a.get(B$1(f));T&&(T(),a.delete(B$1(f)));}else if(y.type==="CUSTOM_QUERY"){let{resource:m,procedure:p,input:f,id:T}=y;t.debug("Received custom query from client:",y);try{let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:m,procedure:p,input:f,context:await l??{},queryParams:u}});s({id:T,type:"REPLY",data:g});}catch(g){s({id:T,type:"REJECT",resource:m,message:g.message}),t.error("Error handling custom query from the client:",g);}}else if(y.type==="MUTATE"){let{resource:m}=y;t.debug("Received mutation from client:",y);try{let p=await c.handleMutation({req:{...i,type:"MUTATE",resource:m,input:y.payload,context:{messageId:y.id,...await l??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:u,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&s({id:y.id,type:"REPLY",data:p});}catch(p){s({id:y.id,type:"REJECT",resource:m,message:p.message}),t.error("Error parsing mutation from the client:",p);}}}catch(y){t.error("Error handling message from the client:",y);}}),r.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let h of Array.from(a.values()))h();});}};function Ve(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var Lr=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,_e(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{qe(e)(Ve(r)).then(o=>o.json().then(a=>n.status(o.status).send(a)));});};var X=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,r,n,s,o,a,i){this._collection=e,this._client=t,this._where=r??{},this._include=n??{},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 r=[...this._sort??[],{key:e,direction:t}];return new c(this._collection,this._client,this._where,this._include,this._limit,this._single,r,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,r){return new c(e,t,void 0,void 0,void 0,void 0,void 0,r??false)}};var jt=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),ye=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(r=>jt(r)?z$2(r):r))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function $(c,e){let t=new ye(c),r=s=>{let o=X._init(s,t,true);return Object.assign(Object.create(o),{insert:i=>c.insert(s,i),update:(i,u)=>c.update(s,i,u)})},n={get(s,o){if(o==="findOne")return c.findOne.bind(c);if(o==="find")return c.find.bind(c);if(o==="insert")return c.insert.bind(c);if(o==="update")return c.update.bind(c);if(o==="transaction")return async a=>c.transaction(async({trx:i,commit:u,rollback:l})=>{let d=$(i,e);return a({trx:d,commit:u,rollback:l})});if(o in e){let a=e[o];return r(a)}}};return new Proxy({},n)}var he=class c{routes;hooksRegistry=new Map;constructor(e){this.routes=e.routes;for(let t of Object.values(e.routes)){if(t.resourceSchema===void 0)continue;let r=t;r.hooks&&this.hooksRegistry.set(r.resourceSchema.name,r.hooks);}}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}},zr=c=>he.create({...c}),ze=(c=>({handler:e=>({_type:"query",inputValidator:c??z$1.undefined(),handler:e})})),Fe=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z$1.undefined(),handler:e})})),pe=class c{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,r,n,s){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=r??{},this.authorization=n,this.hooks=s;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:Fe,query:ze}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new c(this.resourceSchema,r,n,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new c(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async r=>{let n={resource:r.resource,where:r.where,include:r.include,lastSyncedAt:r.lastSyncedAt,limit:r.limit,sort:r.sort},s=B$1(n);return {data:await t.rawFind({resource:r.resource,commonWhere:r.where,uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort}),unsubscribe:void 0,queryHash:s}})(e);handleMutation=async({req:e,db:t,schema:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}else {if(i.procedure==="INSERT"||i.procedure==="UPDATE")return this.handleSet({req:i,db:s,operation:i.procedure,schema:r});throw new Error(`Unknown procedure: ${i.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(e){var t,r;return (r=(t=this.authorization)==null?void 0:t.read)==null?void 0:r.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:r,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let s=await t.rawFindById(e.resource,e.resourceId);if(r==="INSERT"&&s)throw new Error("Resource already exists");if(r==="UPDATE"&&!s)throw new Error("Resource not found");let o={value:e.input};return t.transaction(async({trx:a})=>{var l,d,h,y,m,p,f;if(r==="INSERT"){let{data:T,acceptedValues:g}=await a.rawInsert(e.resource,e.resourceId,o,(l=e.context)==null?void 0:l.messageId,e.context);if(!g)throw new Error("Mutation rejected");let b=z$2(T);if(b.id=b.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let S=this.authorization.insert({ctx:e.context,value:b});if(typeof S=="boolean"){if(!S)throw new Error("Not authorized")}else {let R=C$1(S,e.resource,n),M=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):T,v=z$2(M);if(v.id=v.id??e.resourceId,!D$1(v,S))throw new Error("Not authorized")}}return {data:T,acceptedValues:g}}if((y=(h=this.authorization)==null?void 0:h.update)!=null&&y.preMutation){let T=z$2(s);T.id=T.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let b=C$1(g,e.resource,n),S=Object.keys(b).length>0?await a.rawFindById(e.resource,e.resourceId,b):s,R=z$2(S);if(R.id=R.id??e.resourceId,!D$1(R,g))throw new Error("Not authorized")}}let{data:i,acceptedValues:u}=await a.rawUpdate(e.resource,e.resourceId,o,(m=e.context)==null?void 0:m.messageId,e.context);if(!u)throw new Error("Mutation rejected");if((f=(p=this.authorization)==null?void 0:p.update)!=null&&f.postMutation){let T=z$2(i);T.id=T.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let b=C$1(g,e.resource,n),S=Object.keys(b).length>0?await a.rawFindById(e.resource,e.resourceId,b):i,R=z$2(S);if(R.id=R.id??e.resourceId,!D$1(R,g))throw new Error("Not authorized")}}return {data:i,acceptedValues:u}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},me=class{resourceSchema=void 0;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:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}throw new Error(`Unknown procedure: ${i.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},fe=class c{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new pe(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:Fe,query:ze}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new me(r,n).use(...this.middlewares)}use(...e){return new c([...this.middlewares,...e])}static create(){return new c}},Fr=fe.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 r=this._getTimestamp(),n=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([s,o])=>[s,{value:o,_meta:{timestamp:r}}]))});return z$2(n.data)}async update(e,t,r){let n=this._getTimestamp(),{id:s,...o}=r,a=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([l,d])=>[l,{value:d,_meta:{timestamp:n}}]))}),i=z$2(a.data),u={};for(let l of Object.keys(o))l in i&&(u[l]=i[l]);return u}};var Qt={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function C(c){var n,s,o;let e=(n=c.getExecutor)==null?void 0:n.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let r=((o=(s=t.constructor)==null?void 0:s.name)==null?void 0:o.toLowerCase())??"";return r.includes("postgres")?"postgres":r.includes("mysql")?"mysql":r.includes("sqlite")?"sqlite":"postgres"}function Ue(c){let e=C(c);return Qt[e]}var Nt="42701";function F(c){var t;if(c.code===Nt)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 Te(c,e){let{type:t,enumValues:r,enumName:n}=c;if(r&&r.length>0)return e==="postgres"&&n?n:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function qt(c,e,t,r){if(t!=="postgres")return;let n=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&&n.set(a.enumName,{name:a.enumName,values:a.enumValues});}for(let s of Array.from(n.values())){let{name:o,values:a}=s;try{let i=a.map(u=>`'${u}'`).join(", ");await sql`
1
+ import {a,b,B as B$1,z as z$2,C as C$1,D as D$1,G as G$1,F as F$1,E}from'./chunk-3XEJ2M4E.js';import H from'crypto';import Tt,{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 oe=a(Y=>{Object.defineProperty(Y,"__esModule",{value:true});Y.parse=yt;Y.serialize=ht;var at=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ot=/^[\u0021-\u003A\u003C-\u007E]*$/,ct=/^([.]?[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]*$/,dt=Object.prototype.toString,lt=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function yt(c,e){let t=new lt,r=c.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||pt,s=0;do{let o=c.indexOf("=",s);if(o===-1)break;let a=c.indexOf(";",s),i=a===-1?r:a;if(o>i){s=c.lastIndexOf(";",o-1)+1;continue}let u=Ee(c,s,o),l=Pe(c,o,u),d=c.slice(u,l);if(t[d]===void 0){let h=Ee(c,o+1,i),y=Pe(c,i,h),m=n(c.slice(h,y));t[d]=m;}s=i+1;}while(s<r);return t}function Ee(c,e,t){do{let r=c.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Pe(c,e,t){for(;e>t;){let r=c.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function ht(c,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!at.test(c))throw new TypeError(`argument name is invalid: ${c}`);let n=r(e);if(!ot.test(n))throw new TypeError(`argument val is invalid: ${e}`);let s=c+"="+n;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(!ct.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(!mt(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 pt(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function mt(c){return dt.call(c)==="[object Date]"}});var je="0123456789ABCDEFGHJKMNPQRSTVWXYZ",V=32;var Xe=16,Oe=10,Me=0xffffffffffff;var N;(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";})(N||(N={}));var q=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function et(c){let e=Math.floor(c()*V);return e===V&&(e=V-1),je.charAt(e)}function tt(c){var r;let e=rt(),t=e&&(e.crypto||e.msCrypto)||(typeof H<"u"?H:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=H)!=null&&r.randomBytes)return ()=>H.randomBytes(1).readUInt8()/255;throw new q(N.PRNGDetectFailure,"Failed to find a reliable PRNG")}function rt(){return st()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function nt(c,e){let t="";for(;c>0;c--)t=et(e)+t;return t}function it(c,e=Oe){if(isNaN(c))throw new q(N.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>Me)throw new q(N.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Me}: ${c}`);if(c<0)throw new q(N.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new q(N.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,r="";for(let n=e;n>0;n--)t=c%V,r=je.charAt(t)+r,c=(c-t)/V;return r}function st(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ae(c,e){let t=tt(),r=Date.now();return it(r,Oe)+nt(Xe,t)}var J=()=>Ae().toLowerCase(),K=c=>({then(e,t){try{if(e){let r=e(c);return r instanceof Promise?r:K(r)}return K(c)}catch(r){if(t){let n=t(r);return n instanceof Promise?n:K(n)}throw r}}}),se=c=>c instanceof Promise?c:K(c);var D=(...c)=>{let e=c.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var G=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...n}){return new Promise((s,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...n}),i={resource:e,commonWhere:t,uniqueWhere:r,...n,resolve:s,reject:o};this.queue.has(a)||this.queue.set(a,[]);let u=this.queue.get(a);u&&u.push(i),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...n}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(r){t.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:n,include:s,sort:o}=t,a=e.length===1?t.limit:void 0,i=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),u=n,l=(h=Object.entries(i[0]??{})[0])==null?void 0:h[0];if(i.length>0){let y=i.map(m=>m[l]).filter(m=>m!=null);y.length>0&&(u=D(n,{[l]:{$in:y}}));}let d=await this.storage.get({resource:r,where:u,include:s,sort:o,limit:a});for(let y of e){let m=d;if(y.uniqueWhere){let[p,f]=Object.entries(y.uniqueWhere)[0];m=d.filter(T=>{var g;return ((g=T.value[p])==null?void 0:g.value)===f});}y.resolve(m);}}};function ae(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})}var Z=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,r=this.schema[e];if(!(r!=null&&r.relations))return t;for(let[n,s]of Object.entries(r.relations))s.type==="one"&&s.relationalColumn&&t.set(String(s.relationalColumn),{relationName:n,targetResource:s.entity.name});return t}ensureObjectNode(e,t,r){let n=this.objectNodes.get(e);return n?r&&n.matchedQueries.add(r):(n={id:e,type:t,matchedQueries:new Set(r?[r]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,n)),n}storeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.set(r,t),o&&n){let a=o.referencedByObjects.get(n);a||(a=new Set,o.referencedByObjects.set(n,a)),a.add(e);}}removeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.delete(r),o&&n){let a=o.referencedByObjects.get(n);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(n));}}getInverseRelationName(e,t,r){let n=this.schema[e];if(!(n!=null&&n.relations))return;let s=n.relations[r];if(!s)return;let o=this.schema[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}}}updateRelationsFromMutation(e,t,r,n){let s=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){if(!(n&&a in n))continue;let d=this.getInverseRelationName(e,u,i),h=o.referencesObjects.get(i),y=r[a];h!==y&&(h&&this.removeRelation(t,h,i,d),y&&(this.ensureObjectNode(y,u),this.storeRelation(t,y,i,d)));}}get(e,t){let r=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(r,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new G(this.storage)})}subscribe(e,t,r={}){let n=this.breakdownQuery({query:e,context:r}),s={},o=[];for(let a of n){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let i=ae(a),u=s[a.stepPath.at(-2)??""],l=a.stepPath.at(-1)??"",d=this.queryNodes.get(i);if(d)d.subscriptions.add(t);else if(d={hash:i,queryStep:a,relationName:l,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:u,childQueries:new Set},this.queryNodes.set(d.hash,d),u){let h=this.queryNodes.get(u);h&&h.childQueries.add(d.hash);}s[l]=i,o.push(()=>{let h=this.queryNodes.get(i);h&&(h.subscriptions.delete(t),h.subscriptions.size===0&&this.queryNodes.delete(i));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var f;let{query:t,stepPath:r=[],context:n={},parentResource:s}=e,{include:o}=t,a=r.length===0,i=r.at(-1),u,l,d;if(!a&&s&&i){let T=this.schema[s],g=(f=T==null?void 0:T.relations)==null?void 0:f[i];g&&(d=g.type==="many",g.type==="one"?(u=S=>({id:S}),l=S=>S.map(b=>{var R,w;return (w=(R=b.value)==null?void 0:R[g.relationalColumn])==null?void 0:w.value}).filter(b=>b!==void 0)):(u=S=>({[g.foreignColumn]:S}),l=S=>S.map(b=>{var R,w;return (w=(R=b.value)==null?void 0:R.id)==null?void 0:w.value}).filter(b=>b!==void 0)));}let{include:h,...y}=t,p=[this.router.incrementQueryStep({query:y,stepPath:[...r],getWhere:u,referenceGetter:l,isMany:d,relationName:i},n)];if(o&&typeof o=="object"&&Object.keys(o).length>0){let T=this.schema[t.resource];if(!T)throw new Error(`Resource ${t.resource} not found`);p.push(...Object.entries(o).flatMap(([g,S])=>{let b=T.relations[g];if(!b)throw new Error(`Relation ${g} not found for resource ${t.resource}`);let R=b.entity.name,w=E(S)?S:null;return this.breakdownQuery({query:{resource:R,include:w?w.include:typeof S=="object"?S:void 0,where:w==null?void 0:w.where,limit:w==null?void 0:w.limit,sort:w==null?void 0:w.orderBy},stepPath:[...r,g],context:n,parentResource:t.resource})}));}return p}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(s=>s.stepPath.join(".")).join(" -> "));let r={},n=this.resolveStep(e[0],t).then(s=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",s.length),r[e[0].stepPath.join(".")]=[{data:s}];});for(let s=1;s<e.length;s++){let o=e[s],a=o.stepPath.slice(0,-1).join(".");n=n.then(async()=>{var u,l;let i=r[a];if(!i){r[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let d=new Map;for(let m of i)for(let p of m.data){let f=(l=(u=p==null?void 0:p.value)==null?void 0:u.id)==null?void 0:l.value;if(!f)continue;let g=o.referenceGetter([p])[0];if(g){d.has(g)||d.set(g,new Set);let S=d.get(g);S&&S.add(f);}}let h=Array.from(d.keys());if(h.length===0){r[o.stepPath.join(".")]=[];return}let y=[];for(let m of h){let p=o.getWhere(m),f={...o,relationalWhere:p},T=await this.resolveStep(f,t),g=d.get(m);if(g)for(let S of Array.from(g))y.push({includedBy:S,data:T});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",y.reduce((m,p)=>m+p.data.length,0)),r[o.stepPath.join(".")]=y;}else {let d=await this.resolveStep(o,t);r[o.stepPath.join(".")]=[{data:d}];}});}return n=n.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,r)))),n}assembleResults(e,t){var o,a,i,u,l;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let r=new Map;for(let d of e){let h=d.stepPath.join("."),y=t[h]??[],m=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${h}"`,{resource:d.query.resource,includedRelations:m,resultGroups:y.length,isMany:d.isMany,relationName:d.relationName});for(let p of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${h}"`,{dataCount:p.data.length,includedBy:p.includedBy});for(let f of p.data){let T=(a=(o=f==null?void 0:f.value)==null?void 0:o.id)==null?void 0:a.value;if(!T){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${h}"`);continue}let g=h?`${h}.${T}`:T,S=[];if(d.stepPath.length>0&&p.includedBy){let R=d.stepPath.slice(0,-1).join(".");S=[R?`${R}.${p.includedBy}`:p.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${g}" has parent keys:`,S,{stepPath:h,parentStepPath:R,includedBy:p.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${g}" (no parent)`);let b=r.get(g);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${g}" already exists, adding parent keys:`,S);for(let R of S)b.includedBy.add(R);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${g}"`,{resource:d.query.resource,path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,includedRelations:m,parentKeys:S}),r.set(g,{data:f,includedBy:new Set(S),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.query.resource,includedRelations:m});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${r.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(r.keys()));let n=Array.from(r.entries()),s=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${n.length} entries`);for(let d=n.length-1;d>=0;d--){let[h,y]=n[d],m=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${h}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let p of y.includedRelations){let f=(u=(i=m==null?void 0:m.relations)==null?void 0:i[p])==null?void 0:u.type,T=!!y.data.value[p];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${p}" for "${h}"`,{relationType:f,hasRelation:T,resourceHasRelation:!!((l=m==null?void 0:m.relations)!=null&&l[p])}),y.data.value[p])this.logger.debug(`[QueryEngine] assembleResults: Relation "${p}" already exists for "${h}"`,y.data.value[p]);else {let g=f==="many"?{value:[]}:{value:null};y.data.value[p]=g,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${p}" for "${h}" with`,g);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${h}" to resultData`),s.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to ${y.includedBy.size} parent(s)`);for(let p of Array.from(y.includedBy)){let f=r.get(p);if(!f){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${p}" not found in entriesMap for child "${h}"`);continue}let T=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to parent "${p}" via relation "${T}"`,{isMany:y.isMany,parentHasRelation:!!f.data.value[T]}),y.isMany?(f.data.value[T]??={value:[]},f.data.value[T].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${h}" to many relation "${T}" on parent "${p}"`,{arrayLength:f.data.value[T].value.length})):(f.data.value[T]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${T}" on parent "${p}" to "${h}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${s.length} root items`),s}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:r,relationalWhere:n}=e,s=r.where&&n?D(r.where,n):n??r.where,o=s?{...r,where:s}:r;return se(this.router.get(o,t)).then(a=>(this.loadStepResults(e,a),a))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let r=ae(e),n=this.queryNodes.get(r),s=e.query.resource;if(!n)return;let o=this.getRelationalColumns(s);for(let a of t){let i=z$2(a),u=i.id;this.ensureObjectNode(u,s,r),n.trackedObjects.add(u);for(let[l,{relationName:d,targetResource:h}]of Array.from(o)){let y=i[l];if(y){this.ensureObjectNode(y,h);let m=this.getInverseRelationName(s,h,d);this.storeRelation(u,y,d,m);}}this.loadNestedRelations(s,u,i),this.logger.debug("[QueryEngine] Loaded nested relations for",u);}}loadNestedRelations(e,t,r){let n=this.schema[e];if(n!=null&&n.relations)for(let[s,o]of Object.entries(n.relations)){let a=r[s];if(!a)continue;let i=o.entity.name,u=this.getInverseRelationName(e,i,s);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,i),this.storeRelation(t,a.id,s,u),this.loadNestedRelations(i,a.id,a));else if(o.type==="many"&&Array.isArray(a)){for(let l of a)if(l&&typeof l=="object"&&l.id){this.ensureObjectNode(l.id,i);let d=this.getInverseRelationName(i,e,s);d&&this.storeRelation(l.id,t,d,s),this.loadNestedRelations(i,l.id,l);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let r={};for(let n of Array.from(t.childQueries)){let s=this.queryNodes.get(n);if(!s||!s.relationName)continue;let o=this.buildIncludeFromChildQueries(n);r[s.relationName]=Object.keys(o).length>0?o:true;}return r}sendInsertsForTree(e,t,r){var a,i;let n=(i=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:i.value;if(!n)return;let s={procedure:"INSERT",resource:r,resourceId:n,type:"MUTATE",payload:t.value};for(let u of Array.from(e.subscriptions))try{u(s);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:r,resourceId:n,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(n),this.ensureObjectNode(n,r,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 d=l.relationName,h=l.queryStep.query.resource,y=t.value[d];if(!y)continue;let m=y.value;if(Array.isArray(m))for(let p of m)this.sendInsertsForTree(l,p,h);else m&&typeof m=="object"&&this.sendInsertsForTree(l,m,h);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let r=z$2(t);if(!r)return;let n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,n);let s=this.getRelationalColumns(e.resource);for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){let l=r[a];if(l){this.ensureObjectNode(l,u);let d=this.getInverseRelationName(e.resource,u,i);this.storeRelation(e.resourceId,l,i,d);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,r).then(a=>{for(let i of a){let u=this.queryNodes.get(i);if(u){u.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(i);for(let l of Array.from(u.subscriptions))try{l(e);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:d,queryHash:u.hash,resource:e.resource,resourceId:e.resourceId,stepPath:u.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let r=z$2(t);if(!r)return;let n=this.objectNodes.get(e.resourceId),s=new Set((n==null?void 0:n.matchedQueries)??[]);n||(n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,n)),this.updateRelationsFromMutation(e.resource,e.resourceId,r,e.payload),this.getMatchingQueries(e,r).then(o=>{let a=new Set(o),i=[],u=[],l=[];for(let h of o)s.has(h)?l.push(h):i.push(h);for(let h of Array.from(s))a.has(h)||u.push(h);for(let h of i){let y=this.queryNodes.get(h);y&&y.trackedObjects.add(e.resourceId);}for(let h of u){let y=this.queryNodes.get(h);y&&y.trackedObjects.delete(e.resourceId);}let d=this.objectNodes.get(e.resourceId);if(d){for(let h of i)d.matchedQueries.add(h);for(let h of u)d.matchedQueries.delete(h);}for(let h of [...u,...l]){let y=this.queryNodes.get(h);if(y)for(let m of Array.from(y.subscriptions))try{m(e);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:p,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(i.length>0)for(let h of i){let y=this.queryNodes.get(h);if(!y)continue;let m=this.buildIncludeFromChildQueries(h);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(m).length>0?m:void 0}).then(p=>{!p||p.length===0||this.sendInsertsForTree(y,p[0],e.resource);});}});return}}getMatchingQueries(e,t){let r=[];for(let n of Array.from(this.queryNodes.values()))n.queryStep.query.resource===e.resource&&r.push(n);return r.length===0?se([]):Promise.all(r.map(async n=>{let s=n.queryStep.query.where,o=n.queryStep.query.resource,a=e.resourceId,i=this.objectNodes.get(a);if(!i)return {hash:n.hash,matches:false};if(n.relationName){let y=n.parentQuery?this.queryNodes.get(n.parentQuery):void 0,m=y==null?void 0:y.queryStep.query.resource,p=m?this.getInverseRelationName(m,o,n.relationName):void 0,f=p?i.referencesObjects.get(p):void 0;if(!f)return {hash:n.hash,matches:false};let T=this.objectNodes.get(f);return !T||!y||!T.matchedQueries.has(y.hash)?{hash:n.hash,matches:false}:{hash:n.hash,matches:true}}if(!s)return {hash:n.hash,matches:true};let u=C$1(s,o,this.schema),l=Object.keys(u).length>0;if(!l&&t!==void 0)return {hash:n.hash,matches:D$1(t,s)};let d=await this.storage.get({resource:o,where:{id:a},include:l?u:void 0});if(!d||d.length===0)return {hash:n.hash,matches:false};let h=z$2(d[0]);return h?{hash:n.hash,matches:D$1(h,s)}:{hash:n.hash,matches:false}})).then(n=>n.filter(s=>s.matches).map(s=>s.hash))}};var qe=b(oe(),1);var X=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),ce=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()})),ft=ce.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ce=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()}).optional(),_=Ce.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:Le}),B=Ce.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:ft,meta:Le});z$1.union([B,_]);var Qe=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var Ne=X.omit({resource:true}),ue=_.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:_.shape.meta}),de=B.omit({id:true,type:true,resource:true,procedure:true});z$1.union([de,ue]);var le=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(le);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,r]of Object.entries(c))e[t]=le(r);return e}return c},$e=c=>{let e=c.logger;return async t=>{var r;try{let n=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,s={headers:n,cookies:n.cookie?qe.default.parse(n.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),i=o.searchParams,u=le(Tt.parse(i.toString())),l=await((r=c.contextProvider)==null?void 0:r.call(c,{transport:"HTTP",headers:s.headers,cookies:s.cookies,queryParams:u}))??{};if(t.method==="GET"){let d=a[a.length-1],{success:h,data:y,error:m}=Ne.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:m},{status:400});let p=await c.handleQuery({req:{...s,...y,type:"QUERY",resource:d,context:l,queryParams:u}});return !p||!p.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(p.data)}if(t.method==="POST")try{let d=a[a.length-1],h=a[a.length-2];if(h==="query"){if(a.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let T=a[a.length-3],g=t.body?await t.json():{};if(!T||T.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let S=await c.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:T,procedure:d,input:g.input,context:l,queryParams:u}});return Response.json(S)}let y=h,m=t.body?await t.json():{},p;if(d==="insert"||d==="update"){let{success:T,data:g,error:S}=de.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:S},{status:400});p=g;}else {let{success:T,data:g,error:S}=ue.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:S},{status:400});p=g;}let f=await c.handleMutation({req:{...s,type:"MUTATE",resource:y,input:p.payload,context:l,resourceId:p.resourceId,procedure:d==="insert"||d==="update"?d.toUpperCase():d,queryParams:{},meta:p.meta}});return Response.json(f)}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(n){return e.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var _e=b(oe(),1);var L=z$1.string(),ye=z$1.union([Qe,X]),St=z$1.object({id:L,type:z$1.literal("SUBSCRIBE")}).and(ye),bt=z$1.object({id:L,type:z$1.literal("UNSUBSCRIBE")}).and(ye),Rt=z$1.object({id:L,type:z$1.literal("QUERY")}).and(ye),wt=z$1.object({id:L,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),ke=B.extend({id:L}),vt=_.extend({id:L}),xt=z$1.union([vt,ke]),De=z$1.union([St,Rt,wt,xt,bt]),It=z$1.object({id:L,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),Mt=z$1.object({id:L,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([It,Mt,ke]);z$1.object({resource:z$1.string(),data:z$1.array(ce)});var Ve=c=>{let e={},t=c.logger;return (r,n)=>{var d;let s=h=>{r.send(JSON.stringify(h));},o=J(),a=new Map,i={headers:n.headers,cookies:typeof n.headers.cookie=="string"?_e.default.parse(n.headers.cookie):{}},u=parse(n.url.split("?")[1]),l=(d=c.contextProvider)==null?void 0:d.call(c,{transport:"WEBSOCKET",headers:i.headers,cookies:i.cookies,queryParams:u});e[o]=r,t.info("Client connected:",o),r.on("message",async h=>{try{t.debug("Message received from the client:",h);let y=De.parse(JSON.parse(h.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:m,id:p,...f}=y,T=m==="SUBSCRIBE";if("procedure"in f){let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:f.resource,procedure:f.procedure,input:f.input,context:await l??{},queryParams:u},subscription:T?S=>{var b;!S.resourceId||!S.payload||!Object.keys(S.payload).length||(b=e[o])==null||b.send(JSON.stringify(S));}:void 0});if(T){if(!g||!g.data||!g.query)throw new Error("Invalid resource");g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:g.query.resource,data:(g.data??[]).map(S=>S.value)}});}else s({id:p,type:"REPLY",data:g});}else {let g=await c.handleQuery({req:{...i,...f,type:"QUERY",context:await l??{},queryParams:u},subscription:T?S=>{var b;!S.resourceId||!S.payload||!Object.keys(S.payload).length||(b=e[o])==null||b.send(JSON.stringify(S));}:void 0});if(!g||!g.data)throw new Error("Invalid resource");T&&g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:f.resource,data:(g.data??[]).map(S=>S.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:m,id:p,...f}=y,T=a.get(B$1(f));T&&(T(),a.delete(B$1(f)));}else if(y.type==="CUSTOM_QUERY"){let{resource:m,procedure:p,input:f,id:T}=y;t.debug("Received custom query from client:",y);try{let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:m,procedure:p,input:f,context:await l??{},queryParams:u}});s({id:T,type:"REPLY",data:g});}catch(g){s({id:T,type:"REJECT",resource:m,message:g.message}),t.error("Error handling custom query from the client:",g);}}else if(y.type==="MUTATE"){let{resource:m}=y;t.debug("Received mutation from client:",y);try{let p=await c.handleMutation({req:{...i,type:"MUTATE",resource:m,input:y.payload,context:{messageId:y.id,...await l??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:u,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&s({id:y.id,type:"REPLY",data:p});}catch(p){s({id:y.id,type:"REJECT",resource:m,message:p.message}),t.error("Error parsing mutation from the client:",p);}}}catch(y){t.error("Error handling message from the client:",y);}}),r.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let h of Array.from(a.values()))h();});}};function Be(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var Lr=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Ve(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{$e(e)(Be(r)).then(o=>o.json().then(a=>n.status(o.status).send(a)));});};var ee=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,r,n,s,o,a,i){this._collection=e,this._client=t,this._where=r??{},this._include=n??{},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 r=[...this._sort??[],{key:e,direction:t}];return new c(this._collection,this._client,this._where,this._include,this._limit,this._single,r,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,r){return new c(e,t,void 0,void 0,void 0,void 0,void 0,r??false)}};var Ot=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),he=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(r=>Ot(r)?z$2(r):r))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function $(c,e){let t=new he(c),r=s=>{let o=ee._init(s,t,true);return Object.assign(Object.create(o),{insert:i=>c.insert(s,i),update:(i,u)=>c.update(s,i,u)})},n={get(s,o){if(o==="findOne")return c.findOne.bind(c);if(o==="find")return c.find.bind(c);if(o==="insert")return c.insert.bind(c);if(o==="update")return c.update.bind(c);if(o==="transaction")return async a=>c.transaction(async({trx:i,commit:u,rollback:l})=>{let d=$(i,e);return a({trx:d,commit:u,rollback:l})});if(o in e){let a=e[o];return r(a)}}};return new Proxy({},n)}var pe=class c{routes;hooksRegistry=new Map;constructor(e){this.routes=e.routes;for(let t of Object.values(e.routes)){if(t.resourceSchema===void 0)continue;let r=t;r.hooks&&this.hooksRegistry.set(r.resourceSchema.name,r.hooks);}}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}},zr=c=>pe.create({...c}),Fe=(c=>({handler:e=>({_type:"query",inputValidator:c??z$1.undefined(),handler:e})})),Ue=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z$1.undefined(),handler:e})})),me=class c{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,r,n,s){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=r??{},this.authorization=n,this.hooks=s;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:Ue,query:Fe}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new c(this.resourceSchema,r,n,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new c(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async r=>{let n={resource:r.resource,where:r.where,include:r.include,lastSyncedAt:r.lastSyncedAt,limit:r.limit,sort:r.sort},s=B$1(n);return {data:await t.rawFind({resource:r.resource,commonWhere:r.where,uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort}),unsubscribe:void 0,queryHash:s}})(e);handleMutation=async({req:e,db:t,schema:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}else {if(i.procedure==="INSERT"||i.procedure==="UPDATE")return this.handleSet({req:i,db:s,operation:i.procedure,schema:r});throw new Error(`Unknown procedure: ${i.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(e){var t,r;return (r=(t=this.authorization)==null?void 0:t.read)==null?void 0:r.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:r,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let s=await t.rawFindById(e.resource,e.resourceId);if(r==="INSERT"&&s)throw new Error("Resource already exists");if(r==="UPDATE"&&!s)throw new Error("Resource not found");let o={value:e.input};return t.transaction(async({trx:a})=>{var l,d,h,y,m,p,f;if(r==="INSERT"){let{data:T,acceptedValues:g}=await a.rawInsert(e.resource,e.resourceId,o,(l=e.context)==null?void 0:l.messageId,e.context);if(!g)throw new Error("Mutation rejected");let S=z$2(T);if(S.id=S.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let b=this.authorization.insert({ctx:e.context,value:S});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let R=C$1(b,e.resource,n),w=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):T,x=z$2(w);if(x.id=x.id??e.resourceId,!D$1(x,b))throw new Error("Not authorized")}}return {data:T,acceptedValues:g}}if((y=(h=this.authorization)==null?void 0:h.update)!=null&&y.preMutation){let T=z$2(s);T.id=T.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let S=C$1(g,e.resource,n),b=Object.keys(S).length>0?await a.rawFindById(e.resource,e.resourceId,S):s,R=z$2(b);if(R.id=R.id??e.resourceId,!D$1(R,g))throw new Error("Not authorized")}}let{data:i,acceptedValues:u}=await a.rawUpdate(e.resource,e.resourceId,o,(m=e.context)==null?void 0:m.messageId,e.context);if(!u)throw new Error("Mutation rejected");if((f=(p=this.authorization)==null?void 0:p.update)!=null&&f.postMutation){let T=z$2(i);T.id=T.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let S=C$1(g,e.resource,n),b=Object.keys(S).length>0?await a.rawFindById(e.resource,e.resourceId,S):i,R=z$2(b);if(R.id=R.id??e.resourceId,!D$1(R,g))throw new Error("Not authorized")}}return {data:i,acceptedValues:u}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},fe=class{resourceSchema=void 0;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:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}throw new Error(`Unknown procedure: ${i.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},ge=class c{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new me(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:Ue,query:Fe}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new fe(r,n).use(...this.middlewares)}use(...e){return new c([...this.middlewares,...e])}static create(){return new c}},Fr=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 r=this._getTimestamp(),n=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([s,o])=>[s,{value:o,_meta:{timestamp:r}}]))});return z$2(n.data)}async update(e,t,r){let n=this._getTimestamp(),{id:s,...o}=r,a=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([l,d])=>[l,{value:d,_meta:{timestamp:n}}]))}),i=z$2(a.data),u={};for(let l of Object.keys(o))l in i&&(u[l]=i[l]);return u}};var Nt={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function C(c){var n,s,o;let e=(n=c.getExecutor)==null?void 0:n.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let r=((o=(s=t.constructor)==null?void 0:s.name)==null?void 0:o.toLowerCase())??"";return r.includes("postgres")?"postgres":r.includes("mysql")?"mysql":r.includes("sqlite")?"sqlite":"postgres"}function We(c){let e=C(c);return Nt[e]}var qt="42701";function F(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:r,enumName:n}=c;if(r&&r.length>0)return e==="postgres"&&n?n:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function $t(c,e,t,r){if(t!=="postgres")return;let n=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&&n.set(a.enumName,{name:a.enumName,values:a.enumValues});}for(let s of Array.from(n.values())){let{name:o,values:a}=s;try{let i=a.map(u=>`'${u}'`).join(", ");await sql`
2
2
  DO $$ BEGIN
3
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){r==null||r.warn("Could not create enum type",o,i);}}}function U(c,e){return c.some(t=>t.name===e)}function $t(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function be(c,e){let[t]=e.split(".");return U(c,t)}function ge(c,e,t,r=false){let n=c;return e.unique&&(n=n.unique()),e.nullable||(n=n.notNull()),e.primary&&(n=n.primaryKey()),e.default!==void 0&&(n=n.defaultTo(e.default)),!r&&e.references&&be(t,e.references)&&(n=n.references(e.references)),n}function kt(c,e,t,r,n){let s=[];for(let[o,a]of Object.entries(c.fields)){let i=e==null?void 0:e.columns.find(l=>l.name===o),u=a.getStorageFieldType();i?(i.dataType,u.type):(s.push({name:o,storageFieldType:u}),u.references&&!be(t,u.references)&&r.push({tableName:n,columnName:o,references:u.references}));}return s}function We(c,e){return e==="postgres"&&!!c.enumValues&&c.enumValues.length>0&&!!c.enumName}async function Dt(c,e,t,r,n,s){if(t.length===0)return;let o=c.schema.createTable(e);for(let{name:a,storageFieldType:i}of t)if(We(i,n))o=o.addColumn(a,sql.raw(i.enumName),u=>ge(u,i,r));else {let u=Te(i,n);o=o.addColumn(a,u,l=>ge(l,i,r));}await o.execute().catch(a=>{if(!F(a))throw s==null||s.error("Error creating table",e,a),a});}async function _t(c,e,t,r,n,s,o){for(let{name:a,storageFieldType:i}of t){let u=i.references?be(r,i.references):false,l=We(i,s)?sql.raw(i.enumName):Te(i,s);await c.schema.alterTable(e).addColumn(a,l,d=>ge(d,i,r,!u)).execute().catch(d=>{if(!F(d))throw o==null||o.error("Error adding column",a,d),d}),i.references&&!u&&!n.some(d=>d.tableName===e&&d.columnName===a)&&n.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 Vt(c,e,t,r,n,s){let o=`${e}_meta`,a=[];for(let[i,u]of Object.entries(t.fields)){let l=u.getStorageFieldType();$t(r,i)||a.push({name:i,storageFieldType:l});}if(!r&&a.length>0){let i=c.schema.createTable(o);for(let{name:u,storageFieldType:l}of a)i=i.addColumn(u,"varchar",d=>{let h=d;return l.primary&&(h=h.primaryKey(),U(n,e)&&(h=h.references(`${e}.${u}`))),h});await i.execute().catch(u=>{if(!F(u))throw s==null||s.error("Error creating meta table",o,u),u});}else if(r)for(let{name:i,storageFieldType:u}of a)await c.schema.alterTable(o).addColumn(i,"varchar",l=>{let d=l;return u.primary&&(d=d.primaryKey(),U(n,e)&&(d=d.references(`${e}.${i}`))),d}).execute().catch(l=>{if(!F(l))throw s==null||s.error("Error adding meta column",i,l),l});}async function He(c,e,t,r,n){let[s,o]=r.split("."),a=`${e}_${t}_fk`;try{await sql`
7
+ `.execute(c);}catch(i){r==null||r.warn("Could not create enum type",o,i);}}}function U(c,e){return c.some(t=>t.name===e)}function kt(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function be(c,e){let[t]=e.split(".");return U(c,t)}function Te(c,e,t,r=false){let n=c;return e.unique&&(n=n.unique()),e.nullable||(n=n.notNull()),e.primary&&(n=n.primaryKey()),e.default!==void 0&&(n=n.defaultTo(e.default)),!r&&e.references&&be(t,e.references)&&(n=n.references(e.references)),n}function Dt(c,e,t,r,n){let s=[];for(let[o,a]of Object.entries(c.fields)){let i=e==null?void 0:e.columns.find(l=>l.name===o),u=a.getStorageFieldType();i?(i.dataType,u.type):(s.push({name:o,storageFieldType:u}),u.references&&!be(t,u.references)&&r.push({tableName:n,columnName:o,references:u.references}));}return s}function He(c,e){return e==="postgres"&&!!c.enumValues&&c.enumValues.length>0&&!!c.enumName}async function _t(c,e,t,r,n,s){if(t.length===0)return;let o=c.schema.createTable(e);for(let{name:a,storageFieldType:i}of t)if(He(i,n))o=o.addColumn(a,sql.raw(i.enumName),u=>Te(u,i,r));else {let u=Se(i,n);o=o.addColumn(a,u,l=>Te(l,i,r));}await o.execute().catch(a=>{if(!F(a))throw s==null||s.error("Error creating table",e,a),a});}async function Vt(c,e,t,r,n,s,o){for(let{name:a,storageFieldType:i}of t){let u=i.references?be(r,i.references):false,l=He(i,s)?sql.raw(i.enumName):Se(i,s);await c.schema.alterTable(e).addColumn(a,l,d=>Te(d,i,r,!u)).execute().catch(d=>{if(!F(d))throw o==null||o.error("Error adding column",a,d),d}),i.references&&!u&&!n.some(d=>d.tableName===e&&d.columnName===a)&&n.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 Bt(c,e,t,r,n,s){let o=`${e}_meta`,a=[];for(let[i,u]of Object.entries(t.fields)){let l=u.getStorageFieldType();kt(r,i)||a.push({name:i,storageFieldType:l});}if(!r&&a.length>0){let i=c.schema.createTable(o);for(let{name:u,storageFieldType:l}of a)i=i.addColumn(u,"varchar",d=>{let h=d;return l.primary&&(h=h.primaryKey(),U(n,e)&&(h=h.references(`${e}.${u}`))),h});await i.execute().catch(u=>{if(!F(u))throw s==null||s.error("Error creating meta table",o,u),u});}else if(r)for(let{name:i,storageFieldType:u}of a)await c.schema.alterTable(o).addColumn(i,"varchar",l=>{let d=l;return u.primary&&(d=d.primaryKey(),U(n,e)&&(d=d.references(`${e}.${i}`))),d}).execute().catch(l=>{if(!F(l))throw s==null||s.error("Error adding meta column",i,l),l});}async function Ke(c,e,t,r,n){let[s,o]=r.split("."),a=`${e}_${t}_fk`;try{await sql`
8
8
  ALTER TABLE ${sql.id(e)}
9
9
  ADD CONSTRAINT ${sql.id(a)}
10
10
  FOREIGN KEY (${sql.id(t)})
11
11
  REFERENCES ${sql.id(s)} (${sql.id(o)})
12
- `.execute(c);}catch(i){F(i)||n==null||n.warn("Could not add foreign key constraint",e,t,r,i);}}async function Bt(c,e,t,r){for(let{tableName:n,columnName:s,references:o}of e){let a=t.find(l=>l.name===n),i=a==null?void 0:a.columns.find(l=>l.name===s),[u]=o.split(".");a&&i&&U(t,u)&&await He(c,n,s,o,r);}}async function zt(c,e,t,r){for(let[n,s]of Object.entries(e)){let o=`${n}_meta`,a=t.find(i=>i.name===o);if(a)for(let[i,u]of Object.entries(s.fields)){let l=u.getStorageFieldType(),d=a.columns.find(h=>h.name===i);l.primary&&d&&U(t,n)&&await He(c,o,i,`${n}.${i}`,r);}}}async function Ke(c,e,t){let r=C(c),n=await c.introspection.getTables(),s=[];await qt(c,e,r,t);for(let[a,i]of Object.entries(e)){let u=n.find(h=>h.name===a),l=n.find(h=>h.name===`${a}_meta`),d=kt(i,u,n,s,a);if(u)for(let[h,y]of Object.entries(i.fields)){let m=u.columns.find(T=>T.name===h),p=y.getStorageFieldType(),f=Te(p,r);m&&m.dataType!==f&&(t==null||t.warn("Column type mismatch:",h,"expected to have type:",f,"but has type:",m.dataType));}!u&&d.length>0?await Dt(c,a,d,n,r,t):u&&await _t(c,a,d,n,s,r,t),await Vt(c,a,i,l,n,t);}let o=await c.introspection.getTables();await Bt(c,s,o,t),await zt(c,e,o,t);}function ee(c,e,t,r){if(!c)throw new Error("Schema not initialized");let n=c[e];if(!n)throw new Error("Resource not found");let s=r.$or,o=r.$and;return (s?t.or:t.and)(s?r.$or.map(a=>ee(c,e,t,a)):o?r.$and.map(a=>ee(c,e,t,a)):Object.entries(r).map(([a,i])=>{var u,l;if(n.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?((u=i==null?void 0:i.$not)==null?void 0:u.$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(n.relations[a]){let d=n.relations[a],h=d.entity.name;return d.type==="many"?t.exists(re(c,h,t.selectFrom(h).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),i)):ee(c,h,t,i)}return null}).filter(Boolean))}function te(c,e,t,r){let n=c[e];if(!n)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let s of r.$and)t=te(c,e,t,s);return t}else if(r.$or){for(let s of r.$or)t=te(c,e,t,s);return t}for(let[s,o]of Object.entries(r)){if(!n.relations[s])continue;let a=n.relations[s],i=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,l=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(i,`${i}.${u}`,`${e}.${l}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=te(c,i,t,o));}return t}function re(c,e,t,r){return !r||Object.keys(r).length===0?t:(t=te(c,e,t,r),t.where(n=>ee(c,e,n,r)))}function Ft(c,e,t,r,n){let s=C(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function Ut(c,e,t,r,n){let s=C(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function Wt(c){if(typeof c!="object"||c===null)return false;let e=c;return "where"in e||"limit"in e||"orderBy"in e||"include"in e}function ne(c,e,t,r,n,s){if(!r)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}=n;for(let u of Object.keys(r)){if(!o.relations[u])throw new Error(`Relation ${u} not found in resource ${e}`);let l=o.relations[u],d=l.entity.name,h=r[u],y=l.type==="one"?"id":l.foreignColumn,m=l.type==="one"?l.relationalColumn:"id",p=l.type==="one"?a:i,f=Wt(h)?h:null,T=f==null?void 0:f.include;t=t.select(g=>{let b=`${d}_meta`,S=Ut(g,c,d,d,s).whereRef(`${d}.${y}`,"=",`${e}.${m}`).select(R=>a(Ft(R,c,d,b,s).whereRef(`${b}.id`,"=",`${d}.id`)).as("_meta"));if(f!=null&&f.where&&(S=re(c,d,S,f.where)),f!=null&&f.orderBy)for(let R of f.orderBy)S=S.orderBy(`${d}.${R.key}`,R.direction);return (f==null?void 0:f.limit)!==void 0&&(S=S.limit(f.limit)),T&&Object.keys(T).length>0&&(S=ne(c,d,S,T,n,s)),p(S).as(u)});}return t}var Se=class c extends z{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,r,n){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.dialectHelpers=Ue(this.db),this.schema=t,this.logger=r,this.server=n,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,r){this.schema=e,this.logger=t,this.server=r,await Ke(this.db,e,t);}selectMetaColumns(e,t,r){var o;let n=C(this.db),s=(o=this.schema)==null?void 0:o[t];if(n==="sqlite"&&(s!=null&&s.fields)){let a=Object.keys(s.fields),i=e.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return e.selectFrom(r).selectAll(r)}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=`${e}_meta`,s=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(i=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(i,e,n).whereRef(`${n}.id`,"=",`${e}.id`)).as("_meta"));s=ne(this.schema,e,s,r,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,r){let n=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(n)return z$2(n)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:n,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=re(this.schema,t,i,r),i=ne(this.schema,t,i,n,this.dialectHelpers,this.db),s!==void 0&&(i=i.limit(s)),o!==void 0&&o.forEach(l=>{i=i.orderBy(l.key,l.direction);});let u=await i.execute();return u.length===0?[]:u.map(l=>{let d=this.parseRelationalJsonStrings(l,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(n=>z$2(n))}async rawInsert(e,t,r,n,s){var p,f,T,g,b,S,R;let o=(f=(p=this.server)==null?void 0:p.router)==null?void 0:f.getHooks(e),a=(T=this.schema)==null?void 0:T[e],[i,u]=((g=a==null?void 0:a.mergeMutation)==null?void 0:g.call(a,"set",r.value,void 0))??[r,r.value];if(!u)return {data:r,acceptedValues:null};let l=i,d={...l,value:{...l.value,id:{value:t}}};if(o!=null&&o.beforeInsert){let M=z$2(d);M.id=t;let v=await o.beforeInsert({ctx:s,value:M,rawValue:d,db:this});v&&(l=v);}let h={},y={};for(let[M,v]of Object.entries(l.value)){let O=(b=v._meta)==null?void 0:b.timestamp;if(!O)continue;let j=(R=(S=a==null?void 0:a.fields[M])==null?void 0:S.getStorageFieldType)==null?void 0:R.call(S);(j==null?void 0:j.type)==="jsonb"||(j==null?void 0:j.type)==="json"?h[M]=JSON.stringify(v.value):h[M]=v.value,y[M]=O;}await this.db.insertInto(e).values({...h,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute();let m=this.buildMutation(e,t,"INSERT",l,n);if(m&&this.trackMutation(m,l),o!=null&&o.afterInsert){let M={...l,value:{...l.value,id:{value:t}}},v=z$2(M);v.id=t,await o.afterInsert({ctx:s,value:v,rawValue:M,db:this});}return {data:l,acceptedValues:u}}async rawUpdate(e,t,r,n,s){var f,T,g,b,S,R,M;let o=(T=(f=this.server)==null?void 0:f.router)==null?void 0:T.getHooks(e),a=(g=this.schema)==null?void 0:g[e],i=await this.rawFindById(e,t),[u,l]=((b=a==null?void 0:a.mergeMutation)==null?void 0:b.call(a,"set",r.value,i))??[r,r.value];if(!l)return {data:r,acceptedValues:null};let d=u,h={...d,value:{...d.value,id:{value:t}}};if(o!=null&&o.beforeUpdate){let v=z$2(h);v.id=t;let O;if(i){let A={...i,value:{...i.value,id:{value:t}}};O=z$2(A),O.id=t;}let j=await o.beforeUpdate({ctx:s,value:v,rawValue:h,previousValue:O,previousRawValue:i,db:this});j&&(d=j);}let y={},m={};for(let[v,O]of Object.entries(d.value)){let j=(S=O._meta)==null?void 0:S.timestamp;if(!j)continue;let A=(M=(R=a==null?void 0:a.fields[v])==null?void 0:R.getStorageFieldType)==null?void 0:M.call(R);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?y[v]=JSON.stringify(O.value):y[v]=O.value,m[v]=j;}if(Object.keys(y).length===0)return {data:d,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...m,id:t}).onConflict(v=>v.column("id").doUpdateSet(m)).execute()]);let p=this.buildMutation(e,t,"UPDATE",d,n);if(p){let v=await this.rawFindById(e,t);v&&this.trackMutation(p,v);}if(o!=null&&o.afterUpdate){let v=await this.rawFindById(e,t);if(v){let O={...v,value:{...v.value,id:{value:t}}},j=z$2(O);j.id=t;let A;if(i){let Ge={...i,value:{...i.value,id:{value:t}}};A=z$2(Ge),A.id=t;}await o.afterUpdate({ctx:s,value:j,rawValue:O,previousValue:A,previousRawValue:i,db:this});}}return {data:d,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(),u=false,l=false;try{return await e({trx:this,commit:async()=>{await i.releaseSavepoint(s).execute(),u=!0,o.push(...a);},rollback:async()=>{await i.rollbackToSavepoint(s).execute(),l=!0,a.length=0;}}).then(d=>i.isCommitted||i.isRolledBack||u||l?d:i.releaseSavepoint(s).execute().then(()=>(o.push(...a),d)))}catch(d){throw l||await i.rollbackToSavepoint(s).execute().catch(()=>{}),a.length=0,d}finally{this.mutationStack=o;}}let t=[],r=this.mutationStack;this.mutationStack=t;let n=await this.db.startTransaction().execute();try{let s=new c(n,this.schema,this.logger,this.server);return s.mutationStack=t,await e({trx:s,commit:async()=>{await n.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await n.rollback().execute(),t.length=0;}}).then(o=>n.isCommitted||n.isRolledBack?o:n.commit().execute().then(()=>(this.notifyMutations(t),o)))}catch(s){throw await n.rollback().execute(),t.length=0,s}finally{this.mutationStack=r;}}get internalDB(){return this.db}isRelationalField(e,t){var n;if(!this.schema)return false;let r=this.schema[e];return !!((n=r==null?void 0:r.relations)!=null&&n[t])}parseRelationalJsonStrings(e,t){var s,o;if(C(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 n={};for(let[a,i]of Object.entries(e))if(a==="_meta"&&typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{n[a]=JSON.parse(i);}catch{n[a]=i;}else n[a]=i;else if(this.isRelationalField(t,a))if(typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let u=JSON.parse(i);if(this.schema){let l=this.schema[t],d=(s=l==null?void 0:l.relations)==null?void 0:s[a];if(d){let h=d.entity.name;n[a]=this.parseRelationalJsonStrings(u,h);}else n[a]=u;}else n[a]=u;}catch{n[a]=i;}else n[a]=i;else if(typeof i=="object"&&i!==null&&!Array.isArray(i))if(this.schema){let u=this.schema[t],l=(o=u==null?void 0:u.relations)==null?void 0:o[a];if(l){let d=l.entity.name;n[a]=this.parseRelationalJsonStrings(i,d);}else n[a]=i;}else n[a]=i;else Array.isArray(i)?n[a]=i.map(u=>{var l,d;if(typeof u=="string")try{let h=JSON.parse(u);if(this.schema){let y=this.schema[t],m=(l=y==null?void 0:y.relations)==null?void 0:l[a];if(m){let p=m.entity.name;return this.parseRelationalJsonStrings(h,p)}}return h}catch{return u}if(typeof u=="object"&&u!==null&&this.schema){let h=this.schema[t],y=(d=h==null?void 0:h.relations)==null?void 0:d[a];if(y){let m=y.entity.name;return this.parseRelationalJsonStrings(u,m)}}return u}):n[a]=i;else n[a]=i;return n}convertToMaterializedLiveType(e,t){var n;let r=(n=this.schema)==null?void 0:n[t];return {value:Object.entries(e).reduce((s,[o,a])=>{var d,h,y,m,p,f,T,g,b;if(o==="_meta")return s;let i=(h=(d=r==null?void 0:r.fields[o])==null?void 0:d.getStorageFieldType)==null?void 0:h.call(d),u=(i==null?void 0:i.type)==="jsonb"||(i==null?void 0:i.type)==="json",l=(r==null?void 0:r.relations)&&o in r.relations;if(o==="id")s[o]={value:a};else if(u)s[o]={value:a,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[o]}};else if(l){let S=r.relations[o].entity,R=(S==null?void 0:S.name)??t;Array.isArray(a)?s[o]={value:a.map(M=>this.convertToMaterializedLiveType(M,R)),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[o],relation:true}}:a!==null&&typeof a=="object"?s[o]={...this.convertToMaterializedLiveType(a,R),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[o],relation:true}}:s[o]={value:a,_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[o],relation:true}};}else Array.isArray(a)?s[o]={value:a,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[o]}}:typeof a=="object"&&a!==null&&!(a instanceof Date)?s[o]={value:a,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[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,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",s=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||s&&o}buildMutation(e,t,r,n,s){var a;let o={};for(let[i,u]of Object.entries(n.value)){if(i==="id")continue;let l=(a=u._meta)==null?void 0:a.timestamp;l&&(o[i]={value:u.value,_meta:{timestamp:l}});}return Object.keys(o).length===0?null:{id:s??K(),type:"MUTATE",resource:e,resourceId:t,procedure:r,payload:o}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let r=e;for(let n of r)this.server.notifySubscribers(n,t);}else {let r=e;for(let{mutation:n,entityData:s}of r)this.server.notifySubscribers(n,s);}}};var Re=class c{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=F$1({level:e.logLevel??E.INFO}),(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new G({router:{get:async(r,n)=>{var d;let{headers:s,cookies:o,queryParams:a,context:i}=(n==null?void 0:n.context)??{};if(!(n!=null&&n.batcher))throw new Error("Batcher is required");let u={...r,type:"QUERY",headers:s,cookies:o,queryParams:a,context:i},l=await((d=this.router.routes[r.resource])==null?void 0:d.handleQuery({req:u,batcher:n.batcher}));return (l==null?void 0:l.data)??[]},incrementQueryStep:(r,n={})=>{var a;let s=(a=this.router.routes[r.query.resource])==null?void 0:a.getAuthorizationClause({...r.query,type:"QUERY",headers:n.headers,cookies:n.cookies,queryParams:n.queryParams,context:n.context});if(typeof s=="boolean"&&!s)throw new Error("Not authorized");let o=D(r.query.where,typeof s=="object"?s:void 0);return {...r,query:{...r.query,where:o}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:r,cookies:n,queryParams:s,context:o,...a}=t,i={headers:r,cookies:n,queryParams:s,context:o},u=e.subscription?this.queryEngine.subscribe(a,d=>{var h;(h=e.subscription)==null||h.call(e,d);},i):void 0;return {data:await this.queryEngine.get(a,{context:i}),unsubscribe:u}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){let t=await this.wrapInMiddlewares(async h=>{let y=this.router.routes[h.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:h,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:n,cookies:s,queryParams:o,context:a}=e.req,i={headers:n,cookies:s,queryParams:o,context:a},u=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(u,h=>{var y;(y=e.subscription)==null||y.call(e,h);},i):void 0,d=await this.queryEngine.get(u,{context:i});return e.subscription?{data:d,unsubscribe:l,query:u}:d.map(h=>z$2(h))}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((r,n)=>s=>n({req:s,next:r}),e)(t)}},Sn=Re.create;export{me as ProcedureRoute,pe as Route,fe as RouteFactory,he as Router,Se as SQLStorage,Re as Server,z as Storage,$ as createServerDB,Lr as expressAdapter,Fr as routeFactory,zr as router,Sn as server};
12
+ `.execute(c);}catch(i){F(i)||n==null||n.warn("Could not add foreign key constraint",e,t,r,i);}}async function zt(c,e,t,r){for(let{tableName:n,columnName:s,references:o}of e){let a=t.find(l=>l.name===n),i=a==null?void 0:a.columns.find(l=>l.name===s),[u]=o.split(".");a&&i&&U(t,u)&&await Ke(c,n,s,o,r);}}async function Ft(c,e,t,r){for(let[n,s]of Object.entries(e)){let o=`${n}_meta`,a=t.find(i=>i.name===o);if(a)for(let[i,u]of Object.entries(s.fields)){let l=u.getStorageFieldType(),d=a.columns.find(h=>h.name===i);l.primary&&d&&U(t,n)&&await Ke(c,o,i,`${n}.${i}`,r);}}}async function Je(c,e,t){let r=C(c),n=await c.introspection.getTables(),s=[];await $t(c,e,r,t);for(let[a,i]of Object.entries(e)){let u=n.find(h=>h.name===a),l=n.find(h=>h.name===`${a}_meta`),d=Dt(i,u,n,s,a);if(u)for(let[h,y]of Object.entries(i.fields)){let m=u.columns.find(T=>T.name===h),p=y.getStorageFieldType(),f=Se(p,r);m&&m.dataType!==f&&(t==null||t.warn("Column type mismatch:",h,"expected to have type:",f,"but has type:",m.dataType));}!u&&d.length>0?await _t(c,a,d,n,r,t):u&&await Vt(c,a,d,n,s,r,t),await Bt(c,a,i,l,n,t);}let o=await c.introspection.getTables();await zt(c,s,o,t),await Ft(c,e,o,t);}function te(c,e,t,r){if(!c)throw new Error("Schema not initialized");let n=c[e];if(!n)throw new Error("Resource not found");let s=r.$or,o=r.$and;return (s?t.or:t.and)(s?r.$or.map(a=>te(c,e,t,a)):o?r.$and.map(a=>te(c,e,t,a)):Object.entries(r).map(([a,i])=>{var u,l;if(n.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?((u=i==null?void 0:i.$not)==null?void 0:u.$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(n.relations[a]){let d=n.relations[a],h=d.entity.name;return d.type==="many"?t.exists(ne(c,h,t.selectFrom(h).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),i)):te(c,h,t,i)}return null}).filter(Boolean))}function re(c,e,t,r){let n=c[e];if(!n)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let s of r.$and)t=re(c,e,t,s);return t}else if(r.$or){for(let s of r.$or)t=re(c,e,t,s);return t}for(let[s,o]of Object.entries(r)){if(!n.relations[s])continue;let a=n.relations[s],i=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,l=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(i,`${i}.${u}`,`${e}.${l}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=re(c,i,t,o));}return t}function ne(c,e,t,r){return !r||Object.keys(r).length===0?t:(t=re(c,e,t,r),t.where(n=>te(c,e,n,r)))}function Ut(c,e,t,r,n){let s=C(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function Wt(c,e,t,r,n){let s=C(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function ie(c,e,t,r,n,s){if(!r)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}=n;for(let u of Object.keys(r)){if(!o.relations[u])throw new Error(`Relation ${u} not found in resource ${e}`);let l=o.relations[u],d=l.entity.name,h=r[u],y=l.type==="one"?"id":l.foreignColumn,m=l.type==="one"?l.relationalColumn:"id",p=l.type==="one"?a:i,f=E(h)?h:null,T=f==null?void 0:f.include;t=t.select(g=>{let S=`${d}_meta`,b=Wt(g,c,d,d,s).whereRef(`${d}.${y}`,"=",`${e}.${m}`).select(R=>a(Ut(R,c,d,S,s).whereRef(`${S}.id`,"=",`${d}.id`)).as("_meta"));if(f!=null&&f.where&&(b=ne(c,d,b,f.where)),f!=null&&f.orderBy)for(let R of f.orderBy)b=b.orderBy(`${d}.${R.key}`,R.direction);return (f==null?void 0:f.limit)!==void 0&&(b=b.limit(f.limit)),T&&Object.keys(T).length>0&&(b=ie(c,d,b,T,n,s)),p(b).as(u)});}return t}var Re=class c extends z{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,r,n){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.dialectHelpers=We(this.db),this.schema=t,this.logger=r,this.server=n,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,r){this.schema=e,this.logger=t,this.server=r,await Je(this.db,e,t);}selectMetaColumns(e,t,r){var o;let n=C(this.db),s=(o=this.schema)==null?void 0:o[t];if(n==="sqlite"&&(s!=null&&s.fields)){let a=Object.keys(s.fields),i=e.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return e.selectFrom(r).selectAll(r)}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=`${e}_meta`,s=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(i=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(i,e,n).whereRef(`${n}.id`,"=",`${e}.id`)).as("_meta"));s=ie(this.schema,e,s,r,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,r){let n=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(n)return z$2(n)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:n,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=ne(this.schema,t,i,r),i=ie(this.schema,t,i,n,this.dialectHelpers,this.db),s!==void 0&&(i=i.limit(s)),o!==void 0&&o.forEach(l=>{i=i.orderBy(l.key,l.direction);});let u=await i.execute();return u.length===0?[]:u.map(l=>{let d=this.parseRelationalJsonStrings(l,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(n=>z$2(n))}async rawInsert(e,t,r,n,s){var p,f,T,g,S,b,R;let o=(f=(p=this.server)==null?void 0:p.router)==null?void 0:f.getHooks(e),a=(T=this.schema)==null?void 0:T[e],[i,u]=((g=a==null?void 0:a.mergeMutation)==null?void 0:g.call(a,"set",r.value,void 0))??[r,r.value];if(!u)return {data:r,acceptedValues:null};let l=i,d={...l,value:{...l.value,id:{value:t}}};if(o!=null&&o.beforeInsert){let w=z$2(d);w.id=t;let x=await o.beforeInsert({ctx:s,value:w,rawValue:d,db:this});x&&(l=x);}let h={},y={};for(let[w,x]of Object.entries(l.value)){let O=(S=x._meta)==null?void 0:S.timestamp;if(!O)continue;let j=(R=(b=a==null?void 0:a.fields[w])==null?void 0:b.getStorageFieldType)==null?void 0:R.call(b);(j==null?void 0:j.type)==="jsonb"||(j==null?void 0:j.type)==="json"?h[w]=JSON.stringify(x.value):h[w]=x.value,y[w]=O;}await this.db.insertInto(e).values({...h,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute();let m=this.buildMutation(e,t,"INSERT",l,n);if(m&&this.trackMutation(m,l),o!=null&&o.afterInsert){let w={...l,value:{...l.value,id:{value:t}}},x=z$2(w);x.id=t,await o.afterInsert({ctx:s,value:x,rawValue:w,db:this});}return {data:l,acceptedValues:u}}async rawUpdate(e,t,r,n,s){var f,T,g,S,b,R,w;let o=(T=(f=this.server)==null?void 0:f.router)==null?void 0:T.getHooks(e),a=(g=this.schema)==null?void 0:g[e],i=await this.rawFindById(e,t),[u,l]=((S=a==null?void 0:a.mergeMutation)==null?void 0:S.call(a,"set",r.value,i))??[r,r.value];if(!l)return {data:r,acceptedValues:null};let d=u,h={...d,value:{...d.value,id:{value:t}}};if(o!=null&&o.beforeUpdate){let x=z$2(h);x.id=t;let O;if(i){let A={...i,value:{...i.value,id:{value:t}}};O=z$2(A),O.id=t;}let j=await o.beforeUpdate({ctx:s,value:x,rawValue:h,previousValue:O,previousRawValue:i,db:this});j&&(d=j);}let y={},m={};for(let[x,O]of Object.entries(d.value)){let j=(b=O._meta)==null?void 0:b.timestamp;if(!j)continue;let A=(w=(R=a==null?void 0:a.fields[x])==null?void 0:R.getStorageFieldType)==null?void 0:w.call(R);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?y[x]=JSON.stringify(O.value):y[x]=O.value,m[x]=j;}if(Object.keys(y).length===0)return {data:d,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...m,id:t}).onConflict(x=>x.column("id").doUpdateSet(m)).execute()]);let p=this.buildMutation(e,t,"UPDATE",d,n);if(p){let x=await this.rawFindById(e,t);x&&this.trackMutation(p,x);}if(o!=null&&o.afterUpdate){let x=await this.rawFindById(e,t);if(x){let O={...x,value:{...x.value,id:{value:t}}},j=z$2(O);j.id=t;let A;if(i){let Ze={...i,value:{...i.value,id:{value:t}}};A=z$2(Ze),A.id=t;}await o.afterUpdate({ctx:s,value:j,rawValue:O,previousValue:A,previousRawValue:i,db:this});}}return {data:d,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(),u=false,l=false;try{return await e({trx:this,commit:async()=>{await i.releaseSavepoint(s).execute(),u=!0,o.push(...a);},rollback:async()=>{await i.rollbackToSavepoint(s).execute(),l=!0,a.length=0;}}).then(d=>i.isCommitted||i.isRolledBack||u||l?d:i.releaseSavepoint(s).execute().then(()=>(o.push(...a),d)))}catch(d){throw l||await i.rollbackToSavepoint(s).execute().catch(()=>{}),a.length=0,d}finally{this.mutationStack=o;}}let t=[],r=this.mutationStack;this.mutationStack=t;let n=await this.db.startTransaction().execute();try{let s=new c(n,this.schema,this.logger,this.server);return s.mutationStack=t,await e({trx:s,commit:async()=>{await n.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await n.rollback().execute(),t.length=0;}}).then(o=>n.isCommitted||n.isRolledBack?o:n.commit().execute().then(()=>(this.notifyMutations(t),o)))}catch(s){throw await n.rollback().execute(),t.length=0,s}finally{this.mutationStack=r;}}get internalDB(){return this.db}isRelationalField(e,t){var n;if(!this.schema)return false;let r=this.schema[e];return !!((n=r==null?void 0:r.relations)!=null&&n[t])}parseRelationalJsonStrings(e,t){var s,o;if(C(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 n={};for(let[a,i]of Object.entries(e))if(a==="_meta"&&typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{n[a]=JSON.parse(i);}catch{n[a]=i;}else n[a]=i;else if(this.isRelationalField(t,a))if(typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let u=JSON.parse(i);if(this.schema){let l=this.schema[t],d=(s=l==null?void 0:l.relations)==null?void 0:s[a];if(d){let h=d.entity.name;n[a]=this.parseRelationalJsonStrings(u,h);}else n[a]=u;}else n[a]=u;}catch{n[a]=i;}else n[a]=i;else if(typeof i=="object"&&i!==null&&!Array.isArray(i))if(this.schema){let u=this.schema[t],l=(o=u==null?void 0:u.relations)==null?void 0:o[a];if(l){let d=l.entity.name;n[a]=this.parseRelationalJsonStrings(i,d);}else n[a]=i;}else n[a]=i;else Array.isArray(i)?n[a]=i.map(u=>{var l,d;if(typeof u=="string")try{let h=JSON.parse(u);if(this.schema){let y=this.schema[t],m=(l=y==null?void 0:y.relations)==null?void 0:l[a];if(m){let p=m.entity.name;return this.parseRelationalJsonStrings(h,p)}}return h}catch{return u}if(typeof u=="object"&&u!==null&&this.schema){let h=this.schema[t],y=(d=h==null?void 0:h.relations)==null?void 0:d[a];if(y){let m=y.entity.name;return this.parseRelationalJsonStrings(u,m)}}return u}):n[a]=i;else n[a]=i;return n}convertToMaterializedLiveType(e,t){var n;let r=(n=this.schema)==null?void 0:n[t];return {value:Object.entries(e).reduce((s,[o,a])=>{var d,h,y,m,p,f,T,g,S;if(o==="_meta")return s;let i=(h=(d=r==null?void 0:r.fields[o])==null?void 0:d.getStorageFieldType)==null?void 0:h.call(d),u=(i==null?void 0:i.type)==="jsonb"||(i==null?void 0:i.type)==="json",l=(r==null?void 0:r.relations)&&o in r.relations;if(o==="id")s[o]={value:a};else if(u)s[o]={value:a,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[o]}};else if(l){let b=r.relations[o].entity,R=(b==null?void 0:b.name)??t;Array.isArray(a)?s[o]={value:a.map(w=>this.convertToMaterializedLiveType(w,R)),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[o],relation:true}}:a!==null&&typeof a=="object"?s[o]={...this.convertToMaterializedLiveType(a,R),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[o],relation:true}}:s[o]={value:a,_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[o],relation:true}};}else Array.isArray(a)?s[o]={value:a,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[o]}}:typeof a=="object"&&a!==null&&!(a instanceof Date)?s[o]={value:a,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[o]}}:s[o]={value:a,_meta:{timestamp:(S=e==null?void 0:e._meta)==null?void 0:S[o]}};return s},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",s=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||s&&o}buildMutation(e,t,r,n,s){var a;let o={};for(let[i,u]of Object.entries(n.value)){if(i==="id")continue;let l=(a=u._meta)==null?void 0:a.timestamp;l&&(o[i]={value:u.value,_meta:{timestamp:l}});}return Object.keys(o).length===0?null:{id:s??J(),type:"MUTATE",resource:e,resourceId:t,procedure:r,payload:o}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let r=e;for(let n of r)this.server.notifySubscribers(n,t);}else {let r=e;for(let{mutation:n,entityData:s}of r)this.server.notifySubscribers(n,s);}}};var we=class c{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=G$1({level:e.logLevel??F$1.INFO}),(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new Z({router:{get:async(r,n)=>{var d;let{headers:s,cookies:o,queryParams:a,context:i}=(n==null?void 0:n.context)??{};if(!(n!=null&&n.batcher))throw new Error("Batcher is required");let u={...r,type:"QUERY",headers:s,cookies:o,queryParams:a,context:i},l=await((d=this.router.routes[r.resource])==null?void 0:d.handleQuery({req:u,batcher:n.batcher}));return (l==null?void 0:l.data)??[]},incrementQueryStep:(r,n={})=>{var a;let s=(a=this.router.routes[r.query.resource])==null?void 0:a.getAuthorizationClause({...r.query,type:"QUERY",headers:n.headers,cookies:n.cookies,queryParams:n.queryParams,context:n.context});if(typeof s=="boolean"&&!s)throw new Error("Not authorized");let o=D(r.query.where,typeof s=="object"?s:void 0);return {...r,query:{...r.query,where:o}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:r,cookies:n,queryParams:s,context:o,...a}=t,i={headers:r,cookies:n,queryParams:s,context:o},u=e.subscription?this.queryEngine.subscribe(a,d=>{var h;(h=e.subscription)==null||h.call(e,d);},i):void 0;return {data:await this.queryEngine.get(a,{context:i}),unsubscribe:u}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){let t=await this.wrapInMiddlewares(async h=>{let y=this.router.routes[h.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:h,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:n,cookies:s,queryParams:o,context:a}=e.req,i={headers:n,cookies:s,queryParams:o,context:a},u=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(u,h=>{var y;(y=e.subscription)==null||y.call(e,h);},i):void 0,d=await this.queryEngine.get(u,{context:i});return e.subscription?{data:d,unsubscribe:l,query:u}:d.map(h=>z$2(h))}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((r,n)=>s=>n({req:s,next:r}),e)(t)}},Rn=we.create;export{fe as ProcedureRoute,me as Route,ge as RouteFactory,pe as Router,Re as SQLStorage,we as Server,z as Storage,$ as createServerDB,Lr as expressAdapter,Fr as routeFactory,zr as router,Rn as server};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@live-state/sync",
3
- "version": "0.0.7-canary-2",
3
+ "version": "0.0.7-canary-3",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"