@live-state/sync 0.0.7 → 1.0.0-canary-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-YPTDCIAN.js +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +1 -1
- package/dist/fetch-client.js +1 -1
- package/dist/{index-C0Qm5yHg.d.ts → index-DjBla1td.d.ts} +75 -75
- package/dist/optimistic-client.d.ts +1 -1
- package/dist/server.cjs +6 -6
- package/dist/server.d.cts +183 -240
- package/dist/server.d.ts +183 -240
- package/dist/server.js +6 -6
- package/package.json +1 -1
- package/dist/chunk-LSAVBBUS.js +0 -1
package/dist/server.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
'use strict';var ce=require('crypto'),jsXxhash=require('js-xxhash'),un=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 ce__default=/*#__PURE__*/_interopDefault(ce);var un__default=/*#__PURE__*/_interopDefault(un);var xt=Object.create;var Ke=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var It=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Ct=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vt(e))!Mt.call(i,r)&&r!==t&&Ke(i,r,{get:()=>e[r],enumerable:!(n=St(e,r))||n.enumerable});return i};var He=(i,e,t)=>(t=i!=null?xt(wt(i)):{},Ct(Ke(t,"default",{value:i,enumerable:true}),i));var je=It(fe=>{Object.defineProperty(fe,"__esModule",{value:true});fe.parse=tn;fe.serialize=nn;var Jt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Gt=/^[\u0021-\u003A\u003C-\u007E]*$/,Zt=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Yt=/^[\u0020-\u003A\u003D-\u007E]*$/,Xt=Object.prototype.toString,en=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function tn(i,e){let t=new en,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||rn,a=0;do{let u=i.indexOf("=",a);if(u===-1)break;let o=i.indexOf(";",a),s=o===-1?n:o;if(u>s){a=i.lastIndexOf(";",u-1)+1;continue}let c=Xe(i,a,u),l=et(i,u,c),d=i.slice(c,l);if(t[d]===void 0){let y=Xe(i,u+1,s),p=et(i,s,y),f=r(i.slice(y,p));t[d]=f;}a=s+1;}while(a<n);return t}function Xe(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function et(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function nn(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Jt.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Gt.test(r))throw new TypeError(`argument val is invalid: ${e}`);let a=i+"="+r;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!Zt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Yt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!an(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);a+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(a+="; HttpOnly"),t.secure&&(a+="; Secure"),t.partitioned&&(a+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return a}function rn(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function an(i){return Xt.call(i)==="[object Date]"}});var Me=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),w=i=>i?Array.isArray(i.value)?i.value.map(t=>Me(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=>Me(r)?w(r):r)]:Me(n)?[t,w(n)]:[t,n])):void 0;var Je="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Y=32;var qt=16,Ge=10,We=0xffffffffffff;var B;(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";})(B||(B={}));var z=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function $t(i){let e=Math.floor(i()*Y);return e===Y&&(e=Y-1),Je.charAt(e)}function Dt(i){var n;let e=_t(),t=e&&(e.crypto||e.msCrypto)||(typeof ce__default.default<"u"?ce__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=ce__default.default)!=null&&n.randomBytes)return ()=>ce__default.default.randomBytes(1).readUInt8()/255;throw new z(B.PRNGDetectFailure,"Failed to find a reliable PRNG")}function _t(){return zt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ft(i,e){let t="";for(;i>0;i--)t=$t(e)+t;return t}function Bt(i,e=Ge){if(isNaN(i))throw new z(B.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>We)throw new z(B.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${We}: ${i}`);if(i<0)throw new z(B.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new z(B.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%Y,n=Je.charAt(t)+n,i=(i-t)/Y;return n}function zt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ze(i,e){let t=Dt(),n=Date.now();return Bt(n,Ge)+Ft(qt,t)}var de=()=>Ze().toLowerCase(),le=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:le(n)}return le(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:le(r)}throw n}}}),Ie=i=>i instanceof Promise?i:le(i);var J=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var ye=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((a,u)=>{let o=this.getBatchKey({resource:e,commonWhere:t,...r}),s={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:a,reject:u};this.queue.has(o)||this.queue.set(o,[]);let c=this.queue.get(o);c&&c.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var y;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:a,sort:u}=t,o=e.length===1?t.limit:void 0,s=e.map(p=>p.uniqueWhere).filter(p=>p!==void 0),c=r,l=(y=Object.entries(s[0]??{})[0])==null?void 0:y[0];if(s.length>0){let p=s.map(f=>f[l]).filter(f=>f!=null);p.length>0&&(c=J(r,{[l]:{$in:p}}));}let d=await this.storage.get({resource:n,where:c,include:a,sort:u,limit:o});for(let p of e){let f=d;if(p.uniqueWhere){let[m,h]=Object.entries(p.uniqueWhere)[0];f=d.filter(g=>{var T;return ((T=g.value[m])==null?void 0:T.value)===h});}p.resolve(f);}}};var $=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),U=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let a=u=>{u.$and?u.$and.forEach(a):u.$or?u.$or.forEach(a):Object.entries(u).forEach(([o,s])=>{var c;if((c=r.relations)!=null&&c[o]&&(n[o]=true,typeof s=="object"&&s!==null&&!Array.isArray(s))){let l=U(s,r.relations[o].entity.name,t);Object.keys(l).length>0&&(n[o]={include:l});}});};return a(i),n},N=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(u=>N(i,u,t));if(n==="$or")return r.some(u=>N(i,u,t));let a=(r==null?void 0:r.$eq)!==void 0?r==null?void 0:r.$eq:r;if(typeof r=="object"&&r!==null&&(r==null?void 0:r.$eq)===void 0){if(r.$in!==void 0){let o=i[n];return o===void 0?false:t?!r.$in.includes(o):r.$in.includes(o)}if(r.$not!==void 0&&!t)return N(i,{[n]:r.$not},true);if(r.$gt!==void 0){let o=i[n];return typeof o!="number"?false:t?o<=r.$gt:o>r.$gt}if(r.$gte!==void 0){let o=i[n];return typeof o!="number"?false:t?o<r.$gte:o>=r.$gte}if(r.$lt!==void 0){let o=i[n];return typeof o!="number"?false:t?o>=r.$lt:o<r.$lt}if(r.$lte!==void 0){let o=i[n];return typeof o!="number"?false:t?o>r.$lte:o<=r.$lte}let u=i[n];return !u||typeof u!="object"&&!Array.isArray(u)?false:Array.isArray(u)?t?!u.some(o=>N(o,r,false)):u.some(o=>N(o,r,false)):N(u,r,t)}return t?i[n]!==a:i[n]===a}),pe=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},_={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},Ce=class{level;prefix;constructor(e={}){this.level=e.level??_.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=_.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=_.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=_.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=_.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=_.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},Ye=i=>new Ce(i);function Le(i){return $({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}var me=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,a]of Object.entries(n.relations))a.type==="one"&&a.relationalColumn&&t.set(String(a.relationalColumn),{relationName:r,targetResource:a.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 a=this.objectNodes.get(e),u=this.objectNodes.get(t);if(a&&a.referencesObjects.set(n,t),u&&r){let o=u.referencedByObjects.get(r);o||(o=new Set,u.referencedByObjects.set(r,o)),o.add(e);}}removeRelation(e,t,n,r){let a=this.objectNodes.get(e),u=this.objectNodes.get(t);if(a&&a.referencesObjects.delete(n),u&&r){let o=u.referencedByObjects.get(r);o&&(o.delete(e),o.size===0&&u.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let a=r.relations[n];if(!a)return;let u=this.schema[t];if(u!=null&&u.relations){if(a.type==="many"&&a.foreignColumn){for(let[o,s]of Object.entries(u.relations))if(s.entity.name===e&&s.type==="one"&&s.relationalColumn===a.foreignColumn)return o}if(a.type==="one"&&a.relationalColumn){for(let[o,s]of Object.entries(u.relations))if(s.entity.name===e&&s.type==="many"&&s.foreignColumn===a.relationalColumn)return o}}}updateRelationsFromMutation(e,t,n,r){let a=this.getRelationalColumns(e),u=this.objectNodes.get(t);if(u)for(let[o,{relationName:s,targetResource:c}]of Array.from(a)){if(!(r&&o in r))continue;let d=this.getInverseRelationName(e,c,s),y=u.referencesObjects.get(s),p=n[o];y!==p&&(y&&this.removeRelation(t,y,s,d),p&&(this.ensureObjectNode(p,c),this.storeRelation(t,p,s,d)));}}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 ye(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),a={},u=[];for(let o of r){this.logger.debug("[QueryEngine] Subscribing to step",o.stepPath.join("."));let s=Le(o),c=a[o.stepPath.at(-2)??""],l=o.stepPath.at(-1)??"",d=this.queryNodes.get(s);if(d)d.subscriptions.add(t);else if(d={hash:s,queryStep:o,relationName:l,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:c,childQueries:new Set},this.queryNodes.set(d.hash,d),c){let y=this.queryNodes.get(c);y&&y.childQueries.add(d.hash);}a[l]=s,u.push(()=>{let y=this.queryNodes.get(s);y&&(y.subscriptions.delete(t),y.subscriptions.size===0&&this.queryNodes.delete(s));});}return ()=>{for(let o of u)o();}}breakdownQuery(e){var h;let{query:t,stepPath:n=[],context:r={},parentResource:a}=e,{include:u}=t,o=n.length===0,s=n.at(-1),c,l,d;if(!o&&a&&s){let g=this.schema[a],T=(h=g==null?void 0:g.relations)==null?void 0:h[s];T&&(d=T.type==="many",T.type==="one"?(c=b=>({id:b}),l=b=>b.map(R=>{var x,S;return (S=(x=R.value)==null?void 0:x[T.relationalColumn])==null?void 0:S.value}).filter(R=>R!==void 0)):(c=b=>({[T.foreignColumn]:b}),l=b=>b.map(R=>{var x,S;return (S=(x=R.value)==null?void 0:x.id)==null?void 0:S.value}).filter(R=>R!==void 0)));}let{include:y,...p}=t,m=[this.router.incrementQueryStep({query:p,stepPath:[...n],getWhere:c,referenceGetter:l,isMany:d,relationName:s},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,b])=>{let R=g.relations[T];if(!R)throw new Error(`Relation ${T} not found for resource ${t.resource}`);let x=R.entity.name,S=pe(b)?b:null;return this.breakdownQuery({query:{resource:x,include:S?S.include:typeof b=="object"?b:void 0,where:S==null?void 0:S.where,limit:S==null?void 0:S.limit,sort:S==null?void 0:S.orderBy},stepPath:[...n,T],context:r,parentResource:t.resource})}));}return m}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(a=>a.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(a=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",a.length),n[e[0].stepPath.join(".")]=[{data:a}];});for(let a=1;a<e.length;a++){let u=e[a],o=u.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var c,l;let s=n[o];if(!s){n[u.stepPath.join(".")]=[];return}if(u.referenceGetter&&u.getWhere){let d=new Map;for(let f of s)for(let m of f.data){let h=(l=(c=m==null?void 0:m.value)==null?void 0:c.id)==null?void 0:l.value;if(!h)continue;let T=u.referenceGetter([m])[0];if(T){d.has(T)||d.set(T,new Set);let b=d.get(T);b&&b.add(h);}}let y=Array.from(d.keys());if(y.length===0){n[u.stepPath.join(".")]=[];return}let p=[];for(let f of y){let m=u.getWhere(f),h={...u,relationalWhere:m},g=await this.resolveStep(h,t),T=d.get(f);if(T)for(let b of Array.from(T))p.push({includedBy:b,data:g});}this.logger.debug("[QueryEngine] Resolved step",u.stepPath.join("."),"with results count:",p.reduce((f,m)=>f+m.data.length,0)),n[u.stepPath.join(".")]=p;}else {let d=await this.resolveStep(u,t);n[u.stepPath.join(".")]=[{data:d}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var u,o,s,c,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 n=new Map;for(let d of e){let y=d.stepPath.join("."),p=t[y]??[],f=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${y}"`,{resource:d.query.resource,includedRelations:f,resultGroups:p.length,isMany:d.isMany,relationName:d.relationName});for(let m of p){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${y}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let h of m.data){let g=(o=(u=h==null?void 0:h.value)==null?void 0:u.id)==null?void 0:o.value;if(!g){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${y}"`);continue}let T=y?`${y}.${g}`:g,b=[];if(d.stepPath.length>0&&m.includedBy){let x=d.stepPath.slice(0,-1).join(".");b=[x?`${x}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${T}" has parent keys:`,b,{stepPath:y,parentStepPath:x,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${T}" (no parent)`);let R=n.get(T);if(R){this.logger.debug(`[QueryEngine] assembleResults: Entity "${T}" already exists, adding parent keys:`,b);for(let x of b)R.includedBy.add(x);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${T}"`,{resource:d.query.resource,path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,includedRelations:f,parentKeys:b}),n.set(T,{data:h,includedBy:new Set(b),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.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()),a=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let d=r.length-1;d>=0;d--){let[y,p]=r[d],f=this.schema[p.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${y}"`,{resource:p.resourceName,path:p.path,isMany:p.isMany,relationName:p.relationName,includedRelations:p.includedRelations,parentKeys:Array.from(p.includedBy)});for(let m of p.includedRelations){let h=(c=(s=f==null?void 0:f.relations)==null?void 0:s[m])==null?void 0:c.type,g=!!p.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${y}"`,{relationType:h,hasRelation:g,resourceHasRelation:!!((l=f==null?void 0:f.relations)!=null&&l[m])}),p.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${y}"`,p.data.value[m]);else {let T=h==="many"?{value:[]}:{value:null};p.data.value[m]=T,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${y}" with`,T);}}if(p.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${y}" to resultData`),a.unshift(p.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to ${p.includedBy.size} parent(s)`);for(let m of Array.from(p.includedBy)){let h=n.get(m);if(!h){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${y}"`);continue}let g=p.relationName??p.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to parent "${m}" via relation "${g}"`,{isMany:p.isMany,parentHasRelation:!!h.data.value[g]}),p.isMany?(h.data.value[g]??={value:[]},h.data.value[g].value.push(p.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${y}" to many relation "${g}" on parent "${m}"`,{arrayLength:h.data.value[g].value.length})):(h.data.value[g]=p.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${g}" on parent "${m}" to "${y}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${a.length} root items`),a}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,a=n.where&&r?J(n.where,r):r??n.where,u=a?{...n,where:a}:n;return Ie(this.router.get(u,t)).then(o=>(this.loadStepResults(e,o),o))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=Le(e),r=this.queryNodes.get(n),a=e.query.resource;if(!r)return;let u=this.getRelationalColumns(a);for(let o of t){let s=w(o),c=s.id;this.ensureObjectNode(c,a,n),r.trackedObjects.add(c);for(let[l,{relationName:d,targetResource:y}]of Array.from(u)){let p=s[l];if(p){this.ensureObjectNode(p,y);let f=this.getInverseRelationName(a,y,d);this.storeRelation(c,p,d,f);}}this.loadNestedRelations(a,c,s),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[a,u]of Object.entries(r.relations)){let o=n[a];if(!o)continue;let s=u.entity.name,c=this.getInverseRelationName(e,s,a);if(u.type==="one")o&&typeof o=="object"&&o.id&&(this.ensureObjectNode(o.id,s),this.storeRelation(t,o.id,a,c),this.loadNestedRelations(s,o.id,o));else if(u.type==="many"&&Array.isArray(o)){for(let l of o)if(l&&typeof l=="object"&&l.id){this.ensureObjectNode(l.id,s);let d=this.getInverseRelationName(s,e,a);d&&this.storeRelation(l.id,t,d,a),this.loadNestedRelations(s,l.id,l);}}}}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 a=this.queryNodes.get(r);if(!a||!a.relationName)continue;let u=this.buildIncludeFromChildQueries(r);n[a.relationName]=Object.keys(u).length>0?u:true;}return n}sendInsertsForTree(e,t,n){var o,s;let r=(s=(o=t==null?void 0:t.value)==null?void 0:o.id)==null?void 0:s.value;if(!r)return;let a={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let c of Array.from(e.subscriptions))try{c(a);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,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 l=this.queryNodes.get(c);if(!l||!l.relationName)continue;let d=l.relationName,y=l.queryStep.query.resource,p=t.value[d];if(!p)continue;let f=p.value;if(Array.isArray(f))for(let m of f)this.sendInsertsForTree(l,m,y);else f&&typeof f=="object"&&this.sendInsertsForTree(l,f,y);}}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 a=this.getRelationalColumns(e.resource);for(let[o,{relationName:s,targetResource:c}]of Array.from(a)){let l=n[o];if(l){this.ensureObjectNode(l,c);let d=this.getInverseRelationName(e.resource,c,s);this.storeRelation(e.resourceId,l,s,d);}}let u=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(o=>{for(let s of o){let c=this.queryNodes.get(s);if(c){c.trackedObjects.add(e.resourceId),u&&u.matchedQueries.add(s);for(let l of Array.from(c.subscriptions))try{l(e);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:d,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),a=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 o=new Set(u),s=[],c=[],l=[];for(let y of u)a.has(y)?l.push(y):s.push(y);for(let y of Array.from(a))o.has(y)||c.push(y);for(let y of s){let p=this.queryNodes.get(y);p&&p.trackedObjects.add(e.resourceId);}for(let y of c){let p=this.queryNodes.get(y);p&&p.trackedObjects.delete(e.resourceId);}let d=this.objectNodes.get(e.resourceId);if(d){for(let y of s)d.matchedQueries.add(y);for(let y of c)d.matchedQueries.delete(y);}for(let y of [...c,...l]){let p=this.queryNodes.get(y);if(p)for(let f of Array.from(p.subscriptions))try{f(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:p.hash,resource:e.resource,resourceId:e.resourceId,stepPath:p.queryStep.stepPath.join(".")});}}if(s.length>0)for(let y of s){let p=this.queryNodes.get(y);if(!p)continue;let f=this.buildIncludeFromChildQueries(y);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(p,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?Ie([]):Promise.all(n.map(async r=>{let a=r.queryStep.query.where,u=r.queryStep.query.resource,o=e.resourceId,s=this.objectNodes.get(o);if(!s)return {hash:r.hash,matches:false};if(r.relationName){let p=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=p==null?void 0:p.queryStep.query.resource,m=f?this.getInverseRelationName(f,u,r.relationName):void 0,h=m?s.referencesObjects.get(m):void 0;if(!h)return {hash:r.hash,matches:false};let g=this.objectNodes.get(h);return !g||!p||!g.matchedQueries.has(p.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!a)return {hash:r.hash,matches:true};let c=U(a,u,this.schema),l=Object.keys(c).length>0;if(!l&&t!==void 0)return {hash:r.hash,matches:N(t,a)};let d=await this.storage.get({resource:u,where:{id:o},include:l?c:void 0});if(!d||d.length===0)return {hash:r.hash,matches:false};let y=w(d[0]);return y?{hash:r.hash,matches:N(y,a)}:{hash:r.hash,matches:false}})).then(r=>r.filter(a=>a.matches).map(a=>a.hash))}};var vr=i=>i,Kt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],Ht=i=>i.length===1?i[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let a of i){let u=await a({...e,value:n,rawValue:t});u&&(t=u,n=w(t),n.id=e.value.id,r=true);}return r?t:void 0}),Wt=i=>i.length===1?i[0]:(async e=>{for(let t of i)await t(e);}),Ae=i=>{let e=i.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of Kt){let r=e.map(a=>a[n]).filter(a=>a!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=Wt(r):t[n]=Ht(r));}return t},wr=(...i)=>{let e={},t=new Set;for(let n of i)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=i.map(u=>u[n]),a=Ae(r);a&&(e[n]=a);}return e};var at=He(je());var he=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()}),Ee=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()})),sn=Ee.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),tt=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),nt=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),G=tt.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:nt}),X=tt.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:sn,meta:nt});zod.z.union([X,G]);var rt=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var it=he.omit({resource:true}),Te=G.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:G.shape.meta}),Oe=X.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([Oe,Te]);var Pe=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(Pe);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=Pe(n);return e}return i},st=i=>{let e=i.logger;return async t=>{var n,r,a,u,o,s;try{let c=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,l={headers:c,cookies:c.cookie?at.default.parse(c.cookie):{}},d=new URL(t.url),y=d.pathname.split("/"),p=d.searchParams,f=Pe(un__default.default.parse(p.toString())),m=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:l.headers,cookies:l.cookies,queryParams:f}))??{};if(t.method==="GET"){let h=y[y.length-1],{success:g,data:T,error:b}=it.safeParse(f);if(!g)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:b},{status:400});let R=await i.handleQuery({req:{...l,...T,type:"QUERY",resource:h,context:m,queryParams:f}});return !R||!R.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(R.data)}if(t.method==="POST")try{let h=y[y.length-1],g=y[y.length-2];if(g==="query"){if(y.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let A=y[y.length-3],O=t.body?await t.json():{};if(!A||A.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let I=await i.handleCustomQuery({req:{...l,type:"CUSTOM_QUERY",resource:A,procedure:h,input:O.input,context:m,queryParams:f}});return Response.json(I)}let T=g,b=t.body?await t.json():{},R,x=h,S,v;if(h==="insert"||h==="update"){let A=Oe.safeParse(b);if(x=h.toUpperCase(),A.success)R=A.data;else {if(!(typeof b=="object"&&b!==null&&"payload"in b&&"meta"in b))return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:A.error},{status:400});let I=Te.safeParse(b);if(!I.success)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:I.error},{status:400});R=I.data;let j=(a=(r=i.router)==null?void 0:r.routes)==null?void 0:a[T],E=h==="insert"?"insert":"update";if(!!!((u=j==null?void 0:j.customMutations)!=null&&u[E])){let Z=R.payload??{},{id:ve,...Ue}=Z;if(h==="update"&&typeof ve!="string")return Response.json({message:"Invalid mutation: payload.id is required for update",code:"INVALID_REQUEST"},{status:400});S=typeof ve=="string"?ve:void 0;let we=(o=i.schema)==null?void 0:o[T];if(we&&typeof we.encodeMutation=="function"){let bt=((s=R.meta)==null?void 0:s.timestamp)??new Date().toISOString();v=we.encodeMutation("set",Ue,bt);}else v=Ue;}}}else {let{success:A,data:O,error:I}=Te.safeParse(b);if(!A)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:I},{status:400});R=O;}let C=await i.handleMutation({req:{...l,type:"MUTATE",resource:T,input:v??R.payload,context:m,resourceId:S??R.resourceId,procedure:x,queryParams:{},meta:R.meta}});return Response.json(C)}catch(h){return e.error("Error parsing mutation from the client:",h),h instanceof Error&&h.message.includes("Unknown procedure")?Response.json({message:h.message,code:"UNKNOWN_PROCEDURE"},{status:400}):Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(c){return e.error("Unexpected error:",c),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var ct=He(je());var F=zod.z.string(),Ne=zod.z.union([rt,he]),cn=zod.z.object({id:F,type:zod.z.literal("SUBSCRIBE")}).and(Ne),ln=zod.z.object({id:F,type:zod.z.literal("UNSUBSCRIBE")}).and(Ne),dn=zod.z.object({id:F,type:zod.z.literal("QUERY")}).and(Ne),yn=zod.z.object({id:F,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),ot=X.extend({id:F}),pn=G.extend({id:F}),mn=zod.z.union([pn,ot]),ut=zod.z.union([cn,dn,yn,mn,ln]),fn=zod.z.object({id:F,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),hn=zod.z.object({id:F,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([fn,hn,ot]);zod.z.object({resource:zod.z.string(),data:zod.z.array(Ee)});var lt=i=>{let e={},t=i.logger;return (n,r)=>{var d;let a=y=>{n.send(JSON.stringify(y));},u=de(),o=new Map,s={headers:r.headers,cookies:typeof r.headers.cookie=="string"?ct.default.parse(r.headers.cookie):{}},c=un.parse(r.url.split("?")[1]),l=(d=i.contextProvider)==null?void 0:d.call(i,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:c});e[u]=n,t.info("Client connected:",u),n.on("message",async y=>{var p,f,m,h,g;try{t.debug("Message received from the client:",y);let T=ut.parse(JSON.parse(y.toString()));if(T.type==="SUBSCRIBE"||T.type==="QUERY"){let{type:b,id:R,...x}=T,S=b==="SUBSCRIBE";if("procedure"in x){let v=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:x.resource,procedure:x.procedure,input:x.input,context:await l??{},queryParams:c},subscription:S?C=>{var A;!C.resourceId||!C.payload||!Object.keys(C.payload).length||(A=e[u])==null||A.send(JSON.stringify(C));}:void 0});if(S){if(!v||!v.data||!v.query)throw new Error("Invalid resource");v.unsubscribe&&o.set($(x),v.unsubscribe),a({id:R,type:"REPLY",data:{resource:v.query.resource,data:(v.data??[]).map(C=>C.value)}});}else a({id:R,type:"REPLY",data:v});}else {let v=await i.handleQuery({req:{...s,...x,type:"QUERY",context:await l??{},queryParams:c},subscription:S?C=>{var A;!C.resourceId||!C.payload||!Object.keys(C.payload).length||(A=e[u])==null||A.send(JSON.stringify(C));}:void 0});if(!v||!v.data)throw new Error("Invalid resource");S&&v.unsubscribe&&o.set($(x),v.unsubscribe),a({id:R,type:"REPLY",data:{resource:x.resource,data:(v.data??[]).map(C=>C.value)}});}}else if(T.type==="UNSUBSCRIBE"){let{type:b,id:R,...x}=T,S=o.get($(x));S&&(S(),o.delete($(x)));}else if(T.type==="CUSTOM_QUERY"){let{resource:b,procedure:R,input:x,id:S}=T;t.debug("Received custom query from client:",T);try{let v=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:b,procedure:R,input:x,context:await l??{},queryParams:c}});a({id:S,type:"REPLY",data:v});}catch(v){a({id:S,type:"REJECT",resource:b,message:v.message}),t.error("Error handling custom query from the client:",v);}}else if(T.type==="MUTATE"){let{resource:b}=T;t.debug("Received mutation from client:",T);try{let R=T.procedure,x=R,S=T.payload,v=T.resourceId;if(x==="insert"||x==="update"){let A=(f=(p=i.router)==null?void 0:p.routes)==null?void 0:f[b];if(!!!((m=A==null?void 0:A.customMutations)!=null&&m[x])){let I=T.payload??{},{id:j,...E}=I;if(typeof j!="string")throw new Error(`Invalid mutation: payload.id is required for ${x}`);v=j;let P=(h=i.schema)==null?void 0:h[b];if(P&&typeof P.encodeMutation=="function"){let Z=((g=T.meta)==null?void 0:g.timestamp)??new Date().toISOString();S=P.encodeMutation("set",E,Z);}else S=E;x=x.toUpperCase();}}let C=await i.handleMutation({req:{...s,type:"MUTATE",resource:b,input:S,context:{messageId:T.id,...await l??{}},resourceId:v,procedure:x,queryParams:c,meta:T.meta}});(R&&R!=="INSERT"&&R!=="UPDATE"||x!==R&&(x==="INSERT"||x==="UPDATE"))&&a({id:T.id,type:"REPLY",data:C});}catch(R){a({id:T.id,type:"REJECT",resource:b,message:R.message}),t.error("Error parsing mutation from the client:",R);}}}catch(T){t.error("Error handling message from the client:",T);}}),n.on("close",()=>{t.info("Connection closed",u),delete e[u];for(let y of Array.from(o.values()))y();});}};function dt(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Zr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,lt(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{st(e)(dt(n)).then(u=>u.json().then(o=>r.status(u.status).send(o)));});};var ge=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,a,u,o,s){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=a,this._single=u,this._sort=o,this._shouldAwait=s,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 gn=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Ve=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>gn(n)?w(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function K(i,e,t){let n=new Ve(i),r=u=>{let o=ge._init(u,n,true);return Object.assign(Object.create(o),{insert:async c=>{let l=i._getTimestamp(),d=await i.rawInsert(u.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([y,p])=>[y,{value:p,_meta:{timestamp:l}}]))},void 0,t);return w(d.data)},update:async(c,l)=>{let d=i._getTimestamp(),{id:y,...p}=l,f=await i.rawUpdate(u.name,c,{value:Object.fromEntries(Object.entries(p).map(([g,T])=>[g,{value:T,_meta:{timestamp:d}}]))},void 0,t),m=w(f.data),h={};for(let g of Object.keys(p))g in m&&(h[g]=m[g]);return h}})},a={get(u,o){if(o==="findOne")return i.findOne.bind(i);if(o==="find")return i.find.bind(i);if(o==="insert")return (s,c)=>{let l=i._getTimestamp();return i.rawInsert(s.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([d,y])=>[d,{value:y,_meta:{timestamp:l}}]))},void 0,t).then(d=>w(d.data))};if(o==="update")return (s,c,l)=>{let d=i._getTimestamp(),{id:y,...p}=l;return i.rawUpdate(s.name,c,{value:Object.fromEntries(Object.entries(p).map(([f,m])=>[f,{value:m,_meta:{timestamp:d}}]))},void 0,t).then(f=>{let m=w(f.data),h={};for(let g of Object.keys(p))g in m&&(h[g]=m[g]);return h})};if(o==="transaction")return async s=>i.transaction(async({trx:c,commit:l,rollback:d})=>{let y=K(c,e,t);return s({trx:y,commit:l,rollback:d})});if(o in e){let s=e[o];return r(s)}}};return new Proxy({},a)}var ke=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)}},oi=i=>ke.create({...i}),pt=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),mt=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),Qe=class i{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,n,r,a){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=n??{},this.authorization=r,this.hooks=a;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:mt,query:pt}),n={},r={};for(let[a,u]of Object.entries(t))u._type==="mutation"?n[a]=u:r[a]=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},a=$(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:a}})(e);handleMutation=async({req:e,db:t,schema:n})=>{var o;let r=((o=e.meta)==null?void 0:o.timestamp)??new Date().toISOString(),a=t._setMutationTimestamp(r),u=K(a,n,e.context);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let c=s.procedure==="INSERT"?"insert":s.procedure==="UPDATE"?"update":void 0,l=this.customMutations[s.procedure]?s.procedure:c&&this.customMutations[c]?c:s.procedure,d=this.customMutations[l];if(d){s.procedure=l;let y=d.inputValidator["~standard"].validate(s.input),p=y instanceof Promise?await y:y;if(p.issues){let f=p.issues.map(m=>{var g;let h=(g=m.path)==null?void 0:g.map(T=>typeof T=="object"&&"key"in T?String(T.key):String(T)).join(".");return h?`${h}: ${m.message}`:m.message}).join(", ");throw new Error(`Validation failed: ${f}`)}return s.input=p.value,d.handler({req:s,db:u})}else {if(s.procedure==="INSERT"||s.procedure==="UPDATE")return this.handleSet({req:s,db:a,operation:s.procedure,schema:n});throw new Error(`Unknown procedure: ${s.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=K(t,n,e.context);return await this.wrapInMiddlewares(async a=>{let u=this.customQueries[a.procedure];if(!u)throw new Error(`Unknown query procedure: ${a.procedure}`);let o=u.inputValidator["~standard"].validate(a.input),s=o instanceof Promise?await o:o;if(s.issues){let c=s.issues.map(l=>{var y;let d=(y=l.path)==null?void 0:y.map(p=>typeof p=="object"&&"key"in p?String(p.key):String(p)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return a.input=s.value,u.handler({req:a,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 a=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&a)throw new Error("Resource already exists");if(n==="UPDATE"&&!a)throw new Error("Resource not found");let u={value:e.input};return t.transaction(async({trx:o})=>{var l,d,y,p,f,m,h;if(n==="INSERT"){let{data:g,acceptedValues:T}=await o.rawInsert(e.resource,e.resourceId,u,(l=e.context)==null?void 0:l.messageId,e.context);if(!T)throw new Error("Mutation rejected");let b=w(g);if(b.id=b.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let R=this.authorization.insert({ctx:e.context,value:b});if(typeof R=="boolean"){if(!R)throw new Error("Not authorized")}else {let x=U(R,e.resource,r),S=Object.keys(x).length>0?await o.rawFindById(e.resource,e.resourceId,x):g,v=w(S);if(v.id=v.id??e.resourceId,!N(v,R))throw new Error("Not authorized")}}return {data:g,acceptedValues:T}}if((p=(y=this.authorization)==null?void 0:y.update)!=null&&p.preMutation){let g=w(a);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 b=U(T,e.resource,r),R=Object.keys(b).length>0?await o.rawFindById(e.resource,e.resourceId,b):a,x=w(R);if(x.id=x.id??e.resourceId,!N(x,T))throw new Error("Not authorized")}}let{data:s,acceptedValues:c}=await o.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(s);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 b=U(T,e.resource,r),R=Object.keys(b).length>0?await o.rawFindById(e.resource,e.resourceId,b):s,x=w(R);if(x.id=x.id??e.resourceId,!N(x,T))throw new Error("Not authorized")}}return {data:s,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>a=>r({req:a,next:n}),e)(t)}},qe=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 o;let r=((o=e.meta)==null?void 0:o.timestamp)??new Date().toISOString(),a=t._setMutationTimestamp(r),u=K(a,n,e.context);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[s.procedure];if(c){let l=c.inputValidator["~standard"].validate(s.input),d=l instanceof Promise?await l:l;if(d.issues){let y=d.issues.map(p=>{var m;let f=(m=p.path)==null?void 0:m.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return f?`${f}: ${p.message}`:p.message}).join(", ");throw new Error(`Validation failed: ${y}`)}return s.input=d.value,c.handler({req:s,db:u})}throw new Error(`Unknown procedure: ${s.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=K(t,n,e.context);return await this.wrapInMiddlewares(async a=>{let u=this.customQueries[a.procedure];if(!u)throw new Error(`Unknown query procedure: ${a.procedure}`);let o=u.inputValidator["~standard"].validate(a.input),s=o instanceof Promise?await o:o;if(s.issues){let c=s.issues.map(l=>{var y;let d=(y=l.path)==null?void 0:y.map(p=>typeof p=="object"&&"key"in p?String(p.key):String(p)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return a.input=s.value,u.handler({req:a,db:r})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>a=>r({req:a,next:n}),e)(t)}};function ui(i){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>i({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var $e=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Qe(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:mt,query:pt}),n={},r={};for(let[a,u]of Object.entries(t))u._type==="mutation"?n[a]=u:r[a]=u;return new qe(n,r).use(...this.middlewares)}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new i([...this.middlewares,...t])}static create(){return new i}},ci=$e.create;var ee=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([a,u])=>[a,{value:u,_meta:{timestamp:n}}]))});return w(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:a,...u}=n,o=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(u).map(([l,d])=>[l,{value:d,_meta:{timestamp:r}}]))}),s=w(o.data),c={};for(let l of Object.keys(u))l in s&&(c[l]=s[l]);return c}};var Mn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function D(i){var r,a,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=(a=t.constructor)==null?void 0:a.name)==null?void 0:u.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function ft(i){let e=D(i);return Mn[e]}var In="42701";function te(i){var t;if(i.code===In)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 _e(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 Cn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let a of Object.values(e))for(let u of Object.values(a.fields)){let o=u.getStorageFieldType();o.enumValues&&o.enumName&&r.set(o.enumName,{name:o.enumName,values:o.enumValues});}for(let a of Array.from(r.values())){let{name:u,values:o}=a;try{let s=o.map(c=>`'${c}'`).join(", ");await kysely.sql`
|
|
1
|
+
'use strict';var jsXxhash=require('js-xxhash'),le=require('crypto'),Zt=require('qs'),zod=require('zod'),kysely=require('kysely'),mysql=require('kysely/helpers/mysql'),postgres=require('kysely/helpers/postgres'),sqlite=require('kysely/helpers/sqlite');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var le__default=/*#__PURE__*/_interopDefault(le);var Zt__default=/*#__PURE__*/_interopDefault(Zt);var ut=Object.create;var _e=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var mt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ht=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yt(e))!ft.call(i,r)&&r!==t&&_e(i,r,{get:()=>e[r],enumerable:!(n=dt(e,r))||n.enumerable});return i};var Qe=(i,e,t)=>(t=i!=null?ut(pt(i)):{},ht(_e(t,"default",{value:i,enumerable:true}),i));var we=mt(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.parse=Wt;pe.serialize=Ut;var _t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Qt=/^[\u0021-\u003A\u003C-\u007E]*$/,$t=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,qt=/^[\u0020-\u003A\u003D-\u007E]*$/,Kt=Object.prototype.toString,Bt=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Wt(i,e){let t=new Bt,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Ht,o=0;do{let c=i.indexOf("=",o);if(c===-1)break;let s=i.indexOf(";",o),a=s===-1?n:s;if(c>a){o=i.lastIndexOf(";",c-1)+1;continue}let l=Ue(i,o,c),u=He(i,c,l),d=i.slice(l,u);if(t[d]===void 0){let p=Ue(i,c+1,a),y=He(i,a,p),f=r(i.slice(p,y));t[d]=f;}o=a+1;}while(o<n);return t}function Ue(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function He(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Ut(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!_t.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Qt.test(r))throw new TypeError(`argument val is invalid: ${e}`);let o=i+"="+r;if(!t)return o;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);o+="; Max-Age="+t.maxAge;}if(t.domain){if(!$t.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);o+="; Domain="+t.domain;}if(t.path){if(!qt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);o+="; Path="+t.path;}if(t.expires){if(!zt(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);o+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(o+="; HttpOnly"),t.secure&&(o+="; Secure"),t.partitioned&&(o+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":o+="; Priority=Low";break;case "medium":o+="; Priority=Medium";break;case "high":o+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":o+="; SameSite=Strict";break;case "lax":o+="; SameSite=Lax";break;case "none":o+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return o}function Ht(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function zt(i){return Kt.call(i)==="[object Date]"}});var ge=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),S=i=>i?Array.isArray(i.value)?i.value.map(t=>ge(t)?S(t):t):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([t,n])=>Array.isArray(n)?[t,n.map(r=>ge(r)?S(r):r)]:ge(n)?[t,S(n)]:[t,n])):void 0;var U=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),Re=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let o=c=>{c.$and?c.$and.forEach(o):c.$or?c.$or.forEach(o):Object.entries(c).forEach(([s,a])=>{var l;if((l=r.relations)!=null&&l[s]&&(n[s]=true,typeof a=="object"&&a!==null&&!Array.isArray(a))){let u=Re(a,r.relations[s].entity.name,t);Object.keys(u).length>0&&(n[s]={include:u});}});};return o(i),n},V=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(c=>V(i,c,t));if(n==="$or")return r.some(c=>V(i,c,t));let o=(r==null?void 0:r.$eq)!==void 0?r==null?void 0:r.$eq:r;if(typeof r=="object"&&r!==null&&(r==null?void 0:r.$eq)===void 0){if(r.$in!==void 0){let s=i[n];return s===void 0?false:t?!r.$in.includes(s):r.$in.includes(s)}if(r.$not!==void 0&&!t)return V(i,{[n]:r.$not},true);if(r.$gt!==void 0){let s=i[n];return typeof s!="number"?false:t?s<=r.$gt:s>r.$gt}if(r.$gte!==void 0){let s=i[n];return typeof s!="number"?false:t?s<r.$gte:s>=r.$gte}if(r.$lt!==void 0){let s=i[n];return typeof s!="number"?false:t?s>=r.$lt:s<r.$lt}if(r.$lte!==void 0){let s=i[n];return typeof s!="number"?false:t?s>r.$lte:s<=r.$lte}let c=i[n];return !c||typeof c!="object"&&!Array.isArray(c)?false:Array.isArray(c)?t?!c.some(s=>V(s,r,false)):c.some(s=>V(s,r,false)):V(c,r,t)}return t?i[n]!==o:i[n]===o}),H=i=>{if(typeof i!="object"||i===null)return false;let e=i;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},D={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},xe=class{level;prefix;constructor(e={}){this.level=e.level??D.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=D.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=D.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=D.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=D.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=D.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},$e=i=>new xe(i);var Ke="0123456789ABCDEFGHJKMNPQRSTVWXYZ",J=32;var Mt=16,Be=10,qe=0xffffffffffff;var $;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})($||($={}));var q=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function At(i){let e=Math.floor(i()*J);return e===J&&(e=J-1),Ke.charAt(e)}function Ot(i){var n;let e=jt(),t=e&&(e.crypto||e.msCrypto)||(typeof le__default.default<"u"?le__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=le__default.default)!=null&&n.randomBytes)return ()=>le__default.default.randomBytes(1).readUInt8()/255;throw new q($.PRNGDetectFailure,"Failed to find a reliable PRNG")}function jt(){return Nt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Et(i,e){let t="";for(;i>0;i--)t=At(e)+t;return t}function Pt(i,e=Be){if(isNaN(i))throw new q($.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>qe)throw new q($.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${qe}: ${i}`);if(i<0)throw new q($.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new q($.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%J,n=Ke.charAt(t)+n,i=(i-t)/J;return n}function Nt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function We(i,e){let t=Ot(),n=Date.now();return Pt(n,Be)+Et(Mt,t)}var de=()=>We().toLowerCase(),ue=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ue(n)}return ue(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ue(r)}throw n}}}),K=i=>i instanceof Promise?i:ue(i);function Se(i){return U({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}function Vt(i,e){let t=i==null,n=e==null;if(t&&n)return 0;if(t)return -1;if(n)return 1;if(typeof i=="number"&&typeof e=="number")return i-e;if(typeof i=="boolean"&&typeof e=="boolean")return Number(i)-Number(e);let r=String(i),o=String(e);return r<o?-1:r>o?1:0}var G=class{limit;directions;entries=[];index=new Map;constructor(e){if(!Number.isInteger(e.limit)||e.limit<0)throw new Error("WindowIndex limit must be a non-negative integer");this.limit=e.limit,this.directions=(e.orderBy??[]).map(t=>t.direction);}get size(){return this.entries.length}get isFull(){return this.entries.length>=this.limit}compare(e,t){for(let n=0;n<this.directions.length;n++){let r=Vt(e.sortKey[n],t.sortKey[n]);if(r!==0)return this.directions[n]==="desc"?-r:r}return e.id<t.id?-1:e.id>t.id?1:0}lowerBound(e){let t=0,n=this.entries.length;for(;t<n;){let r=t+n>>>1;this.compare(this.entries[r],e)<0?t=r+1:n=r;}return t}insert(e){if(this.limit===0)return {inserted:false};if(this.index.has(e.id))throw new Error(`WindowIndex already contains id "${e.id}"`);let t=this.lowerBound(e);if(this.isFull&&t>=this.limit)return {inserted:false};if(this.entries.splice(t,0,e),this.index.set(e.id,e),this.entries.length>this.limit){let n=this.entries.pop();if(n)return this.index.delete(n.id),{inserted:true,evicted:n}}return {inserted:true}}remove(e){let t=this.index.get(e);if(!t)return;let n=this.lowerBound(t);return this.entries.splice(n,1),this.index.delete(e),t}has(e){return this.index.has(e)}position(e){let t=this.index.get(e);if(t)return this.lowerBound(t)}boundary(){return this.entries[this.entries.length-1]}needsBackfill(){return this.entries.length<this.limit}get backfillCount(){return Math.max(0,this.limit-this.entries.length)}snapshot(){return this.entries.map(e=>({id:e.id,sortKey:[...e.sortKey]}))}ids(){return this.entries.map(e=>e.id)}};var ye=class{storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,o]of Object.entries(n.relations))o.type==="one"&&o.relationalColumn&&t.set(String(o.relationalColumn),{relationName:r,targetResource:o.entity.name});return t}ensureObjectNode(e,t,n){let r=this.objectNodes.get(e);return r?n&&r.matchedQueries.add(n):(r={id:e,type:t,matchedQueries:new Set(n?[n]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,r)),r}storeRelation(e,t,n,r){let o=this.objectNodes.get(e),c=this.objectNodes.get(t);if(o&&o.referencesObjects.set(n,t),c&&r){let s=c.referencedByObjects.get(r);s||(s=new Set,c.referencedByObjects.set(r,s)),s.add(e);}}removeRelation(e,t,n,r){let o=this.objectNodes.get(e),c=this.objectNodes.get(t);if(o&&o.referencesObjects.delete(n),c&&r){let s=c.referencedByObjects.get(r);s&&(s.delete(e),s.size===0&&c.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let o=r.relations[n];if(!o)return;let c=this.schema[t];if(c!=null&&c.relations){if(o.type==="many"&&o.foreignColumn){for(let[s,a]of Object.entries(c.relations))if(a.entity.name===e&&a.type==="one"&&a.relationalColumn===o.foreignColumn)return s}if(o.type==="one"&&o.relationalColumn){for(let[s,a]of Object.entries(c.relations))if(a.entity.name===e&&a.type==="many"&&a.foreignColumn===o.relationalColumn)return s}}}updateRelationsFromMutation(e,t,n,r){let o=this.getRelationalColumns(e),c=this.objectNodes.get(t);if(c)for(let[s,{relationName:a,targetResource:l}]of Array.from(o)){if(!(r&&s in r))continue;let d=this.getInverseRelationName(e,l,a),p=c.referencesObjects.get(a),y=n[s];p!==y&&(p&&this.removeRelation(t,p,a,d),y&&(this.ensureObjectNode(y,l),this.storeRelation(t,y,a,d)));}}get(e,t){let n=this.addedSortRelations(e.resource,e.sort,e.include),r={...e.include??{}};for(let c of n)r[c]=true;let o={...e,...e.limit!==void 0?{sort:[...e.sort??[],{key:"id",direction:"asc"}]}:{},...Object.keys(r).length>0?{include:this.prepareResolveInclude(r,e.resource)}:{}};return K(this.storage.get(o)).then(c=>(this.ingest(e,c),this.stripResolveRelations(c,e.resource,e.include,e.sort),c))}addedSortRelations(e,t,n){var o,c;let r=[];for(let s of t??[]){let a=s.key.indexOf(".");if(a===-1)continue;let l=s.key.slice(0,a);(c=(o=this.schema[e])==null?void 0:o.relations)!=null&&c[l]&&(n&&l in n||r.includes(l)||r.push(l));}return r}stripResolveRelations(e,t,n,r){var c,s,a;let o=this.addedSortRelations(t,r,n);if(o.length>0)for(let l of e){let u=l==null?void 0:l.value;if(u)for(let d of o)delete u[d];}if(n)for(let[l,u]of Object.entries(n)){let d=(s=(c=this.schema[t])==null?void 0:c.relations)==null?void 0:s[l],p=d==null?void 0:d.entity.name;if(!p)continue;let y=H(u)?u:null,f=y?y.include:u&&typeof u=="object"?u:void 0,m=y==null?void 0:y.orderBy;for(let h of e){let T=(a=h==null?void 0:h.value)==null?void 0:a[l];if(!T)continue;let R=d.type==="many"?Array.isArray(T.value)?T.value:[]:[T];this.stripResolveRelations(R,p,f,m);}}}relationalSortDeps(e){var r,o;let t=[],n=e.sort??[];for(let c=0;c<n.length;c++){let s=n[c].key.indexOf(".");if(s===-1)continue;let a=n[c].key.slice(0,s),l=n[c].key.slice(s+1),u=(o=(r=this.schema[e.resource])==null?void 0:r.relations)==null?void 0:o[a];u&&t.push({index:c,relationName:a,field:l,targetResource:u.entity.name});}return t}sortRelationInclude(e){let t=this.relationalSortDeps(e.queryStep.query);if(t.length===0)return;let n={};for(let r of t)n[r.relationName]=true;return n}relationalSortFkColumns(e){let t=new Set,n=this.relationalSortDeps(e.queryStep.query);if(n.length===0)return t;let r=this.getRelationalColumns(e.queryStep.query.resource);for(let[o,{relationName:c}]of Array.from(r))n.some(s=>s.relationName===c)&&t.add(o);return t}ownWriteTouchesSortRelationFk(e,t){if(!t)return false;for(let n of Array.from(this.relationalSortFkColumns(e)))if(n in t)return true;return false}async resolveSortRelations(e,t,n){let r=this.sortRelationInclude(e);if(!r)return n;let o=await K(this.storage.get({resource:e.queryStep.query.resource,where:{id:t},include:r})),c=o[0]?S(o[0]):void 0;if(!c||typeof c!="object")return n;for(let s of Object.keys(r))s in c||(c[s]=void 0);return c}stripPayloadRelations(e,t){if(t)for(let n of Object.keys(t))delete e[n];return e}prepareResolveInclude(e,t){var r,o,c;let n={};for(let[s,a]of Object.entries(e)){let l=(c=(o=(r=this.schema[t])==null?void 0:r.relations)==null?void 0:o[s])==null?void 0:c.entity.name;if(H(a)){let u=a.limit!==void 0,d={...a.include??{}};if(u&&l)for(let y of this.addedSortRelations(l,a.orderBy,a.include))d[y]=true;let p=l&&Object.keys(d).length>0?this.prepareResolveInclude(d,l):a.include;n[s]={...a,...p!==void 0?{include:p}:{},...u?{orderBy:[...a.orderBy??[],{key:"id",direction:"asc"}]}:{}};}else a&&typeof a=="object"&&l?n[s]=this.prepareResolveInclude(a,l):n[s]=a;}return n}ingest(e,t){for(let n of this.buildSteps({query:e})){let r=n.stepPath.length===0?t:this.extractByPath(t,e.resource,n.stepPath);this.trackObjects(n,r);}}extractByPath(e,t,n){var c,s,a;let r=e,o=t;for(let l of n){let u=(s=(c=this.schema[o])==null?void 0:c.relations)==null?void 0:s[l],d=(u==null?void 0:u.type)==="many",p=[];for(let y of r){let f=(a=y==null?void 0:y.value)==null?void 0:a[l];if(f)if(d){if(Array.isArray(f.value))for(let m of f.value)m&&p.push(m);}else f.value!=null&&p.push(f);}r=p,u&&(o=u.entity.name);}return r}subscribe(e,t,n={}){let r=this.buildSteps({query:e}),o={},c=[];for(let s of r){this.logger.debug("[QueryEngine] Subscribing to step",s.stepPath.join("."));let a=Se(s),l=o[s.stepPath.at(-2)??""],u=s.stepPath.at(-1)??"",d=this.queryNodes.get(a);if(d)d.subscriptions.add(t);else {let p=s.stepPath.length===0&&s.query.limit!==void 0;if(d={hash:a,queryStep:s,relationName:u,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:l,childQueries:new Set,windowIndex:p?new G({limit:s.query.limit,orderBy:this.orderByFor(s.query)}):void 0},this.queryNodes.set(d.hash,d),l){let y=this.queryNodes.get(l);y&&y.childQueries.add(d.hash);}}o[u]=a,c.push(()=>{let p=this.queryNodes.get(a);p&&(p.subscriptions.delete(t),p.subscriptions.size===0&&this.queryNodes.delete(a));});}return ()=>{for(let s of c)s();}}buildSteps(e){var y,f;let{query:t,stepPath:n=[],parentResource:r}=e,{include:o}=t,c=n.length===0,s=n.at(-1),a;if(!c&&r&&s){let m=(f=(y=this.schema[r])==null?void 0:y.relations)==null?void 0:f[s];m&&(a=m.type==="many");}let{include:l,...u}=t,p=[{query:u,stepPath:[...n],includedRelations:o&&typeof o=="object"?Object.keys(o):[],isMany:a,relationName:s}];if(o&&typeof o=="object"&&Object.keys(o).length>0){let m=this.schema[t.resource];if(!m)throw new Error(`Resource ${t.resource} not found`);p.push(...Object.entries(o).flatMap(([h,T])=>{let R=m.relations[h];if(!R)throw new Error(`Relation ${h} not found for resource ${t.resource}`);let w=R.entity.name,x=H(T)?T:null;return this.buildSteps({query:{resource:w,include:x?x.include:typeof T=="object"?T:void 0,where:x==null?void 0:x.where,limit:x==null?void 0:x.limit,sort:x==null?void 0:x.orderBy},stepPath:[...n,h],parentResource:t.resource})}));}return p}trackObjects(e,t){var a;this.logger.debug("[QueryEngine] Tracking step objects",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=Se(e),r=this.queryNodes.get(n),o=e.query.resource;if(!r)return;let c=this.getRelationalColumns(o);for(let l of t){let u=S(l),d=u.id;this.ensureObjectNode(d,o,n),r.trackedObjects.add(d);for(let[p,{relationName:y,targetResource:f}]of Array.from(c)){let m=u[p];if(m){this.ensureObjectNode(m,f);let h=this.getInverseRelationName(o,f,y);this.storeRelation(d,m,y,h);}}this.loadNestedRelations(o,d,u),this.logger.debug("[QueryEngine] Loaded nested relations for",d);}if(r.windowIndex&&!r.windowInitialized){for(let l of t){let u=S(l);!(u!=null&&u.id)||r.windowIndex.has(u.id)||r.windowIndex.insert({id:u.id,sortKey:this.sortKeyFor(r,u)});}r.windowInitialized=true;}let s=this.includeForeignColumn(r);if(s){r.seededParents??=new Set;for(let l of t){let u=S(l),d=u==null?void 0:u.id,p=u==null?void 0:u[s];if(!d||p==null||r.seededParents.has(p))continue;let y=this.ensureParentWindow(r,p);y.has(d)||y.insert({id:d,sortKey:this.sortKeyFor(r,u)});}for(let l of t){let u=(a=S(l))==null?void 0:a[s];u!=null&&r.seededParents.add(u);}}}orderByFor(e){return (e.sort??[]).map(t=>({key:t.key,direction:t.direction}))}sortKeyFor(e,t,n){return (e.queryStep.query.sort??[]).map((r,o)=>{let c=r.key.indexOf(".");if(c===-1)return t==null?void 0:t[r.key];let s=r.key.slice(0,c),a=r.key.slice(c+1),l=t==null?void 0:t[s];if(l&&typeof l=="object"&&a in l)return l[a];if(!(t&&typeof t=="object"&&s in t))return n==null?void 0:n[o]})}storageSortFor(e){return [...e.queryStep.query.sort??[],{key:"id",direction:"asc"}]}includeForeignColumn(e){var o,c;if(e.queryStep.stepPath.length===0||e.queryStep.query.limit===void 0||!e.relationName||!e.parentQuery)return;let t=this.queryNodes.get(e.parentQuery),n=t==null?void 0:t.queryStep.query.resource;if(!n)return;let r=(c=(o=this.schema[n])==null?void 0:o.relations)==null?void 0:c[e.relationName];if(!((r==null?void 0:r.type)!=="many"||!r.foreignColumn))return String(r.foreignColumn)}isWindowedIncludeNode(e){return this.includeForeignColumn(e)!==void 0}ensureParentWindow(e,t){e.windowIndexes||(e.windowIndexes=new Map);let n=e.windowIndexes.get(t);return n||(n=new G({limit:e.queryStep.query.limit,orderBy:this.orderByFor(e.queryStep.query)}),e.windowIndexes.set(t,n)),n}parentWindowHolding(e,t){if(e.windowIndexes){for(let[n,r]of Array.from(e.windowIndexes))if(r.has(t))return {parentId:n,wi:r}}}emitToSubscribers(e,t,n){for(let r of Array.from(e.subscriptions))try{r(t);}catch(o){this.logger.error(`[QueryEngine] Error in subscription during ${n}`,{error:o,queryHash:e.hash,resource:t.resource,resourceId:t.resourceId});}}emitScopeOut(e,t,n){var r;e.trackedObjects.delete(t),(r=this.objectNodes.get(t))==null||r.matchedQueries.delete(e.hash),this.emitToSubscribers(e,{type:"SYNC",op:"DELETE",resource:e.queryStep.query.resource,resourceId:t,payload:{},meta:n},"scope-out DELETE");}handleWindowedInsert(e,t,n,r){var c;let o=t.insert({id:n.resourceId,sortKey:this.sortKeyFor(e,r)});o.inserted&&(e.trackedObjects.add(n.resourceId),(c=this.objectNodes.get(n.resourceId))==null||c.matchedQueries.add(e.hash),this.emitToSubscribers(e,n,"windowed scope-in INSERT"),o.evicted&&this.emitScopeOut(e,o.evicted.id,n.meta));}async handleWindowedUpdate(e,t,n,r,o){let c=e.windowIndex;if(!c)return;let s=t.resourceId,a=c.has(s);if(o&&(!a||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,s,r)),o){if(a){await this.refreshInWindow(e,c,t,r);return}this.scopeInViaUpdate(e,c,t,n,r);return}a&&(c.remove(s),this.emitScopeOut(e,s,t.meta),await this.backfillWindow(e,c,t.meta));}async refreshInWindow(e,t,n,r,o){var l,u;let c=n.resourceId,s=(l=t.remove(c))==null?void 0:l.sortKey,a=this.sortKeyFor(e,r,s);if(t.insert({id:c,sortKey:a}),t.isFull&&((u=t.boundary())==null?void 0:u.id)===c&&!this.sortKeysEqual(s,a)){await this.reconcileDemotion(e,t,c,a,n,o);return}this.emitToSubscribers(e,n,"windowed UPDATE");}scopeInViaUpdate(e,t,n,r,o){var a;let c=n.resourceId,s=t.insert({id:c,sortKey:this.sortKeyFor(e,o)});s.inserted&&(e.trackedObjects.add(c),(a=this.objectNodes.get(c))==null||a.matchedQueries.add(e.hash),this.emitToSubscribers(e,this.fullInsertDelta(e,n,r),"windowed scope-in INSERT"),s.evicted&&this.emitScopeOut(e,s.evicted.id,n.meta));}async handleWindowedIncludeUpdate(e,t,n,r,o){let c=this.includeForeignColumn(e);if(!c)return;let s=t.resourceId,a=o?r[c]:void 0,l=this.parentWindowHolding(e,s),u=l==null?void 0:l.parentId,d=u!==void 0&&u===a;if((a!==void 0&&!d||this.ownWriteTouchesSortRelationFk(e,t.payload))&&(r=await this.resolveSortRelations(e,s,r)),d){await this.refreshInWindow(e,l.wi,t,r,{column:c,parentId:u});return}if(l&&(l.wi.remove(s),this.emitScopeOut(e,s,t.meta),await this.backfillWindow(e,l.wi,t.meta,{column:c,parentId:l.parentId})),a!==void 0){let p=this.ensureParentWindow(e,a);p.has(s)||this.scopeInViaUpdate(e,p,t,n,r);}}async handleRelationalSortFanout(e,t){if(!e.payload)return;let n=this.objectNodes.get(e.resourceId);for(let r of Array.from(this.queryNodes.values())){let o=this.relationalSortDeps(r.queryStep.query);if(o.length===0)continue;let c=!!r.windowIndex,s=this.isWindowedIncludeNode(r);if(!c&&!s)continue;let a=false;for(let l of o){if(l.targetResource!==e.resource||!(l.field in e.payload))continue;a=true;let u=t==null?void 0:t[l.field],d=this.getInverseRelationName(r.queryStep.query.resource,e.resource,l.relationName),p=n&&d?n.referencedByObjects.get(d):void 0;if(!(!p||p.size===0))for(let y of Array.from(p))if(c){let f=r.windowIndex;if(!f.has(y))continue;this.repositionForRelationalChange(f,y,l.index,u);}else {let f=this.parentWindowHolding(r,y);if(!f)continue;this.repositionForRelationalChange(f.wi,y,l.index,u);}}if(a){if(c)r.windowInitialized&&await this.reconcilePromotions(r,r.windowIndex,e);else if(r.windowIndexes){let l=this.includeForeignColumn(r);for(let[u,d]of Array.from(r.windowIndexes))await this.reconcilePromotions(r,d,e,{column:l,parentId:u});}}}}repositionForRelationalChange(e,t,n,r){let o=e.remove(t);if(!o)return;let c=[...o.sortKey];c[n]=r,e.insert({id:t,sortKey:c});}async reconcilePromotions(e,t,n,r){let o=e.queryStep.query.limit;if(o===void 0)return;let c=e.queryStep.query.resource,s=this.sortRelationInclude(e),a=e.queryStep.query.where;r&&(a=this.combineWhere(a,{[r.column]:r.parentId}));let u=(await K(this.storage.get({resource:c,where:a,sort:this.storageSortFor(e),limit:o,include:s}))).map(p=>({row:p,value:S(p)})).filter(p=>{var y;return !!((y=p.value)!=null&&y.id)}),d=new Set(u.map(p=>p.value.id));for(let p of t.ids())d.has(p)||(t.remove(p),this.emitScopeOut(e,p,n.meta));for(let{row:p,value:y}of u){let f=this.sortKeyFor(e,y);if(t.has(y.id)){t.remove(y.id),t.insert({id:y.id,sortKey:f});continue}let m=t.insert({id:y.id,sortKey:f});if(!m.inserted)continue;e.trackedObjects.add(y.id),this.ensureObjectNode(y.id,c,e.hash).matchedQueries.add(e.hash),this.registerObjectRelations(c,y.id,y);let h=this.stripPayloadRelations({...(p==null?void 0:p.value)??{}},s);delete h.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:c,resourceId:y.id,payload:h,meta:n.meta},"windowed relational promotion INSERT"),m.evicted&&this.emitScopeOut(e,m.evicted.id,n.meta);}}registerObjectRelations(e,t,n){let r=this.getRelationalColumns(e);for(let[o,{relationName:c,targetResource:s}]of Array.from(r)){let a=n==null?void 0:n[o];if(!a)continue;this.ensureObjectNode(a,s);let l=this.getInverseRelationName(e,s,c);this.storeRelation(t,a,c,l);}}sortKeysEqual(e,t){if(!e||e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return false;return true}async reconcileDemotion(e,t,n,r,o,c){t.remove(n);let s=e.queryStep.query.resource,a=this.windowReadWhere(e,t,c),l=this.sortRelationInclude(e),u=await K(this.storage.get({resource:s,where:a,sort:this.storageSortFor(e),limit:2,include:l})),d,p;for(let f of u){let m=S(f);if(!(!(m!=null&&m.id)||m.id===n||t.has(m.id))){d=m,p=f;break}}if(!d){t.insert({id:n,sortKey:r}),this.emitToSubscribers(e,o,"windowed UPDATE");return}if(t.insert({id:d.id,sortKey:this.sortKeyFor(e,d)}),t.insert({id:n,sortKey:r}).inserted){this.emitToSubscribers(e,o,"windowed UPDATE");return}e.trackedObjects.add(d.id),this.ensureObjectNode(d.id,s,e.hash).matchedQueries.add(e.hash);let y=this.stripPayloadRelations({...(p==null?void 0:p.value)??{}},l);delete y.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:s,resourceId:d.id,payload:y,meta:o.meta},"windowed demotion backfill INSERT"),this.emitScopeOut(e,n,o.meta);}fullInsertDelta(e,t,n){let r={...(n==null?void 0:n.value)??{}};return delete r.id,{type:"SYNC",op:"INSERT",resource:e.queryStep.query.resource,resourceId:t.resourceId,payload:r,meta:t.meta}}async backfillWindow(e,t,n,r){let o=t.backfillCount;if(o<=0)return;let c=e.queryStep.query.resource,s=this.windowReadWhere(e,t,r),a=this.sortRelationInclude(e),l=await K(this.storage.get({resource:c,where:s,sort:this.storageSortFor(e),limit:o,include:a}));for(let u of l){let d=S(u);if(!(d!=null&&d.id)||t.has(d.id))continue;t.insert({id:d.id,sortKey:this.sortKeyFor(e,d)}),e.trackedObjects.add(d.id),this.ensureObjectNode(d.id,c,e.hash).matchedQueries.add(e.hash);let p=this.stripPayloadRelations({...(u==null?void 0:u.value)??{}},a);delete p.id,this.emitToSubscribers(e,{type:"SYNC",op:"INSERT",resource:c,resourceId:d.id,payload:p,meta:n},"windowed backfill INSERT");}}buildCursorWhere(e,t){if(!t)return;let n=[...e.queryStep.query.sort??[],{key:"id",direction:"asc"}],r=[...t.sortKey,t.id],o=[];for(let c=0;c<n.length;c++){let s=[];for(let l=0;l<c;l++)s.push(this.cursorCond(n[l].key,r[l]));let a=n[c].direction==="desc"?"$lt":"$gt";s.push(this.cursorCond(n[c].key,{[a]:r[c]})),o.push(s.length===1?s[0]:{$and:s});}return o.length===1?o[0]:{$or:o}}cursorCond(e,t){let n=e.indexOf(".");return n===-1?{[e]:t}:{[e.slice(0,n)]:{[e.slice(n+1)]:t}}}windowReadWhere(e,t,n){let r=e.queryStep.query.where;return n&&(r=this.combineWhere(r,{[n.column]:n.parentId})),this.combineWhere(r,this.buildCursorWhere(e,t.boundary()))}combineWhere(e,t){return t?!e||Object.keys(e).length===0?t:{$and:[e,t]}:e}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[o,c]of Object.entries(r.relations)){let s=n[o];if(!s)continue;let a=c.entity.name,l=this.getInverseRelationName(e,a,o);if(c.type==="one")s&&typeof s=="object"&&s.id&&(this.ensureObjectNode(s.id,a),this.storeRelation(t,s.id,o,l),this.loadNestedRelations(a,s.id,s));else if(c.type==="many"&&Array.isArray(s)){for(let u of s)if(u&&typeof u=="object"&&u.id){this.ensureObjectNode(u.id,a);let d=this.getInverseRelationName(a,e,o);d&&this.storeRelation(u.id,t,d,o),this.loadNestedRelations(a,u.id,u);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let o=this.queryNodes.get(r);if(!o||!o.relationName)continue;let c=this.buildIncludeFromChildQueries(r);n[o.relationName]=Object.keys(c).length>0?c:true;}return n}sendInsertsForTree(e,t,n,r){var a,l;let o=(l=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:l.value;if(!o)return;let c={op:"INSERT",resource:n,resourceId:o,type:"SYNC",payload:t.value,meta:r};for(let u of Array.from(e.subscriptions))try{u(c);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:o,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(o),this.ensureObjectNode(o,n,e.hash).matchedQueries.add(e.hash);for(let u of Array.from(e.childQueries)){let d=this.queryNodes.get(u);if(!d||!d.relationName)continue;let p=d.relationName,y=d.queryStep.query.resource,f=t.value[p];if(!f)continue;let m=f.value;if(Array.isArray(m))for(let h of m)this.sendInsertsForTree(d,h,y,r);else m&&typeof m=="object"&&this.sendInsertsForTree(d,m,y,r);}}handleMutation(e,t){if(e.op==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=S(t);if(!n)return;let r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,r);let o=this.getRelationalColumns(e.resource);for(let[s,{relationName:a,targetResource:l}]of Array.from(o)){let u=n[s];if(u){this.ensureObjectNode(u,l);let d=this.getInverseRelationName(e.resource,l,a);this.storeRelation(e.resourceId,u,a,d);}}let c=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(async s=>{try{for(let a of s){let l=this.queryNodes.get(a);if(!l)continue;if(l.windowIndex){let d=await this.resolveSortRelations(l,e.resourceId,n);this.handleWindowedInsert(l,l.windowIndex,e,d);continue}let u=this.includeForeignColumn(l);if(u){let d=n[u];if(d!=null){let p=await this.resolveSortRelations(l,e.resourceId,n);this.handleWindowedInsert(l,this.ensureParentWindow(l,d),e,p);}continue}l.trackedObjects.add(e.resourceId),c&&c.matchedQueries.add(a);for(let d of Array.from(l.subscriptions))try{d(e);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:p,queryHash:l.hash,resource:e.resource,resourceId:e.resourceId,stepPath:l.queryStep.stepPath.join(".")});}}}catch(a){this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:a,resource:e.resource,resourceId:e.resourceId});}},s=>{this.logger.error("[QueryEngine] Error handling INSERT mutation",{error:s,resource:e.resource,resourceId:e.resourceId});});return}if(e.op==="UPDATE"){let n=S(t);if(!n)return;let r=this.objectNodes.get(e.resourceId),o=new Set((r==null?void 0:r.matchedQueries)??[]);r||(r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,r)),this.updateRelationsFromMutation(e.resource,e.resourceId,n,e.payload),this.handleRelationalSortFanout(e,n).catch(c=>{this.logger.error("[QueryEngine] Error during relational sort fan-out",{error:c,resource:e.resource,resourceId:e.resourceId});}),this.getMatchingQueries(e,n).then(async c=>{let s=new Set(c),a=new Set;for(let y of Array.from(this.queryNodes.values()))y.queryStep.query.resource===e.resource&&(y.windowIndex?(a.add(y.hash),await this.handleWindowedUpdate(y,e,t,n,s.has(y.hash))):this.isWindowedIncludeNode(y)&&(a.add(y.hash),await this.handleWindowedIncludeUpdate(y,e,t,n,s.has(y.hash))));let l=[],u=[],d=[];for(let y of c)a.has(y)||(o.has(y)?d.push(y):l.push(y));for(let y of Array.from(o))a.has(y)||s.has(y)||u.push(y);for(let y of l){let f=this.queryNodes.get(y);f&&f.trackedObjects.add(e.resourceId);}for(let y of u){let f=this.queryNodes.get(y);f&&f.trackedObjects.delete(e.resourceId);}let p=this.objectNodes.get(e.resourceId);if(p){for(let y of l)p.matchedQueries.add(y);for(let y of u)p.matchedQueries.delete(y);}for(let y of [...u,...d]){let f=this.queryNodes.get(y);if(f)for(let m of Array.from(f.subscriptions))try{m(e);}catch(h){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:h,queryHash:f.hash,resource:e.resource,resourceId:e.resourceId,stepPath:f.queryStep.stepPath.join(".")});}}if(l.length>0)for(let y of l){let f=this.queryNodes.get(y);if(!f)continue;let m=this.buildIncludeFromChildQueries(y);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(m).length>0?m:void 0}).then(h=>{!h||h.length===0||this.sendInsertsForTree(f,h[0],e.resource,e.meta);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?K([]):Promise.all(n.map(async r=>{let o=r.queryStep.query.where,c=r.queryStep.query.resource,s=e.resourceId,a=this.objectNodes.get(s);if(!a)return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=y==null?void 0:y.queryStep.query.resource,m=f?this.getInverseRelationName(f,c,r.relationName):void 0,h=m?a.referencesObjects.get(m):void 0;if(!h)return {hash:r.hash,matches:false};let T=this.objectNodes.get(h);if(!T||!y||!T.matchedQueries.has(y.hash))return {hash:r.hash,matches:false}}if(!o)return {hash:r.hash,matches:true};let l=Re(o,c,this.schema),u=Object.keys(l).length>0;if(!u&&t!==void 0)return {hash:r.hash,matches:V(t,o)};let d=await this.storage.get({resource:c,where:{id:s},include:u?l:void 0});if(!d||d.length===0)return {hash:r.hash,matches:false};let p=S(d[0]);return p?{hash:r.hash,matches:V(p,o)}:{hash:r.hash,matches:false}})).then(r=>r.filter(o=>o.matches).map(o=>o.hash))}};var mr=i=>i,kt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],Dt=i=>i.length===1?i[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let o of i){let c=await o({...e,value:n,rawValue:t});c&&(t=c,n=S(t),n.id=e.value.id,r=true);}return r?t:void 0}),Ft=i=>i.length===1?i[0]:(async e=>{for(let t of i)await t(e);}),ve=i=>{let e=i.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of kt){let r=e.map(o=>o[n]).filter(o=>o!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=Ft(r):t[n]=Dt(r));}return t},hr=(...i)=>{let e={},t=new Set;for(let n of i)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=i.map(c=>c[n]),o=ve(r);o&&(e[n]=o);}return e};var Ze=Qe(we());zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()});var be=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.any().nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),Jt=be.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Gt=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),ze=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),Z=Gt.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:ze}),Ie=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("SYNC"),resource:zod.z.string(),resourceId:zod.z.string(),op:zod.z.enum(["INSERT","UPDATE","DELETE"]),payload:Jt,meta:ze}),Ce=(i,e)=>{i.op==="DELETE"&&Object.keys(i.payload).length>0&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"DELETE delta payload must be empty"});};Ie.superRefine(Ce);var Je=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var Ge=Z.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:Z.shape.meta});var Le=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(Le);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=Le(n);return e}return i},Ye=i=>{let e=i.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,o={headers:r,cookies:r.cookie?Ze.default.parse(r.cookie):{}},c=new URL(t.url),s=c.pathname.split("/"),a=c.searchParams,l=Le(Zt__default.default.parse(a.toString())),u=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:o.headers,cookies:o.cookies,queryParams:l}))??{};if(t.method==="POST")try{let d=s[s.length-1],p=s[s.length-2];if(p==="query"){if(s.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let x=s[s.length-3],C=t.body?await t.json():{};if(!x||x.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let O=await i.handleCustomQuery({req:{...o,type:"CUSTOM_QUERY",resource:x,procedure:d,input:C.input,context:u,queryParams:l}});return Response.json(O)}let y=p,f=t.body?await t.json():{},{success:m,data:h,error:T}=Ge.safeParse(f);if(!m)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:T},{status:400});let R=h,w=await i.handleMutation({req:{...o,type:"MUTATE",resource:y,input:R.payload,context:u,resourceId:R.resourceId,procedure:d,queryParams:{},meta:R.meta}});return Response.json(w)}catch(d){return e.error("Error parsing mutation from the client:",d),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var et=Qe(we());var F=zod.z.string(),Me=Je,Yt=zod.z.object({id:F,type:zod.z.literal("SUBSCRIBE")}).and(Me),Xt=zod.z.object({id:F,type:zod.z.literal("UNSUBSCRIBE")}).and(Me),en=zod.z.object({id:F,type:zod.z.literal("QUERY")}).and(Me),tn=zod.z.object({id:F,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),nn=Z.extend({id:F}),rn=nn,Xe=zod.z.union([Yt,en,tn,rn,Xt]),sn=zod.z.object({id:F,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),on=zod.z.object({id:F,type:zod.z.literal("REPLY"),data:zod.z.any()}),an=Ie.extend({id:F}).superRefine(Ce);zod.z.union([sn,on,an]);zod.z.object({resource:zod.z.string(),data:zod.z.array(be)});var tt=i=>{let e={},t=i.logger;return (n,r)=>{var d;let o=p=>{n.send(JSON.stringify(p));},c=de(),s=new Map,a={headers:r.headers,cookies:typeof r.headers.cookie=="string"?et.default.parse(r.headers.cookie):{}},l=Zt.parse(r.url.split("?")[1]),u=(d=i.contextProvider)==null?void 0:d.call(i,{transport:"WEBSOCKET",headers:a.headers,cookies:a.cookies,queryParams:l});e[c]=n,t.info("Client connected:",c),n.on("message",async p=>{try{t.debug("Message received from the client:",p);let y=Xe.parse(JSON.parse(p.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:f,id:m,...h}=y,T=f==="SUBSCRIBE";try{let R=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h.resource,procedure:h.procedure,input:h.input,context:await u??{},queryParams:l},subscription:T?w=>{var x;!w.resourceId||!w.payload||!Object.keys(w.payload).length||(x=e[c])==null||x.send(JSON.stringify(w));}:void 0});if(T){if(!R||!R.data||!R.query)throw new Error("Cannot subscribe to a one-shot query: the procedure must return a query builder (a Tracked Query), not a computed value");R.unsubscribe&&s.set(U(h),R.unsubscribe),o({id:m,type:"REPLY",data:{resource:R.query.resource,data:(R.data??[]).map(w=>w.value)}});}else o({id:m,type:"REPLY",data:R});}catch(R){o({id:m,type:"REJECT",resource:h.resource,message:R.message}),t.error("Error handling query from the client:",R);}}else if(y.type==="UNSUBSCRIBE"){let{type:f,id:m,...h}=y,T=s.get(U(h));T&&(T(),s.delete(U(h)));}else if(y.type==="CUSTOM_QUERY"){let{resource:f,procedure:m,input:h,id:T}=y;t.debug("Received custom query from client:",y);try{let R=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:f,procedure:m,input:h,context:await u??{},queryParams:l}});o({id:T,type:"REPLY",data:R});}catch(R){o({id:T,type:"REJECT",resource:f,message:R.message}),t.error("Error handling custom query from the client:",R);}}else if(y.type==="MUTATE"){let{resource:f}=y;t.debug("Received mutation from client:",y);try{let m=await i.handleMutation({req:{...a,type:"MUTATE",resource:f,input:y.payload,context:{messageId:y.id,...await u??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:l,meta:y.meta}});o({id:y.id,type:"REPLY",data:m});}catch(m){o({id:y.id,type:"REJECT",resource:f,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",c),delete e[c];for(let p of Array.from(s.values()))p();});}};function nt(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var qr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,tt(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{Ye(e)(nt(n)).then(c=>c.json().then(s=>r.status(c.status).send(s)));});};var Y=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,o,c,s,a){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=o,this._single=c,this._sort=s,this._shouldAwait=a,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new i(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new i(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new i(this._collection,this._client,this._where,this._include,e,this._single,this._sort,this._shouldAwait)}one(e){return this.first({id:e})}first(e){return new i(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new i(this._collection,this._client,this._where,this._include,this._limit,this._single,n,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}buildQueryRequest(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}get(){let e=this._client.get(this.buildQueryRequest());return this._shouldAwait?Promise.resolve(e).then(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,n){return new i(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var ln=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Ae=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>ln(n)?S(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function X(i,e,t){let n=new Ae(i),r=c=>{let s=Y._init(c,n,true);return Object.assign(Object.create(s),{insert:async l=>{let u=i._getTimestamp(),d=await i.rawInsert(c.name,l.id,{value:Object.fromEntries(Object.entries(l).map(([p,y])=>[p,{value:y,_meta:{timestamp:u}}]))},void 0,t);return S(d.data)},update:async(l,u)=>{let d=i._getTimestamp(),{id:p,...y}=u,f=await i.rawUpdate(c.name,l,{value:Object.fromEntries(Object.entries(y).map(([T,R])=>[T,{value:R,_meta:{timestamp:d}}]))},void 0,t),m=S(f.data),h={};for(let T of Object.keys(y))T in m&&(h[T]=m[T]);return h}})},o={get(c,s){if(s==="findOne")return i.findOne.bind(i);if(s==="find")return i.find.bind(i);if(s==="insert")return (a,l)=>{let u=i._getTimestamp();return i.rawInsert(a.name,l.id,{value:Object.fromEntries(Object.entries(l).map(([d,p])=>[d,{value:p,_meta:{timestamp:u}}]))},void 0,t).then(d=>S(d.data))};if(s==="update")return (a,l,u)=>{let d=i._getTimestamp(),{id:p,...y}=u;return i.rawUpdate(a.name,l,{value:Object.fromEntries(Object.entries(y).map(([f,m])=>[f,{value:m,_meta:{timestamp:d}}]))},void 0,t).then(f=>{let m=S(f.data),h={};for(let T of Object.keys(y))T in m&&(h[T]=m[T]);return h})};if(s==="transaction")return async a=>i.transaction(async({trx:l,commit:u,rollback:d})=>{let p=X(l,e,t);return a({trx:p,commit:u,rollback:d})});if(s in e){let a=e[s];return r(a)}}};return new Proxy({},o)}var Oe=class i{routes;schema;constructor(e){this.routes=e.routes,this.schema=e.schema;}static create(e){return new i(e)}},Gr=i=>Oe.create(i),un=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),dn=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),je=class{middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:n})=>{var c;let r=((c=e.meta)==null?void 0:c.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let a=this.customMutations[s.procedure];if(a){let l=a.inputValidator["~standard"].validate(s.input),u=l instanceof Promise?await l:l;if(u.issues){let p=u.issues.map(y=>{var m;let f=(m=y.path)==null?void 0:m.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return f?`${f}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}s.input=u.value;let d=X(o,n,s.context);return a.handler({req:s,db:d})}throw new Error(`Unknown procedure: ${s.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{let o=this.customQueries[r.procedure];if(!o)throw new Error(`Unknown query procedure: ${r.procedure}`);let c=o.inputValidator["~standard"].validate(r.input),s=c instanceof Promise?await c:c;if(s.issues){let l=s.issues.map(u=>{var p;let d=(p=u.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${u.message}`:u.message}).join(", ");throw new Error(`Validation failed: ${l}`)}r.input=s.value;let a=X(t,n,r.context);return o.handler({req:r,db:a})})(e);wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}};function Zr(i){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>i({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var Ee=class i{middlewares;constructor(e=[]){this.middlewares=e;}withProcedures(e){let t=e({mutation:dn,query:un}),n={},r={};for(let[o,c]of Object.entries(t))c._type==="mutation"?n[o]=c:r[o]=c;return new je(n,r).use(...this.middlewares)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new i([...this.middlewares,...t])}static create(){return new i}},Yr=Ee.create;var ee=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([o,c])=>[o,{value:c,_meta:{timestamp:n}}]))});return S(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:o,...c}=n,s=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(c).map(([u,d])=>[u,{value:d,_meta:{timestamp:r}}]))}),a=S(s.data),l={};for(let u of Object.keys(c))u in a&&(l[u]=a[u]);return l}};var gn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function k(i){var r,o,c;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((c=(o=t.constructor)==null?void 0:o.name)==null?void 0:c.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function it(i){let e=k(i);return gn[e]}var xn="42701";function te(i){var t;if(i.code===xn)return true;let e=((t=i.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function Ne(i,e){let{type:t,enumValues:n,enumName:r}=i;if(n&&n.length>0)return e==="postgres"&&r?r:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function Rn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let o of Object.values(e))for(let c of Object.values(o.fields)){let s=c.getStorageFieldType();s.enumValues&&s.enumName&&r.set(s.enumName,{name:s.enumName,values:s.enumValues});}for(let o of Array.from(r.values())){let{name:c,values:s}=o;try{let a=s.map(l=>`'${l}'`).join(", ");await kysely.sql`
|
|
2
2
|
DO $$ BEGIN
|
|
3
|
-
CREATE TYPE ${kysely.sql.id(
|
|
3
|
+
CREATE TYPE ${kysely.sql.id(c)} AS ENUM (${kysely.sql.raw(a)});
|
|
4
4
|
EXCEPTION
|
|
5
5
|
WHEN duplicate_object THEN null;
|
|
6
6
|
END $$;
|
|
7
|
-
`.execute(i);}catch(
|
|
7
|
+
`.execute(i);}catch(a){n==null||n.warn("Could not create enum type",c,a);}}}function ne(i,e){return i.some(t=>t.name===e)}function Sn(i,e){return (i==null?void 0:i.columns.some(t=>t.name===e))??false}function Ve(i,e){let[t]=e.split(".");return ne(i,t)}function Pe(i,e,t,n=false){let r=i;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&Ve(t,e.references)&&(r=r.references(e.references)),r}function vn(i,e,t,n,r){let o=[];for(let[c,s]of Object.entries(i.fields)){let a=e==null?void 0:e.columns.find(u=>u.name===c),l=s.getStorageFieldType();a?(a.dataType,l.type):(o.push({name:c,storageFieldType:l}),l.references&&!Ve(t,l.references)&&n.push({tableName:r,columnName:c,references:l.references}));}return o}function st(i,e){return e==="postgres"&&!!i.enumValues&&i.enumValues.length>0&&!!i.enumName}async function wn(i,e,t,n,r,o){if(t.length===0)return;let c=i.schema.createTable(e);for(let{name:s,storageFieldType:a}of t)if(st(a,r))c=c.addColumn(s,kysely.sql.raw(a.enumName),l=>Pe(l,a,n));else {let l=Ne(a,r);c=c.addColumn(s,l,u=>Pe(u,a,n));}await c.execute().catch(s=>{if(!te(s))throw o==null||o.error("Error creating table",e,s),s});}async function bn(i,e,t,n,r,o,c){for(let{name:s,storageFieldType:a}of t){let l=a.references?Ve(n,a.references):false,u=st(a,o)?kysely.sql.raw(a.enumName):Ne(a,o);await i.schema.alterTable(e).addColumn(s,u,d=>Pe(d,a,n,!l)).execute().catch(d=>{if(!te(d))throw c==null||c.error("Error adding column",s,d),d}),a.references&&!l&&!r.some(d=>d.tableName===e&&d.columnName===s)&&r.push({tableName:e,columnName:s,references:a.references}),a.index&&await i.schema.createIndex(`${e}_${s}_index`).on(e).column(s).execute().catch(()=>{});}}async function In(i,e,t,n,r,o){let c=`${e}_meta`,s=[];for(let[a,l]of Object.entries(t.fields)){let u=l.getStorageFieldType();Sn(n,a)||s.push({name:a,storageFieldType:u});}if(!n&&s.length>0){let a=i.schema.createTable(c);for(let{name:l,storageFieldType:u}of s)a=a.addColumn(l,"varchar",d=>{let p=d;return u.primary&&(p=p.primaryKey(),ne(r,e)&&(p=p.references(`${e}.${l}`))),p});await a.execute().catch(l=>{if(!te(l))throw o==null||o.error("Error creating meta table",c,l),l});}else if(n)for(let{name:a,storageFieldType:l}of s)await i.schema.alterTable(c).addColumn(a,"varchar",u=>{let d=u;return l.primary&&(d=d.primaryKey(),ne(r,e)&&(d=d.references(`${e}.${a}`))),d}).execute().catch(u=>{if(!te(u))throw o==null||o.error("Error adding meta column",a,u),u});}async function ot(i,e,t,n,r){let[o,c]=n.split("."),s=`${e}_${t}_fk`;try{await kysely.sql`
|
|
8
8
|
ALTER TABLE ${kysely.sql.id(e)}
|
|
9
|
-
ADD CONSTRAINT ${kysely.sql.id(
|
|
9
|
+
ADD CONSTRAINT ${kysely.sql.id(s)}
|
|
10
10
|
FOREIGN KEY (${kysely.sql.id(t)})
|
|
11
|
-
REFERENCES ${kysely.sql.id(
|
|
12
|
-
`.execute(i);}catch(s){te(s)||r==null||r.warn("Could not add foreign key constraint",e,t,n,s);}}async function Pn(i,e,t,n){for(let{tableName:r,columnName:a,references:u}of e){let o=t.find(l=>l.name===r),s=o==null?void 0:o.columns.find(l=>l.name===a),[c]=u.split(".");o&&s&&ne(t,c)&&await Tt(i,r,a,u,n);}}async function Nn(i,e,t,n){for(let[r,a]of Object.entries(e)){let u=`${r}_meta`,o=t.find(s=>s.name===u);if(o)for(let[s,c]of Object.entries(a.fields)){let l=c.getStorageFieldType(),d=o.columns.find(y=>y.name===s);l.primary&&d&&ne(t,r)&&await Tt(i,u,s,`${r}.${s}`,n);}}}async function gt(i,e,t){let n=D(i),r=await i.introspection.getTables(),a=[];await Cn(i,e,n,t);for(let[o,s]of Object.entries(e)){let c=r.find(y=>y.name===o),l=r.find(y=>y.name===`${o}_meta`),d=An(s,c,r,a,o);if(c)for(let[y,p]of Object.entries(s.fields)){let f=c.columns.find(g=>g.name===y),m=p.getStorageFieldType(),h=_e(m,n);f&&f.dataType!==h&&(t==null||t.warn("Column type mismatch:",y,"expected to have type:",h,"but has type:",f.dataType));}!c&&d.length>0?await jn(i,o,d,r,n,t):c&&await En(i,o,d,r,a,n,t),await On(i,o,s,l,r,t);}let u=await i.introspection.getTables();await Pn(i,a,u,t),await Nn(i,e,u,t);}function Re(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 a=n.$or,u=n.$and;return (a?t.or:t.and)(a?n.$or.map(o=>Re(i,e,t,o)):u?n.$and.map(o=>Re(i,e,t,o)):Object.entries(n).map(([o,s])=>{var c,l;if(r.fields[o])return (s==null?void 0:s.$eq)!==void 0?t(`${e}.${o}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?t(`${e}.${o}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((c=s==null?void 0:s.$not)==null?void 0:c.$in)!==void 0?t(`${e}.${o}`,"not in",s.$not.$in):((l=s==null?void 0:s.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${o}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):t(`${e}.${o}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?t(`${e}.${o}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?t(`${e}.${o}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?t(`${e}.${o}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?t(`${e}.${o}`,"<=",s.$lte):t(`${e}.${o}`,s===null?"is":"=",s);if(r.relations[o]){let d=r.relations[o],y=d.entity.name;return d.type==="many"?t.exists(xe(i,y,t.selectFrom(y).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),s)):Re(i,y,t,s)}return null}).filter(Boolean))}function be(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 a of n.$and)t=be(i,e,t,a);return t}else if(n.$or){for(let a of n.$or)t=be(i,e,t,a);return t}for(let[a,u]of Object.entries(n)){if(!r.relations[a])continue;let o=r.relations[a],s=o.entity.name,c=o.type==="one"?"id":o.foreignColumn,l=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(s,`${s}.${c}`,`${e}.${l}`),u instanceof Object&&!Array.isArray(u)&&u!==null&&(t=be(i,s,t,u));}return t}function xe(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=be(i,e,t,n),t.where(r=>Re(i,e,r,n)))}function Vn(i,e,t,n,r){let a=D(r),u=e[t];if(a==="sqlite"&&(u!=null&&u.fields)){let o=Object.keys(u.fields),s=i.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return i.selectFrom(n).selectAll(n)}function kn(i,e,t,n,r){let a=D(r),u=e[t];if(a==="sqlite"&&(u!=null&&u.fields)){let o=Object.keys(u.fields),s=i.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return i.selectFrom(n).selectAll(n)}function Se(i,e,t,n,r,a){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:o,jsonArrayFrom:s}=r;for(let c of Object.keys(n)){if(!u.relations[c])throw new Error(`Relation ${c} not found in resource ${e}`);let l=u.relations[c],d=l.entity.name,y=n[c],p=l.type==="one"?"id":l.foreignColumn,f=l.type==="one"?l.relationalColumn:"id",m=l.type==="one"?o:s,h=pe(y)?y:null,g=h==null?void 0:h.include;t=t.select(T=>{let b=`${d}_meta`,R=kn(T,i,d,d,a).whereRef(`${d}.${p}`,"=",`${e}.${f}`).select(x=>o(Vn(x,i,d,b,a).whereRef(`${b}.id`,"=",`${d}.id`)).as("_meta"));if(h!=null&&h.where&&(R=xe(i,d,R,h.where)),h!=null&&h.orderBy)for(let x of h.orderBy)R=R.orderBy(`${d}.${x.key}`,x.direction);return (h==null?void 0:h.limit)!==void 0&&(R=R.limit(h.limit)),g&&Object.keys(g).length>0&&(R=Se(i,d,R,g,r,a)),m(R).as(c)});}return t}var Be=class i extends ee{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,n,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.dialectHelpers=ft(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 gt(this.db,e,t);}selectMetaColumns(e,t,n){var u;let r=D(this.db),a=(u=this.schema)==null?void 0:u[t];if(r==="sqlite"&&(a!=null&&a.fields)){let o=Object.keys(a.fields),s=e.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,a=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(s,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));a=Se(this.schema,e,a,n,this.dialectHelpers,this.db);let u=await a.executeTakeFirst();if(!u)return;let o=this.parseRelationalJsonStrings(u,e);return this.convertToMaterializedLiveType(o,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return w(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:a,sort:u}=e,o=`${t}_meta`,s=this.db.selectFrom(t).selectAll(t).select(l=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(l,t,o).whereRef(`${o}.id`,"=",`${t}.id`)).as("_meta"));s=xe(this.schema,t,s,n),s=Se(this.schema,t,s,r,this.dialectHelpers,this.db),a!==void 0&&(s=s.limit(a)),u!==void 0&&u.forEach(l=>{s=s.orderBy(l.key,l.direction);});let c=await s.execute();return c.length===0?[]:c.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(r=>w(r))}async rawInsert(e,t,n,r,a){var m,h,g,T,b,R,x,S,v,C,A;let u=(m=this.server)==null?void 0:m.getHooks(e),o=(h=this.schema)==null?void 0:h[e],[s,c]=((g=o==null?void 0:o.mergeMutation)==null?void 0:g.call(o,"set",n.value,void 0))??[n,n.value];if(!c)return {data:n,acceptedValues:null};let l=s,d={...l,value:{...l.value,id:{value:t}}};if(u!=null&&u.beforeInsert){let O=w(d);O.id=t;let I=await u.beforeInsert({ctx:a,value:O,rawValue:d,db:this});I&&(l=I);}let y={},p={};for(let[O,I]of Object.entries(l.value)){let j=(T=I._meta)==null?void 0:T.timestamp;if(!j)continue;let E=(R=(b=o==null?void 0:o.fields[O])==null?void 0:b.getStorageFieldType)==null?void 0:R.call(b);(E==null?void 0:E.type)==="jsonb"||(E==null?void 0:E.type)==="json"?y[O]=JSON.stringify(I.value):y[O]=I.value,p[O]=j;}await this.db.insertInto(e).values({...y,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...p,id:t}).execute(),(S=(x=this.logger)==null?void 0:x.debug)==null||S.call(x,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(a==null?void 0:a.messageId)??"(none)",hasContext:!!a,contextKeys:a?Object.keys(a):[]});let f=this.buildMutation(e,t,"INSERT",l,r,a==null?void 0:a.messageId);if(f&&((A=(v=this.logger)==null?void 0:v.debug)==null||A.call(v,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:((C=f.meta)==null?void 0:C.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,l)),u!=null&&u.afterInsert){let O={...l,value:{...l.value,id:{value:t}}},I=w(O);I.id=t,await u.afterInsert({ctx:a,value:I,rawValue:O,db:this});}return {data:l,acceptedValues:c}}async rawUpdate(e,t,n,r,a){var h,g,T,b,R,x,S,v,C,A,O;let u=(h=this.server)==null?void 0:h.getHooks(e),o=(g=this.schema)==null?void 0:g[e],s=await this.rawFindById(e,t),[c,l]=((T=o==null?void 0:o.mergeMutation)==null?void 0:T.call(o,"set",n.value,s))??[n,n.value];if(!l)return {data:n,acceptedValues:null};let d=c,y={...d,value:{...d.value,id:{value:t}}};if(u!=null&&u.beforeUpdate){let I=w(y);I.id=t;let j;if(s){let P={...s,value:{...s.value,id:{value:t}}};j=w(P),j.id=t;}let E=await u.beforeUpdate({ctx:a,value:I,rawValue:y,previousValue:j,previousRawValue:s,db:this});E&&(d=E);}let p={},f={};for(let[I,j]of Object.entries(d.value)){let E=(b=j._meta)==null?void 0:b.timestamp;if(!E)continue;let P=(x=(R=o==null?void 0:o.fields[I])==null?void 0:R.getStorageFieldType)==null?void 0:x.call(R);(P==null?void 0:P.type)==="jsonb"||(P==null?void 0:P.type)==="json"?p[I]=JSON.stringify(j.value):p[I]=j.value,f[I]=E;}if(Object.keys(p).length===0)return {data:d,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(p).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(I=>I.column("id").doUpdateSet(f)).execute()]),(v=(S=this.logger)==null?void 0:S.debug)==null||v.call(S,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(a==null?void 0:a.messageId)??"(none)",hasContext:!!a,contextKeys:a?Object.keys(a):[]});let m=this.buildMutation(e,t,"UPDATE",d,r,a==null?void 0:a.messageId);if(m){(O=(C=this.logger)==null?void 0:C.debug)==null||O.call(C,"[rawUpdate] Mutation built, tracking",{mutationId:m.id,hasMeta:!!m.meta,originMutationId:((A=m.meta)==null?void 0:A.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let I=await this.rawFindById(e,t);I&&this.trackMutation(m,I);}if(u!=null&&u.afterUpdate){let I=await this.rawFindById(e,t);if(I){let j={...I,value:{...I.value,id:{value:t}}},E=w(j);E.id=t;let P;if(s){let Z={...s,value:{...s.value,id:{value:t}}};P=w(Z),P.id=t;}await u.afterUpdate({ctx:a,value:E,rawValue:j,previousValue:P,previousRawValue:s,db:this});}}return {data:d,acceptedValues:l}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let a=Math.random().toString(36).substring(2,15),u=this.mutationStack,o=[];this.mutationStack=o;let s=await this.db.savepoint(a).execute(),c=false,l=false;try{return await e({trx:this,commit:async()=>{await s.releaseSavepoint(a).execute(),c=!0,u.push(...o);},rollback:async()=>{await s.rollbackToSavepoint(a).execute(),l=!0,o.length=0;}}).then(d=>s.isCommitted||s.isRolledBack||c||l?d:s.releaseSavepoint(a).execute().then(()=>(u.push(...o),d)))}catch(d){throw l||await s.rollbackToSavepoint(a).execute().catch(()=>{}),o.length=0,d}finally{this.mutationStack=u;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let a=new i(r,this.schema,this.logger,this.server);return a.mutationStack=t,await e({trx:a,commit:async()=>{var u,o;await r.commit().execute(),(o=(u=this.logger)==null?void 0:u.debug)==null||o.call(u,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:s})=>{var c;return {id:s.id,resource:s.resource,resourceId:s.resourceId,procedure:s.procedure,hasMeta:!!s.meta,originMutationId:((c=s.meta)==null?void 0:c.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(u=>r.isCommitted||r.isRolledBack?u:r.commit().execute().then(()=>{var o,s;return (s=(o=this.logger)==null?void 0:o.debug)==null||s.call(o,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:c})=>{var l;return {id:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure,hasMeta:!!c.meta,originMutationId:((l=c.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t),u}))}catch(a){throw await r.rollback().execute(),t.length=0,a}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 a,u;if(D(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(o=>this.parseRelationalJsonStrings(o,t));let r={};for(let[o,s]of Object.entries(e))if(o==="_meta"&&typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{r[o]=JSON.parse(s);}catch{r[o]=s;}else r[o]=s;else if(this.isRelationalField(t,o))if(typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{let c=JSON.parse(s);if(this.schema){let l=this.schema[t],d=(a=l==null?void 0:l.relations)==null?void 0:a[o];if(d){let y=d.entity.name;r[o]=this.parseRelationalJsonStrings(c,y);}else r[o]=c;}else r[o]=c;}catch{r[o]=s;}else r[o]=s;else if(typeof s=="object"&&s!==null&&!Array.isArray(s))if(this.schema){let c=this.schema[t],l=(u=c==null?void 0:c.relations)==null?void 0:u[o];if(l){let d=l.entity.name;r[o]=this.parseRelationalJsonStrings(s,d);}else r[o]=s;}else r[o]=s;else Array.isArray(s)?r[o]=s.map(c=>{var l,d;if(typeof c=="string")try{let y=JSON.parse(c);if(this.schema){let p=this.schema[t],f=(l=p==null?void 0:p.relations)==null?void 0:l[o];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(y,m)}}return y}catch{return c}if(typeof c=="object"&&c!==null&&this.schema){let y=this.schema[t],p=(d=y==null?void 0:y.relations)==null?void 0:d[o];if(p){let f=p.entity.name;return this.parseRelationalJsonStrings(c,f)}}return c}):r[o]=s;else r[o]=s;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((a,[u,o])=>{var d,y,p,f,m,h,g,T,b;if(u==="_meta")return a;let s=(y=(d=n==null?void 0:n.fields[u])==null?void 0:d.getStorageFieldType)==null?void 0:y.call(d),c=(s==null?void 0:s.type)==="jsonb"||(s==null?void 0:s.type)==="json",l=(n==null?void 0:n.relations)&&u in n.relations;if(u==="id")a[u]={value:o};else if(c)a[u]={value:o,_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[u]}};else if(l){let R=n.relations[u].entity,x=(R==null?void 0:R.name)??t;Array.isArray(o)?a[u]={value:o.map(S=>this.convertToMaterializedLiveType(S,x)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[u],relation:true}}:o!==null&&typeof o=="object"?a[u]={...this.convertToMaterializedLiveType(o,x),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[u],relation:true}}:a[u]={value:o,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[u],relation:true}};}else Array.isArray(o)?a[u]={value:o,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[u]}}:typeof o=="object"&&o!==null&&!(o instanceof Date)?a[u]={value:o,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[u]}}:a[u]={value:o,_meta:{timestamp:(b=e==null?void 0:e._meta)==null?void 0:b[u]}};return a},{})}}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",a=typeof t.savepoint=="function",u=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||a&&u}buildMutation(e,t,n,r,a,u){var s;let o={};for(let[c,l]of Object.entries(r.value)){if(c==="id")continue;let d=(s=l._meta)==null?void 0:s.timestamp;d&&(o[c]={value:l.value,_meta:{timestamp:d}});}return Object.keys(o).length===0?null:{id:a??de(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:o,meta:u?{originMutationId:u}:void 0}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let n=e;for(let r of n)this.server.notifySubscribers(r,t);}else {let n=e;for(let{mutation:r,entityData:a}of n)this.server.notifySubscribers(r,a);}}};var ze=class i{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var r;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=Ye({level:e.logLevel??_.INFO}),(r=e.middlewares)==null||r.forEach(a=>{this.middlewares.add(a);});let t=this.router.hooksRegistry,n=new Set;if(t&&t.forEach((a,u)=>{n.add(u);}),e.hooks)for(let a of Object.keys(e.hooks))n.add(a);n.forEach(a=>{var c;let u=t==null?void 0:t.get(a),o=(c=e.hooks)==null?void 0:c[a],s=Ae([u,o]);s&&this.hooksRegistry.set(a,s);}),this.initPromise=this.storage.init(this.schema,this.logger,this).catch(a=>{this.initError=a;}),this.contextProvider=e.contextProvider,this.queryEngine=new me({router:{get:async(a,u)=>{var p;let{headers:o,cookies:s,queryParams:c,context:l}=(u==null?void 0:u.context)??{};if(!(u!=null&&u.batcher))throw new Error("Batcher is required");let d={...a,type:"QUERY",headers:o,cookies:s,queryParams:c,context:l},y=await((p=this.router.routes[a.resource])==null?void 0:p.handleQuery({req:d,batcher:u.batcher}));return (y==null?void 0:y.data)??[]},incrementQueryStep:(a,u={})=>{var c;let o=(c=this.router.routes[a.query.resource])==null?void 0:c.getAuthorizationClause({...a.query,type:"QUERY",headers:u.headers,cookies:u.cookies,queryParams:u.queryParams,context:u.context});if(typeof o=="boolean"&&!o)throw new Error("Not authorized");let s=J(a.query.where,typeof o=="object"?o:void 0);return {...a,query:{...a.query,where:s}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleQuery(e){return await this.ensureInitialized(),this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:a,context:u,...o}=t,s={headers:n,cookies:r,queryParams:a,context:u},c=e.subscription?this.queryEngine.subscribe(o,d=>{var y;(y=e.subscription)==null||y.call(e,d);},s):void 0;return {data:await this.queryEngine.get(o,{context:s}),unsubscribe:c}})(e.req)}async handleMutation(e){return await this.ensureInitialized(),await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async y=>{let p=this.router.routes[y.resource];if(!p)throw new Error("Invalid resource");return p.handleCustomQuery({req:y,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:r,cookies:a,queryParams:u,context:o}=e.req,s={headers:r,cookies:a,queryParams:u,context:o},c=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(c,y=>{var p;(p=e.subscription)==null||p.call(e,y);},s):void 0,d=await this.queryEngine.get(c,{context:s});return e.subscription?{data:d,unsubscribe:l,query:c}:d.map(y=>w(y))}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}notifySubscribers(e,t){this.queryEngine.handleMutation(e,t);}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>a=>r({req:a,next:n}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},Di=ze.create;exports.ProcedureRoute=qe;exports.Route=Qe;exports.RouteFactory=$e;exports.Router=ke;exports.SQLStorage=Be;exports.Server=ze;exports.Storage=ee;exports.createMiddleware=ui;exports.createServerDB=K;exports.defineHooks=vr;exports.expressAdapter=Zr;exports.mergeEntityHooks=Ae;exports.mergeHooks=wr;exports.routeFactory=ci;exports.router=oi;exports.server=Di;
|
|
11
|
+
REFERENCES ${kysely.sql.id(o)} (${kysely.sql.id(c)})
|
|
12
|
+
`.execute(i);}catch(a){te(a)||r==null||r.warn("Could not add foreign key constraint",e,t,n,a);}}async function Cn(i,e,t,n){for(let{tableName:r,columnName:o,references:c}of e){let s=t.find(u=>u.name===r),a=s==null?void 0:s.columns.find(u=>u.name===o),[l]=c.split(".");s&&a&&ne(t,l)&&await ot(i,r,o,c,n);}}async function Ln(i,e,t,n){for(let[r,o]of Object.entries(e)){let c=`${r}_meta`,s=t.find(a=>a.name===c);if(s)for(let[a,l]of Object.entries(o.fields)){let u=l.getStorageFieldType(),d=s.columns.find(p=>p.name===a);u.primary&&d&&ne(t,r)&&await ot(i,c,a,`${r}.${a}`,n);}}}async function at(i,e,t){let n=k(i),r=await i.introspection.getTables(),o=[];await Rn(i,e,n,t);for(let[s,a]of Object.entries(e)){let l=r.find(p=>p.name===s),u=r.find(p=>p.name===`${s}_meta`),d=vn(a,l,r,o,s);if(l)for(let[p,y]of Object.entries(a.fields)){let f=l.columns.find(T=>T.name===p),m=y.getStorageFieldType(),h=Ne(m,n);f&&f.dataType!==h&&(t==null||t.warn("Column type mismatch:",p,"expected to have type:",h,"but has type:",f.dataType));}!l&&d.length>0?await wn(i,s,d,r,n,t):l&&await bn(i,s,d,r,o,n,t),await In(i,s,a,u,r,t);}let c=await i.introspection.getTables();await Cn(i,o,c,t),await Ln(i,e,c,t);}function fe(i,e,t,n){if(!i)throw new Error("Schema not initialized");let r=i[e];if(!r)throw new Error("Resource not found");let o=n.$or,c=n.$and;return (o?t.or:t.and)(o?n.$or.map(s=>fe(i,e,t,s)):c?n.$and.map(s=>fe(i,e,t,s)):Object.entries(n).map(([s,a])=>{var l,u;if(r.fields[s])return (a==null?void 0:a.$eq)!==void 0?t(`${e}.${s}`,a.$eq===null?"is":"=",a.$eq):(a==null?void 0:a.$in)!==void 0?t(`${e}.${s}`,"in",a.$in):(a==null?void 0:a.$not)!==void 0?((l=a==null?void 0:a.$not)==null?void 0:l.$in)!==void 0?t(`${e}.${s}`,"not in",a.$not.$in):((u=a==null?void 0:a.$not)==null?void 0:u.$eq)!==void 0?t(`${e}.${s}`,a.$not.$eq===null?"is not":"!=",a.$not.$eq):t(`${e}.${s}`,a.$not===null?"is not":"!=",a.$not):(a==null?void 0:a.$gt)!==void 0?t(`${e}.${s}`,">",a.$gt):(a==null?void 0:a.$gte)!==void 0?t(`${e}.${s}`,">=",a.$gte):(a==null?void 0:a.$lt)!==void 0?t(`${e}.${s}`,"<",a.$lt):(a==null?void 0:a.$lte)!==void 0?t(`${e}.${s}`,"<=",a.$lte):t(`${e}.${s}`,a===null?"is":"=",a);if(r.relations[s]){let d=r.relations[s],p=d.entity.name;return d.type==="many"?t.exists(he(i,p,t.selectFrom(p).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),a)):fe(i,p,t,a)}return null}).filter(Boolean))}function me(i,e,t,n,r=new Set){let o=i[e];if(!o)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let c of n.$and)t=me(i,e,t,c,r);return t}else if(n.$or){for(let c of n.$or)t=me(i,e,t,c,r);return t}for(let[c,s]of Object.entries(n)){if(!o.relations[c])continue;let a=o.relations[c],l=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,d=a.type==="one"?a.relationalColumn:"id";r.has(l)||(r.add(l),t=t.leftJoin(l,`${l}.${u}`,`${e}.${d}`)),s instanceof Object&&!Array.isArray(s)&&s!==null&&(t=me(i,l,t,s,r));}return t}function he(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=me(i,e,t,n),t.where(r=>fe(i,e,r,n)))}function Mn(i,e,t,n,r){let o=k(r),c=e[t];if(o==="sqlite"&&(c!=null&&c.fields)){let s=Object.keys(c.fields),a=i.selectFrom(n);for(let l of s)a=a.select(`${n}.${l}`);return a}return i.selectFrom(n).selectAll(n)}function An(i,e,t,n,r){let o=k(r),c=e[t];if(o==="sqlite"&&(c!=null&&c.fields)){let s=Object.keys(c.fields),a=i.selectFrom(n);for(let l of s)a=a.select(`${n}.${l}`);return a}return i.selectFrom(n).selectAll(n)}function ke(i,e,t,n){var r,o;for(let c of n){let s=c.key.indexOf(".");if(s!==-1){let a=c.key.slice(0,s),l=c.key.slice(s+1),u=(o=(r=i==null?void 0:i[e])==null?void 0:r.relations)==null?void 0:o[a];if((u==null?void 0:u.type)==="one"&&u.relationalColumn){let d=u.entity.name,p=String(u.relationalColumn);t=t.orderBy(y=>y.selectFrom(d).select(`${d}.${l}`).whereRef(`${d}.id`,"=",`${e}.${p}`),c.direction);continue}if(u)throw new Error(`Relational sort on "${c.key}" is only supported for "one" relations with a relationalColumn`)}t=t.orderBy(c.key,c.direction);}return t}function Te(i,e,t,n,r,o){if(!n)return t;if(!i)throw new Error("Schema not initialized");let c=i[e];if(!c)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:s,jsonArrayFrom:a}=r;for(let l of Object.keys(n)){if(!c.relations[l])throw new Error(`Relation ${l} not found in resource ${e}`);let u=c.relations[l],d=u.entity.name,p=n[l],y=u.type==="one"?"id":u.foreignColumn,f=u.type==="one"?u.relationalColumn:"id",m=u.type==="one"?s:a,h=H(p)?p:null,T=h?h.include:p&&typeof p=="object"?p:void 0;t=t.select(R=>{let w=`${d}_meta`,x=An(R,i,d,d,o).whereRef(`${d}.${y}`,"=",`${e}.${f}`).select(C=>s(Mn(C,i,d,w,o).whereRef(`${w}.id`,"=",`${d}.id`)).as("_meta"));return h!=null&&h.where&&(x=he(i,d,x,h.where)),h!=null&&h.orderBy&&(x=ke(i,d,x,h.orderBy)),(h==null?void 0:h.limit)!==void 0&&(x=x.limit(h.limit)),T&&Object.keys(T).length>0&&(x=Te(i,d,x,T,r,o)),m(x).as(l)});}return t}var De=class i extends ee{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,n,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.dialectHelpers=it(this.db),this.schema=t,this.logger=n,this.server=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,n){this.schema=e,this.logger=t,this.server=n,await at(this.db,e,t);}selectMetaColumns(e,t,n){var c;let r=k(this.db),o=(c=this.schema)==null?void 0:c[t];if(r==="sqlite"&&(o!=null&&o.fields)){let s=Object.keys(o.fields),a=e.selectFrom(n);for(let l of s)a=a.select(`${n}.${l}`);return a}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,o=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(a=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(a,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));o=Te(this.schema,e,o,n,this.dialectHelpers,this.db);let c=await o.executeTakeFirst();if(!c)return;let s=this.parseRelationalJsonStrings(c,e);return this.convertToMaterializedLiveType(s,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return S(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:o,sort:c}=e,s=`${t}_meta`,a=this.db.selectFrom(t).selectAll(t).select(u=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(u,t,s).whereRef(`${s}.id`,"=",`${t}.id`)).as("_meta"));a=he(this.schema,t,a,n),a=Te(this.schema,t,a,r,this.dialectHelpers,this.db),o!==void 0&&(a=a.limit(o)),c!==void 0&&(a=ke(this.schema,t,a,c));let l=await a.execute();return l.length===0?[]:l.map(u=>{let d=this.parseRelationalJsonStrings(u,t);return this.convertToMaterializedLiveType(d,t)})}async find(e,t){return (await this.get({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort})).map(r=>S(r))}async rawInsert(e,t,n,r,o){var m,h,T,R,w,x,C,O,_,Q,z;let c=(m=this.server)==null?void 0:m.getHooks(e),s=(h=this.schema)==null?void 0:h[e],[a,l]=((T=s==null?void 0:s.mergeMutation)==null?void 0:T.call(s,"set",n.value,void 0))??[n,n.value];if(!l)return {data:n,acceptedValues:null};let u=a,d={...u,value:{...u.value,id:{value:t}}};if(c!=null&&c.beforeInsert){let L=S(d);L.id=t;let v=await c.beforeInsert({ctx:o,value:L,rawValue:d,db:this});v&&(u=v);}let p={},y={};for(let[L,v]of Object.entries(u.value)){let M=(R=v._meta)==null?void 0:R.timestamp;if(!M)continue;let I=(x=(w=s==null?void 0:s.fields[L])==null?void 0:w.getStorageFieldType)==null?void 0:x.call(w);(I==null?void 0:I.type)==="jsonb"||(I==null?void 0:I.type)==="json"?p[L]=JSON.stringify(v.value):p[L]=v.value,y[L]=M;}await this.db.insertInto(e).values({...p,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute(),(O=(C=this.logger)==null?void 0:C.debug)==null||O.call(C,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(o==null?void 0:o.messageId)??"(none)",hasContext:!!o,contextKeys:o?Object.keys(o):[]});let f=this.buildMutation(e,t,"INSERT",u,r,o==null?void 0:o.messageId);if(f&&((z=(_=this.logger)==null?void 0:_.debug)==null||z.call(_,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:((Q=f.meta)==null?void 0:Q.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,u)),c!=null&&c.afterInsert){let L={...u,value:{...u.value,id:{value:t}}},v=S(L);v.id=t,await c.afterInsert({ctx:o,value:v,rawValue:L,db:this});}return {data:u,acceptedValues:l}}async rawUpdate(e,t,n,r,o){var h,T,R,w,x,C,O,_,Q,z,L;let c=(h=this.server)==null?void 0:h.getHooks(e),s=(T=this.schema)==null?void 0:T[e],a=await this.rawFindById(e,t),[l,u]=((R=s==null?void 0:s.mergeMutation)==null?void 0:R.call(s,"set",n.value,a))??[n,n.value];if(!u)return {data:n,acceptedValues:null};let d=l,p={...d,value:{...d.value,id:{value:t}}};if(c!=null&&c.beforeUpdate){let v=S(p);v.id=t;let M;if(a){let A={...a,value:{...a.value,id:{value:t}}};M=S(A),M.id=t;}let I=await c.beforeUpdate({ctx:o,value:v,rawValue:p,previousValue:M,previousRawValue:a,db:this});I&&(d=I);}let y={},f={};for(let[v,M]of Object.entries(d.value)){let I=(w=M._meta)==null?void 0:w.timestamp;if(!I)continue;let A=(C=(x=s==null?void 0:s.fields[v])==null?void 0:x.getStorageFieldType)==null?void 0:C.call(x);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?y[v]=JSON.stringify(M.value):y[v]=M.value,f[v]=I;}if(Object.keys(y).length===0)return {data:d,acceptedValues:u};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(v=>v.column("id").doUpdateSet(f)).execute()]),(_=(O=this.logger)==null?void 0:O.debug)==null||_.call(O,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(o==null?void 0:o.messageId)??"(none)",hasContext:!!o,contextKeys:o?Object.keys(o):[]});let m=this.buildMutation(e,t,"UPDATE",d,r,o==null?void 0:o.messageId);if(m){(L=(Q=this.logger)==null?void 0:Q.debug)==null||L.call(Q,"[rawUpdate] Mutation built, tracking",{mutationId:m.id,hasMeta:!!m.meta,originMutationId:((z=m.meta)==null?void 0:z.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let v=await this.rawFindById(e,t);v&&this.trackMutation(m,v);}if(c!=null&&c.afterUpdate){let v=await this.rawFindById(e,t);if(v){let M={...v,value:{...v.value,id:{value:t}}},I=S(M);I.id=t;let A;if(a){let lt={...a,value:{...a.value,id:{value:t}}};A=S(lt),A.id=t;}await c.afterUpdate({ctx:o,value:I,rawValue:M,previousValue:A,previousRawValue:a,db:this});}}return {data:d,acceptedValues:u}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let o=Math.random().toString(36).substring(2,15),c=this.mutationStack,s=[];this.mutationStack=s;let a=await this.db.savepoint(o).execute(),l=false,u=false;try{return await e({trx:this,commit:async()=>{await a.releaseSavepoint(o).execute(),l=!0,c.push(...s);},rollback:async()=>{await a.rollbackToSavepoint(o).execute(),u=!0,s.length=0;}}).then(d=>a.isCommitted||a.isRolledBack||l||u?d:a.releaseSavepoint(o).execute().then(()=>(c.push(...s),d)))}catch(d){throw u||await a.rollbackToSavepoint(o).execute().catch(()=>{}),s.length=0,d}finally{this.mutationStack=c;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let o=new i(r,this.schema,this.logger,this.server);return o.mutationStack=t,await e({trx:o,commit:async()=>{var c,s;await r.commit().execute(),(s=(c=this.logger)==null?void 0:c.debug)==null||s.call(c,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:a})=>{var l;return {id:a.id,resource:a.resource,resourceId:a.resourceId,op:a.op,hasMeta:!!a.meta,originMutationId:((l=a.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(c=>r.isCommitted||r.isRolledBack?c:r.commit().execute().then(()=>{var s,a;return (a=(s=this.logger)==null?void 0:s.debug)==null||a.call(s,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:l})=>{var u;return {id:l.id,resource:l.resource,resourceId:l.resourceId,op:l.op,hasMeta:!!l.meta,originMutationId:((u=l.meta)==null?void 0:u.originMutationId)??"(none)"}})}),this.notifyMutations(t),c}))}catch(o){throw await r.rollback().execute(),t.length=0,o}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var o,c;if(k(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(s=>this.parseRelationalJsonStrings(s,t));let r={};for(let[s,a]of Object.entries(e))if(s==="_meta"&&typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{r[s]=JSON.parse(a);}catch{r[s]=a;}else r[s]=a;else if(this.isRelationalField(t,s))if(typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{let l=JSON.parse(a);if(this.schema){let u=this.schema[t],d=(o=u==null?void 0:u.relations)==null?void 0:o[s];if(d){let p=d.entity.name;r[s]=this.parseRelationalJsonStrings(l,p);}else r[s]=l;}else r[s]=l;}catch{r[s]=a;}else r[s]=a;else if(typeof a=="object"&&a!==null&&!Array.isArray(a))if(this.schema){let l=this.schema[t],u=(c=l==null?void 0:l.relations)==null?void 0:c[s];if(u){let d=u.entity.name;r[s]=this.parseRelationalJsonStrings(a,d);}else r[s]=a;}else r[s]=a;else Array.isArray(a)?r[s]=a.map(l=>{var u,d;if(typeof l=="string")try{let p=JSON.parse(l);if(this.schema){let y=this.schema[t],f=(u=y==null?void 0:y.relations)==null?void 0:u[s];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(p,m)}}return p}catch{return l}if(typeof l=="object"&&l!==null&&this.schema){let p=this.schema[t],y=(d=p==null?void 0:p.relations)==null?void 0:d[s];if(y){let f=y.entity.name;return this.parseRelationalJsonStrings(l,f)}}return l}):r[s]=a;else r[s]=a;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((o,[c,s])=>{var d,p,y,f,m,h,T,R,w;if(c==="_meta")return o;let a=(p=(d=n==null?void 0:n.fields[c])==null?void 0:d.getStorageFieldType)==null?void 0:p.call(d),l=(a==null?void 0:a.type)==="jsonb"||(a==null?void 0:a.type)==="json",u=(n==null?void 0:n.relations)&&c in n.relations;if(c==="id")o[c]={value:s};else if(l)o[c]={value:s,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[c]}};else if(u){let x=n.relations[c].entity,C=(x==null?void 0:x.name)??t;Array.isArray(s)?o[c]={value:s.map(O=>this.convertToMaterializedLiveType(O,C)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[c],relation:true}}:s!==null&&typeof s=="object"?o[c]={...this.convertToMaterializedLiveType(s,C),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[c],relation:true}}:o[c]={value:s,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[c],relation:true}};}else Array.isArray(s)?o[c]={value:s,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[c]}}:typeof s=="object"&&s!==null&&!(s instanceof Date)?o[c]={value:s,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[c]}}:o[c]={value:s,_meta:{timestamp:(w=e==null?void 0:e._meta)==null?void 0:w[c]}};return o},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",r=typeof t.startTransaction=="function",o=typeof t.savepoint=="function",c=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||o&&c}buildMutation(e,t,n,r,o,c){var a;let s={};for(let[l,u]of Object.entries(r.value)){if(l==="id")continue;let d=(a=u._meta)==null?void 0:a.timestamp;d&&(s[l]={value:u.value,_meta:{timestamp:d}});}return Object.keys(s).length===0?null:{id:o??de(),type:"SYNC",resource:e,resourceId:t,op:n,payload:s,meta:c?{originMutationId:c}:void 0}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let n=e;for(let r of n)this.server.notifySubscribers(r,t);}else {let n=e;for(let{mutation:r,entityData:o}of n)this.server.notifySubscribers(r,o);}}};var Fe=class i{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var t;if(this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=$e({level:e.logLevel??D.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),e.hooks)for(let[n,r]of Object.entries(e.hooks)){let o=ve([r]);o&&this.hooksRegistry.set(n,o);}this.initPromise=this.storage.init(this.schema,this.logger,this).catch(n=>{this.initError=n;}),this.contextProvider=e.contextProvider,this.queryEngine=new ye({storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleMutation(e){return await this.ensureInitialized(),await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async p=>{let y=this.router.routes[p.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:p,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:r,cookies:o,queryParams:c,context:s}=e.req,a={headers:r,cookies:o,queryParams:c,context:s},l=t.buildQueryRequest(),u=e.subscription?this.queryEngine.subscribe(l,p=>{var y;(y=e.subscription)==null||y.call(e,p);},a):void 0,d=await this.queryEngine.get(l,{context:a});return e.subscription?{data:d,unsubscribe:u,query:l}:d.map(p=>S(p))}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}notifySubscribers(e,t){this.queryEngine.handleMutation(e,t);}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},Ai=Fe.create;exports.QueryBuilder=Y;exports.Route=je;exports.RouteFactory=Ee;exports.Router=Oe;exports.SQLStorage=De;exports.Server=Fe;exports.Storage=ee;exports.createMiddleware=Zr;exports.createServerDB=X;exports.defineHooks=mr;exports.expressAdapter=qr;exports.mergeEntityHooks=ve;exports.mergeHooks=hr;exports.routeFactory=Yr;exports.router=Gr;exports.server=Ai;
|