@live-state/sync 0.0.7-canary-7 → 0.0.7-pr-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +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-LV6LHPwh.d.ts → index-C0Qm5yHg.d.ts} +25 -12
- package/dist/optimistic-client.d.ts +1 -1
- package/dist/server.cjs +6 -6
- package/dist/server.d.cts +62 -3
- package/dist/server.d.ts +62 -3
- package/dist/server.js +3 -3
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
'use strict';var ce=require('crypto'),jsXxhash=require('js-xxhash'),en=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 en__default=/*#__PURE__*/_interopDefault(en);var Tt=Object.create;var ke=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var Rt=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,xt=Object.prototype.hasOwnProperty;var vt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var St=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Rt(e))!xt.call(i,r)&&r!==t&&ke(i,r,{get:()=>e[r],enumerable:!(n=gt(e,r))||n.enumerable});return i};var Be=(i,e,t)=>(t=i!=null?Tt(bt(i)):{},St(ke(t,"default",{value:i,enumerable:true}),i));var Ie=vt(fe=>{Object.defineProperty(fe,"__esModule",{value:true});fe.parse=Ht;fe.serialize=Jt;var kt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Bt=/^[\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,Kt=/^[\u0020-\u003A\u003D-\u007E]*$/,Ut=Object.prototype.toString,Wt=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Ht(i,e){let t=new Wt,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Gt,o=0;do{let u=i.indexOf("=",o);if(u===-1)break;let s=i.indexOf(";",o),a=s===-1?n:s;if(u>a){o=i.lastIndexOf(";",u-1)+1;continue}let c=Je(i,o,u),d=Ge(i,u,c),l=i.slice(c,d);if(t[l]===void 0){let p=Je(i,u+1,a),y=Ge(i,a,p),f=r(i.slice(p,y));t[l]=f;}o=a+1;}while(o<n);return t}function Je(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function Ge(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Jt(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!kt.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Bt.test(r))throw new TypeError(`argument val is invalid: ${e}`);let 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(!zt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);o+="; Domain="+t.domain;}if(t.path){if(!Kt.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 Gt(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Zt(i){return Ut.call(i)==="[object Date]"}});var ve=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),S=i=>i?Array.isArray(i.value)?i.value.map(t=>ve(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=>ve(r)?S(r):r)]:ve(n)?[t,S(n)]:[t,n])):void 0;var Ke="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Y=32;var Vt=16,Ue=10,ze=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 Nt(i){let e=Math.floor(i()*Y);return e===Y&&(e=Y-1),Ke.charAt(e)}function Qt(i){var n;let e=qt(),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 qt(){return Ft()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function $t(i,e){let t="";for(;i>0;i--)t=Nt(e)+t;return t}function Dt(i,e=Ue){if(isNaN(i))throw new z(B.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>ze)throw new z(B.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${ze}: ${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=Ke.charAt(t)+n,i=(i-t)/Y;return n}function Ft(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function We(i,e){let t=Qt(),n=Date.now();return Dt(n,Ue)+$t(Vt,t)}var de=()=>We().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}}}),Se=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((o,u)=>{let s=this.getBatchKey({resource:e,commonWhere:t,...r}),a={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:o,reject:u};this.queue.has(s)||this.queue.set(s,[]);let c=this.queue.get(s);c&&c.push(a),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var p;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:o,sort:u}=t,s=e.length===1?t.limit:void 0,a=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),c=r,d=(p=Object.entries(a[0]??{})[0])==null?void 0:p[0];if(a.length>0){let y=a.map(f=>f[d]).filter(f=>f!=null);y.length>0&&(c=J(r,{[d]:{$in:y}}));}let l=await this.storage.get({resource:n,where:c,include:o,sort:u,limit:s});for(let y of e){let f=l;if(y.uniqueWhere){let[m,h]=Object.entries(y.uniqueWhere)[0];f=l.filter(T=>{var g;return ((g=T.value[m])==null?void 0:g.value)===h});}y.resolve(f);}}};var q=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),K=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let o=u=>{u.$and?u.$and.forEach(o):u.$or?u.$or.forEach(o):Object.entries(u).forEach(([s,a])=>{var c;if((c=r.relations)!=null&&c[s]&&(n[s]=true,typeof a=="object"&&a!==null&&!Array.isArray(a))){let d=K(a,r.relations[s].entity.name,t);Object.keys(d).length>0&&(n[s]={include:d});}});};return o(i),n},j=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(u=>j(i,u,t));if(n==="$or")return r.some(u=>j(i,u,t));let o=(r==null?void 0:r.$eq)!==void 0?r==null?void 0:r.$eq:r;if(typeof r=="object"&&r!==null&&(r==null?void 0:r.$eq)===void 0){if(r.$in!==void 0){let s=i[n];return s===void 0?false:t?!r.$in.includes(s):r.$in.includes(s)}if(r.$not!==void 0&&!t)return j(i,{[n]:r.$not},true);if(r.$gt!==void 0){let s=i[n];return typeof s!="number"?false:t?s<=r.$gt:s>r.$gt}if(r.$gte!==void 0){let s=i[n];return typeof s!="number"?false:t?s<r.$gte:s>=r.$gte}if(r.$lt!==void 0){let s=i[n];return typeof s!="number"?false:t?s>=r.$lt:s<r.$lt}if(r.$lte!==void 0){let s=i[n];return typeof s!="number"?false:t?s>r.$lte:s<=r.$lte}let u=i[n];return !u||typeof u!="object"&&!Array.isArray(u)?false:Array.isArray(u)?t?!u.some(s=>j(s,r,false)):u.some(s=>j(s,r,false)):j(u,r,t)}return t?i[n]!==o:i[n]===o}),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},F={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},we=class{level;prefix;constructor(e={}){this.level=e.level??F.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=F.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=F.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=F.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=F.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=F.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},He=i=>new we(i);function Me(i){return q({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,o]of Object.entries(n.relations))o.type==="one"&&o.relationalColumn&&t.set(String(o.relationalColumn),{relationName:r,targetResource:o.entity.name});return t}ensureObjectNode(e,t,n){let r=this.objectNodes.get(e);return r?n&&r.matchedQueries.add(n):(r={id:e,type:t,matchedQueries:new Set(n?[n]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,r)),r}storeRelation(e,t,n,r){let o=this.objectNodes.get(e),u=this.objectNodes.get(t);if(o&&o.referencesObjects.set(n,t),u&&r){let s=u.referencedByObjects.get(r);s||(s=new Set,u.referencedByObjects.set(r,s)),s.add(e);}}removeRelation(e,t,n,r){let o=this.objectNodes.get(e),u=this.objectNodes.get(t);if(o&&o.referencesObjects.delete(n),u&&r){let s=u.referencedByObjects.get(r);s&&(s.delete(e),s.size===0&&u.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let o=r.relations[n];if(!o)return;let u=this.schema[t];if(u!=null&&u.relations){if(o.type==="many"&&o.foreignColumn){for(let[s,a]of Object.entries(u.relations))if(a.entity.name===e&&a.type==="one"&&a.relationalColumn===o.foreignColumn)return s}if(o.type==="one"&&o.relationalColumn){for(let[s,a]of Object.entries(u.relations))if(a.entity.name===e&&a.type==="many"&&a.foreignColumn===o.relationalColumn)return s}}}updateRelationsFromMutation(e,t,n,r){let o=this.getRelationalColumns(e),u=this.objectNodes.get(t);if(u)for(let[s,{relationName:a,targetResource:c}]of Array.from(o)){if(!(r&&s in r))continue;let l=this.getInverseRelationName(e,c,a),p=u.referencesObjects.get(a),y=n[s];p!==y&&(p&&this.removeRelation(t,p,a,l),y&&(this.ensureObjectNode(y,c),this.storeRelation(t,y,a,l)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new ye(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),o={},u=[];for(let s of r){this.logger.debug("[QueryEngine] Subscribing to step",s.stepPath.join("."));let a=Me(s),c=o[s.stepPath.at(-2)??""],d=s.stepPath.at(-1)??"",l=this.queryNodes.get(a);if(l)l.subscriptions.add(t);else if(l={hash:a,queryStep:s,relationName:d,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:c,childQueries:new Set},this.queryNodes.set(l.hash,l),c){let p=this.queryNodes.get(c);p&&p.childQueries.add(l.hash);}o[d]=a,u.push(()=>{let p=this.queryNodes.get(a);p&&(p.subscriptions.delete(t),p.subscriptions.size===0&&this.queryNodes.delete(a));});}return ()=>{for(let s of u)s();}}breakdownQuery(e){var h;let{query:t,stepPath:n=[],context:r={},parentResource:o}=e,{include:u}=t,s=n.length===0,a=n.at(-1),c,d,l;if(!s&&o&&a){let T=this.schema[o],g=(h=T==null?void 0:T.relations)==null?void 0:h[a];g&&(l=g.type==="many",g.type==="one"?(c=R=>({id:R}),d=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x[g.relationalColumn])==null?void 0:w.value}).filter(b=>b!==void 0)):(c=R=>({[g.foreignColumn]:R}),d=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x.id)==null?void 0:w.value}).filter(b=>b!==void 0)));}let{include:p,...y}=t,m=[this.router.incrementQueryStep({query:y,stepPath:[...n],getWhere:c,referenceGetter:d,isMany:l,relationName:a},r)];if(u&&typeof u=="object"&&Object.keys(u).length>0){let T=this.schema[t.resource];if(!T)throw new Error(`Resource ${t.resource} not found`);m.push(...Object.entries(u).flatMap(([g,R])=>{let b=T.relations[g];if(!b)throw new Error(`Relation ${g} not found for resource ${t.resource}`);let x=b.entity.name,w=pe(R)?R:null;return this.breakdownQuery({query:{resource:x,include:w?w.include:typeof R=="object"?R:void 0,where:w==null?void 0:w.where,limit:w==null?void 0:w.limit,sort:w==null?void 0:w.orderBy},stepPath:[...n,g],context:r,parentResource:t.resource})}));}return m}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(o=>o.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(o=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",o.length),n[e[0].stepPath.join(".")]=[{data:o}];});for(let o=1;o<e.length;o++){let u=e[o],s=u.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var c,d;let a=n[s];if(!a){n[u.stepPath.join(".")]=[];return}if(u.referenceGetter&&u.getWhere){let l=new Map;for(let f of a)for(let m of f.data){let h=(d=(c=m==null?void 0:m.value)==null?void 0:c.id)==null?void 0:d.value;if(!h)continue;let g=u.referenceGetter([m])[0];if(g){l.has(g)||l.set(g,new Set);let R=l.get(g);R&&R.add(h);}}let p=Array.from(l.keys());if(p.length===0){n[u.stepPath.join(".")]=[];return}let y=[];for(let f of p){let m=u.getWhere(f),h={...u,relationalWhere:m},T=await this.resolveStep(h,t),g=l.get(f);if(g)for(let R of Array.from(g))y.push({includedBy:R,data:T});}this.logger.debug("[QueryEngine] Resolved step",u.stepPath.join("."),"with results count:",y.reduce((f,m)=>f+m.data.length,0)),n[u.stepPath.join(".")]=y;}else {let l=await this.resolveStep(u,t);n[u.stepPath.join(".")]=[{data:l}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var u,s,a,c,d;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let n=new Map;for(let l of e){let p=l.stepPath.join("."),y=t[p]??[],f=Object.keys(l.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${p}"`,{resource:l.query.resource,includedRelations:f,resultGroups:y.length,isMany:l.isMany,relationName:l.relationName});for(let m of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${p}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let h of m.data){let T=(s=(u=h==null?void 0:h.value)==null?void 0:u.id)==null?void 0:s.value;if(!T){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${p}"`);continue}let g=p?`${p}.${T}`:T,R=[];if(l.stepPath.length>0&&m.includedBy){let x=l.stepPath.slice(0,-1).join(".");R=[x?`${x}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${g}" has parent keys:`,R,{stepPath:p,parentStepPath:x,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${g}" (no parent)`);let b=n.get(g);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${g}" already exists, adding parent keys:`,R);for(let x of R)b.includedBy.add(x);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${g}"`,{resource:l.query.resource,path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,includedRelations:f,parentKeys:R}),n.set(g,{data:h,includedBy:new Set(R),path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,resourceName:l.query.resource,includedRelations:f});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),o=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let l=r.length-1;l>=0;l--){let[p,y]=r[l],f=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${p}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let m of y.includedRelations){let h=(c=(a=f==null?void 0:f.relations)==null?void 0:a[m])==null?void 0:c.type,T=!!y.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${p}"`,{relationType:h,hasRelation:T,resourceHasRelation:!!((d=f==null?void 0:f.relations)!=null&&d[m])}),y.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${p}"`,y.data.value[m]);else {let g=h==="many"?{value:[]}:{value:null};y.data.value[m]=g,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${p}" with`,g);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${p}" to resultData`),o.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to ${y.includedBy.size} parent(s)`);for(let m of Array.from(y.includedBy)){let h=n.get(m);if(!h){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${p}"`);continue}let T=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to parent "${m}" via relation "${T}"`,{isMany:y.isMany,parentHasRelation:!!h.data.value[T]}),y.isMany?(h.data.value[T]??={value:[]},h.data.value[T].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${p}" to many relation "${T}" on parent "${m}"`,{arrayLength:h.data.value[T].value.length})):(h.data.value[T]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${T}" on parent "${m}" to "${p}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${o.length} root items`),o}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:n,relationalWhere:r}=e,o=n.where&&r?J(n.where,r):r??n.where,u=o?{...n,where:o}:n;return Se(this.router.get(u,t)).then(s=>(this.loadStepResults(e,s),s))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=Me(e),r=this.queryNodes.get(n),o=e.query.resource;if(!r)return;let u=this.getRelationalColumns(o);for(let s of t){let a=S(s),c=a.id;this.ensureObjectNode(c,o,n),r.trackedObjects.add(c);for(let[d,{relationName:l,targetResource:p}]of Array.from(u)){let y=a[d];if(y){this.ensureObjectNode(y,p);let f=this.getInverseRelationName(o,p,l);this.storeRelation(c,y,l,f);}}this.loadNestedRelations(o,c,a),this.logger.debug("[QueryEngine] Loaded nested relations for",c);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[o,u]of Object.entries(r.relations)){let s=n[o];if(!s)continue;let a=u.entity.name,c=this.getInverseRelationName(e,a,o);if(u.type==="one")s&&typeof s=="object"&&s.id&&(this.ensureObjectNode(s.id,a),this.storeRelation(t,s.id,o,c),this.loadNestedRelations(a,s.id,s));else if(u.type==="many"&&Array.isArray(s)){for(let d of s)if(d&&typeof d=="object"&&d.id){this.ensureObjectNode(d.id,a);let l=this.getInverseRelationName(a,e,o);l&&this.storeRelation(d.id,t,l,o),this.loadNestedRelations(a,d.id,d);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let o=this.queryNodes.get(r);if(!o||!o.relationName)continue;let u=this.buildIncludeFromChildQueries(r);n[o.relationName]=Object.keys(u).length>0?u:true;}return n}sendInsertsForTree(e,t,n){var s,a;let r=(a=(s=t==null?void 0:t.value)==null?void 0:s.id)==null?void 0:a.value;if(!r)return;let o={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let c of Array.from(e.subscriptions))try{c(o);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let c of Array.from(e.childQueries)){let d=this.queryNodes.get(c);if(!d||!d.relationName)continue;let l=d.relationName,p=d.queryStep.query.resource,y=t.value[l];if(!y)continue;let f=y.value;if(Array.isArray(f))for(let m of f)this.sendInsertsForTree(d,m,p);else f&&typeof f=="object"&&this.sendInsertsForTree(d,f,p);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=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:c}]of Array.from(o)){let d=n[s];if(d){this.ensureObjectNode(d,c);let l=this.getInverseRelationName(e.resource,c,a);this.storeRelation(e.resourceId,d,a,l);}}let u=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(s=>{for(let a of s){let c=this.queryNodes.get(a);if(c){c.trackedObjects.add(e.resourceId),u&&u.matchedQueries.add(a);for(let d of Array.from(c.subscriptions))try{d(e);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:l,queryHash:c.hash,resource:e.resource,resourceId:e.resourceId,stepPath:c.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let n=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.getMatchingQueries(e,n).then(u=>{let s=new Set(u),a=[],c=[],d=[];for(let p of u)o.has(p)?d.push(p):a.push(p);for(let p of Array.from(o))s.has(p)||c.push(p);for(let p of a){let y=this.queryNodes.get(p);y&&y.trackedObjects.add(e.resourceId);}for(let p of c){let y=this.queryNodes.get(p);y&&y.trackedObjects.delete(e.resourceId);}let l=this.objectNodes.get(e.resourceId);if(l){for(let p of a)l.matchedQueries.add(p);for(let p of c)l.matchedQueries.delete(p);}for(let p of [...c,...d]){let y=this.queryNodes.get(p);if(y)for(let f of Array.from(y.subscriptions))try{f(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(a.length>0)for(let p of a){let y=this.queryNodes.get(p);if(!y)continue;let f=this.buildIncludeFromChildQueries(p);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(y,m[0],e.resource);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?Se([]):Promise.all(n.map(async r=>{let o=r.queryStep.query.where,u=r.queryStep.query.resource,s=e.resourceId,a=this.objectNodes.get(s);if(!a)return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=y==null?void 0:y.queryStep.query.resource,m=f?this.getInverseRelationName(f,u,r.relationName):void 0,h=m?a.referencesObjects.get(m):void 0;if(!h)return {hash:r.hash,matches:false};let T=this.objectNodes.get(h);return !T||!y||!T.matchedQueries.has(y.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!o)return {hash:r.hash,matches:true};let c=K(o,u,this.schema),d=Object.keys(c).length>0;if(!d&&t!==void 0)return {hash:r.hash,matches:j(t,o)};let l=await this.storage.get({resource:u,where:{id:s},include:d?c:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let p=S(l[0]);return p?{hash:r.hash,matches:j(p,o)}:{hash:r.hash,matches:false}})).then(r=>r.filter(o=>o.matches).map(o=>o.hash))}};var tt=Be(Ie());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()}),Ce=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()})),Yt=Ce.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ze=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),Ye=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),G=Ze.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:Ye}),X=Ze.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:Yt,meta:Ye});zod.z.union([X,G]);var Xe=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var et=he.omit({resource:true}),Le=G.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:G.shape.meta}),Ae=X.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([Ae,Le]);var je=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(je);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=je(n);return e}return i},nt=i=>{let e=i.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,o={headers:r,cookies:r.cookie?tt.default.parse(r.cookie):{}},u=new URL(t.url),s=u.pathname.split("/"),a=u.searchParams,c=je(en__default.default.parse(a.toString())),d=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:o.headers,cookies:o.cookies,queryParams:c}))??{};if(t.method==="GET"){let l=s[s.length-1],{success:p,data:y,error:f}=et.safeParse(c);if(!p)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:f},{status:400});let m=await i.handleQuery({req:{...o,...y,type:"QUERY",resource:l,context:d,queryParams:c}});return !m||!m.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(m.data)}if(t.method==="POST")try{let l=s[s.length-1],p=s[s.length-2];if(p==="query"){if(s.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let T=s[s.length-3],g=t.body?await t.json():{};if(!T||T.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let R=await i.handleCustomQuery({req:{...o,type:"CUSTOM_QUERY",resource:T,procedure:l,input:g.input,context:d,queryParams:c}});return Response.json(R)}let y=p,f=t.body?await t.json():{},m;if(l==="insert"||l==="update"){let{success:T,data:g,error:R}=Ae.safeParse(f);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});m=g;}else {let{success:T,data:g,error:R}=Le.safeParse(f);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});m=g;}let h=await i.handleMutation({req:{...o,type:"MUTATE",resource:y,input:m.payload,context:d,resourceId:m.resourceId,procedure:l==="insert"||l==="update"?l.toUpperCase():l,queryParams:{},meta:m.meta}});return Response.json(h)}catch(l){return e.error("Error parsing mutation from the client:",l),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var at=Be(Ie());var _=zod.z.string(),Oe=zod.z.union([Xe,he]),tn=zod.z.object({id:_,type:zod.z.literal("SUBSCRIBE")}).and(Oe),nn=zod.z.object({id:_,type:zod.z.literal("UNSUBSCRIBE")}).and(Oe),rn=zod.z.object({id:_,type:zod.z.literal("QUERY")}).and(Oe),an=zod.z.object({id:_,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),rt=X.extend({id:_}),sn=G.extend({id:_}),on=zod.z.union([sn,rt]),it=zod.z.union([tn,rn,an,on,nn]),un=zod.z.object({id:_,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),cn=zod.z.object({id:_,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([un,cn,rt]);zod.z.object({resource:zod.z.string(),data:zod.z.array(Ce)});var st=i=>{let e={},t=i.logger;return (n,r)=>{var l;let o=p=>{n.send(JSON.stringify(p));},u=de(),s=new Map,a={headers:r.headers,cookies:typeof r.headers.cookie=="string"?at.default.parse(r.headers.cookie):{}},c=en.parse(r.url.split("?")[1]),d=(l=i.contextProvider)==null?void 0:l.call(i,{transport:"WEBSOCKET",headers:a.headers,cookies:a.cookies,queryParams:c});e[u]=n,t.info("Client connected:",u),n.on("message",async p=>{try{t.debug("Message received from the client:",p);let y=it.parse(JSON.parse(p.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:f,id:m,...h}=y,T=f==="SUBSCRIBE";if("procedure"in h){let g=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h.resource,procedure:h.procedure,input:h.input,context:await d??{},queryParams:c},subscription:T?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(T){if(!g||!g.data||!g.query)throw new Error("Invalid resource");g.unsubscribe&&s.set(q(h),g.unsubscribe),o({id:m,type:"REPLY",data:{resource:g.query.resource,data:(g.data??[]).map(R=>R.value)}});}else o({id:m,type:"REPLY",data:g});}else {let g=await i.handleQuery({req:{...a,...h,type:"QUERY",context:await d??{},queryParams:c},subscription:T?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(!g||!g.data)throw new Error("Invalid resource");T&&g.unsubscribe&&s.set(q(h),g.unsubscribe),o({id:m,type:"REPLY",data:{resource:h.resource,data:(g.data??[]).map(R=>R.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:f,id:m,...h}=y,T=s.get(q(h));T&&(T(),s.delete(q(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 g=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:f,procedure:m,input:h,context:await d??{},queryParams:c}});o({id:T,type:"REPLY",data:g});}catch(g){o({id:T,type:"REJECT",resource:f,message:g.message}),t.error("Error handling custom query from the client:",g);}}else if(y.type==="MUTATE"){let{resource:f}=y;t.debug("Received mutation from client:",y);try{let m=await i.handleMutation({req:{...a,type:"MUTATE",resource:f,input:y.payload,context:{messageId:y.id,...await d??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:c,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&o({id:y.id,type:"REPLY",data:m});}catch(m){o({id:y.id,type:"REJECT",resource:f,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",u),delete e[u];for(let p of Array.from(s.values()))p();});}};function ot(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Fr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,st(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{nt(e)(ot(n)).then(u=>u.json().then(s=>r.status(u.status).send(s)));});};var Te=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,o,u,s,a){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=o,this._single=u,this._sort=s,this._shouldAwait=a,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new i(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new i(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new i(this._collection,this._client,this._where,this._include,e,this._single,this._sort,this._shouldAwait)}one(e){return this.first({id:e})}first(e){return new i(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new i(this._collection,this._client,this._where,this._include,this._limit,this._single,n,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}buildQueryRequest(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}get(){let e=this._client.get(this.buildQueryRequest());return this._shouldAwait?Promise.resolve(e).then(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,n){return new i(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var dn=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Ee=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>dn(n)?S(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function U(i,e,t){let n=new Ee(i),r=u=>{let s=Te._init(u,n,true);return Object.assign(Object.create(s),{insert:async c=>{let d=i._getTimestamp(),l=await i.rawInsert(u.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([p,y])=>[p,{value:y,_meta:{timestamp:d}}]))},void 0,t);return S(l.data)},update:async(c,d)=>{let l=i._getTimestamp(),{id:p,...y}=d,f=await i.rawUpdate(u.name,c,{value:Object.fromEntries(Object.entries(y).map(([T,g])=>[T,{value:g,_meta:{timestamp:l}}]))},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(u,s){if(s==="findOne")return i.findOne.bind(i);if(s==="find")return i.find.bind(i);if(s==="insert")return (a,c)=>{let d=i._getTimestamp();return i.rawInsert(a.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([l,p])=>[l,{value:p,_meta:{timestamp:d}}]))},void 0,t).then(l=>S(l.data))};if(s==="update")return (a,c,d)=>{let l=i._getTimestamp(),{id:p,...y}=d;return i.rawUpdate(a.name,c,{value:Object.fromEntries(Object.entries(y).map(([f,m])=>[f,{value:m,_meta:{timestamp:l}}]))},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:c,commit:d,rollback:l})=>{let p=U(c,e,t);return a({trx:p,commit:d,rollback:l})});if(s in e){let a=e[s];return r(a)}}};return new Proxy({},o)}var Pe=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)}},Gr=i=>Pe.create({...i}),ct=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),lt=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),Ve=class i{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,n,r,o){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=n??{},this.authorization=r,this.hooks=o;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:lt,query:ct}),n={},r={};for(let[o,u]of Object.entries(t))u._type==="mutation"?n[o]=u:r[o]=u;return new i(this.resourceSchema,n,r,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new i(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},o=q(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:o}})(e);handleMutation=async({req:e,db:t,schema:n})=>{var s;let r=((s=e.meta)==null?void 0:s.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r),u=U(o,n,e.context);return await this.wrapInMiddlewares(async a=>{if(!a.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[a.procedure];if(c){let d=c.inputValidator["~standard"].validate(a.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.issues.map(y=>{var m;let f=(m=y.path)==null?void 0:m.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return f?`${f}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}return a.input=l.value,c.handler({req:a,db:u})}else {if(a.procedure==="INSERT"||a.procedure==="UPDATE")return this.handleSet({req:a,db:o,operation:a.procedure,schema:n});throw new Error(`Unknown procedure: ${a.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=U(t,n,e.context);return await this.wrapInMiddlewares(async o=>{let u=this.customQueries[o.procedure];if(!u)throw new Error(`Unknown query procedure: ${o.procedure}`);let s=u.inputValidator["~standard"].validate(o.input),a=s instanceof Promise?await s:s;if(a.issues){let c=a.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return o.input=a.value,u.handler({req:o,db:r})})(e)};getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let o=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&o)throw new Error("Resource already exists");if(n==="UPDATE"&&!o)throw new Error("Resource not found");let u={value:e.input};return t.transaction(async({trx:s})=>{var d,l,p,y,f,m,h;if(n==="INSERT"){let{data:T,acceptedValues:g}=await s.rawInsert(e.resource,e.resourceId,u,(d=e.context)==null?void 0:d.messageId,e.context);if(!g)throw new Error("Mutation rejected");let R=S(T);if(R.id=R.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let x=K(b,e.resource,r),w=Object.keys(x).length>0?await s.rawFindById(e.resource,e.resourceId,x):T,E=S(w);if(E.id=E.id??e.resourceId,!j(E,b))throw new Error("Not authorized")}}return {data:T,acceptedValues:g}}if((y=(p=this.authorization)==null?void 0:p.update)!=null&&y.preMutation){let T=S(o);T.id=T.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let R=K(g,e.resource,r),b=Object.keys(R).length>0?await s.rawFindById(e.resource,e.resourceId,R):o,x=S(b);if(x.id=x.id??e.resourceId,!j(x,g))throw new Error("Not authorized")}}let{data:a,acceptedValues:c}=await s.rawUpdate(e.resource,e.resourceId,u,(f=e.context)==null?void 0:f.messageId,e.context);if(!c)throw new Error("Mutation rejected");if((h=(m=this.authorization)==null?void 0:m.update)!=null&&h.postMutation){let T=S(a);T.id=T.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let R=K(g,e.resource,r),b=Object.keys(R).length>0?await s.rawFindById(e.resource,e.resourceId,R):a,x=S(b);if(x.id=x.id??e.resourceId,!j(x,g))throw new Error("Not authorized")}}return {data:a,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}},Ne=class{resourceSchema=void 0;middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:n})=>{var s;let r=((s=e.meta)==null?void 0:s.timestamp)??new Date().toISOString(),o=t._setMutationTimestamp(r),u=U(o,n,e.context);return await this.wrapInMiddlewares(async a=>{if(!a.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[a.procedure];if(c){let d=c.inputValidator["~standard"].validate(a.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.issues.map(y=>{var m;let f=(m=y.path)==null?void 0:m.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return f?`${f}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}return a.input=l.value,c.handler({req:a,db:u})}throw new Error(`Unknown procedure: ${a.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=U(t,n,e.context);return await this.wrapInMiddlewares(async o=>{let u=this.customQueries[o.procedure];if(!u)throw new Error(`Unknown query procedure: ${o.procedure}`);let s=u.inputValidator["~standard"].validate(o.input),a=s instanceof Promise?await s:s;if(a.issues){let c=a.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return o.input=a.value,u.handler({req:o,db:r})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>o=>r({req:o,next:n}),e)(t)}};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 Qe=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Ve(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:lt,query:ct}),n={},r={};for(let[o,u]of Object.entries(t))u._type==="mutation"?n[o]=u:r[o]=u;return new Ne(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}},Yr=Qe.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,u])=>[o,{value:u,_meta:{timestamp:n}}]))});return S(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:o,...u}=n,s=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(u).map(([d,l])=>[d,{value:l,_meta:{timestamp:r}}]))}),a=S(s.data),c={};for(let d of Object.keys(u))d in a&&(c[d]=a[d]);return c}};var gn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function $(i){var r,o,u;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((u=(o=t.constructor)==null?void 0:o.name)==null?void 0:u.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function dt(i){let e=$(i);return gn[e]}var Rn="42701";function te(i){var t;if(i.code===Rn)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 bn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let o of Object.values(e))for(let u of Object.values(o.fields)){let s=u.getStorageFieldType();s.enumValues&&s.enumName&&r.set(s.enumName,{name:s.enumName,values:s.enumValues});}for(let o of Array.from(r.values())){let{name:u,values:s}=o;try{let a=s.map(c=>`'${c}'`).join(", ");await kysely.sql`
|
|
1
|
+
'use strict';var ue=require('crypto'),jsXxhash=require('js-xxhash'),rn=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 ue__default=/*#__PURE__*/_interopDefault(ue);var rn__default=/*#__PURE__*/_interopDefault(rn);var Tt=Object.create;var Fe=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var Rt=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,xt=Object.prototype.hasOwnProperty;var St=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var vt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Rt(e))!xt.call(i,r)&&r!==t&&Fe(i,r,{get:()=>e[r],enumerable:!(n=gt(e,r))||n.enumerable});return i};var Be=(i,e,t)=>(t=i!=null?Tt(bt(i)):{},vt(Fe(t,"default",{value:i,enumerable:true}),i));var Ce=St(me=>{Object.defineProperty(me,"__esModule",{value:true});me.parse=Zt;me.serialize=Yt;var Ut=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Kt=/^[\u0021-\u003A\u003C-\u007E]*$/,Ht=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Wt=/^[\u0020-\u003A\u003D-\u007E]*$/,Jt=Object.prototype.toString,Gt=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Zt(i,e){let t=new Gt,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Xt,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=Je(i,a,u),d=Ge(i,u,c),l=i.slice(c,d);if(t[l]===void 0){let p=Je(i,u+1,s),y=Ge(i,s,p),f=r(i.slice(p,y));t[l]=f;}a=s+1;}while(a<n);return t}function Je(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function Ge(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Yt(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Ut.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Kt.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(!Ht.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Wt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!en(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 Xt(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function en(i){return Jt.call(i)==="[object Date]"}});var Se=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),S=i=>i?Array.isArray(i.value)?i.value.map(t=>Se(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=>Se(r)?S(r):r)]:Se(n)?[t,S(n)]:[t,n])):void 0;var Ue="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Z=32;var Nt=16,Ke=10,ze=0xffffffffffff;var F;(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";})(F||(F={}));var B=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Vt(i){let e=Math.floor(i()*Z);return e===Z&&(e=Z-1),Ue.charAt(e)}function kt(i){var n;let e=Qt(),t=e&&(e.crypto||e.msCrypto)||(typeof ue__default.default<"u"?ue__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=ue__default.default)!=null&&n.randomBytes)return ()=>ue__default.default.randomBytes(1).readUInt8()/255;throw new B(F.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Qt(){return Dt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function qt(i,e){let t="";for(;i>0;i--)t=Vt(e)+t;return t}function $t(i,e=Ke){if(isNaN(i))throw new B(F.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>ze)throw new B(F.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${ze}: ${i}`);if(i<0)throw new B(F.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new B(F.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%Z,n=Ue.charAt(t)+n,i=(i-t)/Z;return n}function Dt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function He(i,e){let t=kt(),n=Date.now();return $t(n,Ke)+qt(Nt,t)}var le=()=>He().toLowerCase(),ce=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ce(n)}return ce(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ce(r)}throw n}}}),ve=i=>i instanceof Promise?i:ce(i);var W=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var de=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 p;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(y=>y.uniqueWhere).filter(y=>y!==void 0),c=r,d=(p=Object.entries(s[0]??{})[0])==null?void 0:p[0];if(s.length>0){let y=s.map(f=>f[d]).filter(f=>f!=null);y.length>0&&(c=W(r,{[d]:{$in:y}}));}let l=await this.storage.get({resource:n,where:c,include:a,sort:u,limit:o});for(let y of e){let f=l;if(y.uniqueWhere){let[m,T]=Object.entries(y.uniqueWhere)[0];f=l.filter(g=>{var h;return ((h=g.value[m])==null?void 0:h.value)===T});}y.resolve(f);}}};var Q=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),z=(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 d=z(s,r.relations[o].entity.name,t);Object.keys(d).length>0&&(n[o]={include:d});}});};return a(i),n},j=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(u=>j(i,u,t));if(n==="$or")return r.some(u=>j(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 j(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=>j(o,r,false)):u.some(o=>j(o,r,false)):j(u,r,t)}return t?i[n]!==a:i[n]===a}),ye=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},we=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}},We=i=>new we(i);function Me(i){return Q({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}var pe=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 l=this.getInverseRelationName(e,c,s),p=u.referencesObjects.get(s),y=n[o];p!==y&&(p&&this.removeRelation(t,p,s,l),y&&(this.ensureObjectNode(y,c),this.storeRelation(t,y,s,l)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new de(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=Me(o),c=a[o.stepPath.at(-2)??""],d=o.stepPath.at(-1)??"",l=this.queryNodes.get(s);if(l)l.subscriptions.add(t);else if(l={hash:s,queryStep:o,relationName:d,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:c,childQueries:new Set},this.queryNodes.set(l.hash,l),c){let p=this.queryNodes.get(c);p&&p.childQueries.add(l.hash);}a[d]=s,u.push(()=>{let p=this.queryNodes.get(s);p&&(p.subscriptions.delete(t),p.subscriptions.size===0&&this.queryNodes.delete(s));});}return ()=>{for(let o of u)o();}}breakdownQuery(e){var T;let{query:t,stepPath:n=[],context:r={},parentResource:a}=e,{include:u}=t,o=n.length===0,s=n.at(-1),c,d,l;if(!o&&a&&s){let g=this.schema[a],h=(T=g==null?void 0:g.relations)==null?void 0:T[s];h&&(l=h.type==="many",h.type==="one"?(c=R=>({id:R}),d=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x[h.relationalColumn])==null?void 0:w.value}).filter(b=>b!==void 0)):(c=R=>({[h.foreignColumn]:R}),d=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x.id)==null?void 0:w.value}).filter(b=>b!==void 0)));}let{include:p,...y}=t,m=[this.router.incrementQueryStep({query:y,stepPath:[...n],getWhere:c,referenceGetter:d,isMany:l,relationName: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(([h,R])=>{let b=g.relations[h];if(!b)throw new Error(`Relation ${h} not found for resource ${t.resource}`);let x=b.entity.name,w=ye(R)?R:null;return this.breakdownQuery({query:{resource:x,include:w?w.include:typeof R=="object"?R:void 0,where:w==null?void 0:w.where,limit:w==null?void 0:w.limit,sort:w==null?void 0:w.orderBy},stepPath:[...n,h],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,d;let s=n[o];if(!s){n[u.stepPath.join(".")]=[];return}if(u.referenceGetter&&u.getWhere){let l=new Map;for(let f of s)for(let m of f.data){let T=(d=(c=m==null?void 0:m.value)==null?void 0:c.id)==null?void 0:d.value;if(!T)continue;let h=u.referenceGetter([m])[0];if(h){l.has(h)||l.set(h,new Set);let R=l.get(h);R&&R.add(T);}}let p=Array.from(l.keys());if(p.length===0){n[u.stepPath.join(".")]=[];return}let y=[];for(let f of p){let m=u.getWhere(f),T={...u,relationalWhere:m},g=await this.resolveStep(T,t),h=l.get(f);if(h)for(let R of Array.from(h))y.push({includedBy:R,data:g});}this.logger.debug("[QueryEngine] Resolved step",u.stepPath.join("."),"with results count:",y.reduce((f,m)=>f+m.data.length,0)),n[u.stepPath.join(".")]=y;}else {let l=await this.resolveStep(u,t);n[u.stepPath.join(".")]=[{data:l}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var u,o,s,c,d;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let n=new Map;for(let l of e){let p=l.stepPath.join("."),y=t[p]??[],f=Object.keys(l.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${p}"`,{resource:l.query.resource,includedRelations:f,resultGroups:y.length,isMany:l.isMany,relationName:l.relationName});for(let m of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${p}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let T of m.data){let g=(o=(u=T==null?void 0:T.value)==null?void 0:u.id)==null?void 0:o.value;if(!g){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${p}"`);continue}let h=p?`${p}.${g}`:g,R=[];if(l.stepPath.length>0&&m.includedBy){let x=l.stepPath.slice(0,-1).join(".");R=[x?`${x}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${h}" has parent keys:`,R,{stepPath:p,parentStepPath:x,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${h}" (no parent)`);let b=n.get(h);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${h}" already exists, adding parent keys:`,R);for(let x of R)b.includedBy.add(x);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${h}"`,{resource:l.query.resource,path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,includedRelations:f,parentKeys:R}),n.set(h,{data:T,includedBy:new Set(R),path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,resourceName:l.query.resource,includedRelations:f});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),a=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let l=r.length-1;l>=0;l--){let[p,y]=r[l],f=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${p}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let m of y.includedRelations){let T=(c=(s=f==null?void 0:f.relations)==null?void 0:s[m])==null?void 0:c.type,g=!!y.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${p}"`,{relationType:T,hasRelation:g,resourceHasRelation:!!((d=f==null?void 0:f.relations)!=null&&d[m])}),y.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${p}"`,y.data.value[m]);else {let h=T==="many"?{value:[]}:{value:null};y.data.value[m]=h,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${p}" with`,h);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${p}" to resultData`),a.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to ${y.includedBy.size} parent(s)`);for(let m of Array.from(y.includedBy)){let T=n.get(m);if(!T){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${p}"`);continue}let g=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to parent "${m}" via relation "${g}"`,{isMany:y.isMany,parentHasRelation:!!T.data.value[g]}),y.isMany?(T.data.value[g]??={value:[]},T.data.value[g].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${p}" to many relation "${g}" on parent "${m}"`,{arrayLength:T.data.value[g].value.length})):(T.data.value[g]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${g}" on parent "${m}" to "${p}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${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?W(n.where,r):r??n.where,u=a?{...n,where:a}:n;return ve(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=Me(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=S(o),c=s.id;this.ensureObjectNode(c,a,n),r.trackedObjects.add(c);for(let[d,{relationName:l,targetResource:p}]of Array.from(u)){let y=s[d];if(y){this.ensureObjectNode(y,p);let f=this.getInverseRelationName(a,p,l);this.storeRelation(c,y,l,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 d of o)if(d&&typeof d=="object"&&d.id){this.ensureObjectNode(d.id,s);let l=this.getInverseRelationName(s,e,a);l&&this.storeRelation(d.id,t,l,a),this.loadNestedRelations(s,d.id,d);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let 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(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let c of Array.from(e.childQueries)){let d=this.queryNodes.get(c);if(!d||!d.relationName)continue;let l=d.relationName,p=d.queryStep.query.resource,y=t.value[l];if(!y)continue;let f=y.value;if(Array.isArray(f))for(let m of f)this.sendInsertsForTree(d,m,p);else f&&typeof f=="object"&&this.sendInsertsForTree(d,f,p);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=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 a=this.getRelationalColumns(e.resource);for(let[o,{relationName:s,targetResource:c}]of Array.from(a)){let d=n[o];if(d){this.ensureObjectNode(d,c);let l=this.getInverseRelationName(e.resource,c,s);this.storeRelation(e.resourceId,d,s,l);}}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 d of Array.from(c.subscriptions))try{d(e);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:l,queryHash:c.hash,resource:e.resource,resourceId:e.resourceId,stepPath:c.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let n=S(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=[],d=[];for(let p of u)a.has(p)?d.push(p):s.push(p);for(let p of Array.from(a))o.has(p)||c.push(p);for(let p of s){let y=this.queryNodes.get(p);y&&y.trackedObjects.add(e.resourceId);}for(let p of c){let y=this.queryNodes.get(p);y&&y.trackedObjects.delete(e.resourceId);}let l=this.objectNodes.get(e.resourceId);if(l){for(let p of s)l.matchedQueries.add(p);for(let p of c)l.matchedQueries.delete(p);}for(let p of [...c,...d]){let y=this.queryNodes.get(p);if(y)for(let f of Array.from(y.subscriptions))try{f(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(s.length>0)for(let p of s){let y=this.queryNodes.get(p);if(!y)continue;let f=this.buildIncludeFromChildQueries(p);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(y,m[0],e.resource);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?ve([]):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 y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=y==null?void 0:y.queryStep.query.resource,m=f?this.getInverseRelationName(f,u,r.relationName):void 0,T=m?s.referencesObjects.get(m):void 0;if(!T)return {hash:r.hash,matches:false};let g=this.objectNodes.get(T);return !g||!y||!g.matchedQueries.has(y.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!a)return {hash:r.hash,matches:true};let c=z(a,u,this.schema),d=Object.keys(c).length>0;if(!d&&t!==void 0)return {hash:r.hash,matches:j(t,a)};let l=await this.storage.get({resource:u,where:{id:o},include:d?c:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let p=S(l[0]);return p?{hash:r.hash,matches:j(p,a)}:{hash:r.hash,matches:false}})).then(r=>r.filter(a=>a.matches).map(a=>a.hash))}};var Rr=i=>i,Ft=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],Bt=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=S(t),n.id=e.value.id,r=true);}return r?t:void 0}),zt=i=>i.length===1?i[0]:(async e=>{for(let t of i)await t(e);}),Ie=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 Ft){let r=e.map(a=>a[n]).filter(a=>a!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=zt(r):t[n]=Bt(r));}return t},br=(...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=Ie(r);a&&(e[n]=a);}return e};var tt=Be(Ce());var fe=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()}),Le=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()})),tn=Le.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ze=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),Ye=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),J=Ze.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:Ye}),Y=Ze.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:tn,meta:Ye});zod.z.union([Y,J]);var Xe=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var et=fe.omit({resource:true}),he=J.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:J.shape.meta}),Ae=Y.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([Ae,he]);var je=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(je);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=je(n);return e}return i},nt=i=>{let e=i.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,a={headers:r,cookies:r.cookie?tt.default.parse(r.cookie):{}},u=new URL(t.url),o=u.pathname.split("/"),s=u.searchParams,c=je(rn__default.default.parse(s.toString())),d=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:a.headers,cookies:a.cookies,queryParams:c}))??{};if(t.method==="GET"){let l=o[o.length-1],{success:p,data:y,error:f}=et.safeParse(c);if(!p)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:f},{status:400});let m=await i.handleQuery({req:{...a,...y,type:"QUERY",resource:l,context:d,queryParams:c}});return !m||!m.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(m.data)}if(t.method==="POST")try{let l=o[o.length-1],p=o[o.length-2];if(p==="query"){if(o.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let h=o[o.length-3],R=t.body?await t.json():{};if(!h||h.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let b=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h,procedure:l,input:R.input,context:d,queryParams:c}});return Response.json(b)}let y=p,f=t.body?await t.json():{},m,T=l;if(l==="insert"||l==="update"){let h=Ae.safeParse(f);if(h.success)m=h.data,T=l.toUpperCase();else {if(!(typeof f=="object"&&f!==null&&"payload"in f&&"meta"in f))return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:h.error},{status:400});let b=he.safeParse(f);if(!b.success)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b.error},{status:400});m=b.data;}}else {let{success:h,data:R,error:b}=he.safeParse(f);if(!h)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});m=R;}let g=await i.handleMutation({req:{...a,type:"MUTATE",resource:y,input:m.payload,context:d,resourceId:m.resourceId,procedure:T,queryParams:{},meta:m.meta}});return Response.json(g)}catch(l){return e.error("Error parsing mutation from the client:",l),l instanceof Error&&l.message.includes("Unknown procedure")?Response.json({message:l.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(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var at=Be(Ce());var _=zod.z.string(),Ee=zod.z.union([Xe,fe]),an=zod.z.object({id:_,type:zod.z.literal("SUBSCRIBE")}).and(Ee),sn=zod.z.object({id:_,type:zod.z.literal("UNSUBSCRIBE")}).and(Ee),on=zod.z.object({id:_,type:zod.z.literal("QUERY")}).and(Ee),un=zod.z.object({id:_,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),rt=Y.extend({id:_}),cn=J.extend({id:_}),ln=zod.z.union([cn,rt]),it=zod.z.union([an,on,un,ln,sn]),dn=zod.z.object({id:_,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),yn=zod.z.object({id:_,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([dn,yn,rt]);zod.z.object({resource:zod.z.string(),data:zod.z.array(Le)});var st=i=>{let e={},t=i.logger;return (n,r)=>{var l;let a=p=>{n.send(JSON.stringify(p));},u=le(),o=new Map,s={headers:r.headers,cookies:typeof r.headers.cookie=="string"?at.default.parse(r.headers.cookie):{}},c=rn.parse(r.url.split("?")[1]),d=(l=i.contextProvider)==null?void 0:l.call(i,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:c});e[u]=n,t.info("Client connected:",u),n.on("message",async p=>{try{t.debug("Message received from the client:",p);let y=it.parse(JSON.parse(p.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:f,id:m,...T}=y,g=f==="SUBSCRIBE";if("procedure"in T){let h=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:T.resource,procedure:T.procedure,input:T.input,context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(g){if(!h||!h.data||!h.query)throw new Error("Invalid resource");h.unsubscribe&&o.set(Q(T),h.unsubscribe),a({id:m,type:"REPLY",data:{resource:h.query.resource,data:(h.data??[]).map(R=>R.value)}});}else a({id:m,type:"REPLY",data:h});}else {let h=await i.handleQuery({req:{...s,...T,type:"QUERY",context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(!h||!h.data)throw new Error("Invalid resource");g&&h.unsubscribe&&o.set(Q(T),h.unsubscribe),a({id:m,type:"REPLY",data:{resource:T.resource,data:(h.data??[]).map(R=>R.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:f,id:m,...T}=y,g=o.get(Q(T));g&&(g(),o.delete(Q(T)));}else if(y.type==="CUSTOM_QUERY"){let{resource:f,procedure:m,input:T,id:g}=y;t.debug("Received custom query from client:",y);try{let h=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:f,procedure:m,input:T,context:await d??{},queryParams:c}});a({id:g,type:"REPLY",data:h});}catch(h){a({id:g,type:"REJECT",resource:f,message:h.message}),t.error("Error handling custom query from the client:",h);}}else if(y.type==="MUTATE"){let{resource:f}=y;t.debug("Received mutation from client:",y);try{let m=await i.handleMutation({req:{...s,type:"MUTATE",resource:f,input:y.payload,context:{messageId:y.id,...await d??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:c,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&a({id:y.id,type:"REPLY",data:m});}catch(m){a({id:y.id,type:"REJECT",resource:f,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",u),delete e[u];for(let p of Array.from(o.values()))p();});}};function ot(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Hr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,st(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{nt(e)(ot(n)).then(u=>u.json().then(o=>r.status(u.status).send(o)));});};var Te=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 mn=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Oe=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>mn(n)?S(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function U(i,e,t){let n=new Oe(i),r=u=>{let o=Te._init(u,n,true);return Object.assign(Object.create(o),{insert:async c=>{let d=i._getTimestamp(),l=await i.rawInsert(u.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([p,y])=>[p,{value:y,_meta:{timestamp:d}}]))},void 0,t);return S(l.data)},update:async(c,d)=>{let l=i._getTimestamp(),{id:p,...y}=d,f=await i.rawUpdate(u.name,c,{value:Object.fromEntries(Object.entries(y).map(([g,h])=>[g,{value:h,_meta:{timestamp:l}}]))},void 0,t),m=S(f.data),T={};for(let g of Object.keys(y))g in m&&(T[g]=m[g]);return T}})},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 d=i._getTimestamp();return i.rawInsert(s.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([l,p])=>[l,{value:p,_meta:{timestamp:d}}]))},void 0,t).then(l=>S(l.data))};if(o==="update")return (s,c,d)=>{let l=i._getTimestamp(),{id:p,...y}=d;return i.rawUpdate(s.name,c,{value:Object.fromEntries(Object.entries(y).map(([f,m])=>[f,{value:m,_meta:{timestamp:l}}]))},void 0,t).then(f=>{let m=S(f.data),T={};for(let g of Object.keys(y))g in m&&(T[g]=m[g]);return T})};if(o==="transaction")return async s=>i.transaction(async({trx:c,commit:d,rollback:l})=>{let p=U(c,e,t);return s({trx:p,commit:d,rollback:l})});if(o in e){let s=e[o];return r(s)}}};return new Proxy({},a)}var Pe=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)}},ri=i=>Pe.create({...i}),ct=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),lt=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),Ne=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:lt,query:ct}),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=Q(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=U(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,d=this.customMutations[s.procedure]?s.procedure:c&&this.customMutations[c]?c:s.procedure,l=this.customMutations[d];if(l){s.procedure=d;let p=l.inputValidator["~standard"].validate(s.input),y=p instanceof Promise?await p:p;if(y.issues){let f=y.issues.map(m=>{var g;let T=(g=m.path)==null?void 0:g.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return T?`${T}: ${m.message}`:m.message}).join(", ");throw new Error(`Validation failed: ${f}`)}return s.input=y.value,l.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=U(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(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return 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 d,l,p,y,f,m,T;if(n==="INSERT"){let{data:g,acceptedValues:h}=await o.rawInsert(e.resource,e.resourceId,u,(d=e.context)==null?void 0:d.messageId,e.context);if(!h)throw new Error("Mutation rejected");let R=S(g);if(R.id=R.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let x=z(b,e.resource,r),w=Object.keys(x).length>0?await o.rawFindById(e.resource,e.resourceId,x):g,O=S(w);if(O.id=O.id??e.resourceId,!j(O,b))throw new Error("Not authorized")}}return {data:g,acceptedValues:h}}if((y=(p=this.authorization)==null?void 0:p.update)!=null&&y.preMutation){let g=S(a);g.id=g.id??e.resourceId;let h=this.authorization.update.preMutation({ctx:e.context,value:g});if(typeof h=="boolean"){if(!h)throw new Error("Not authorized")}else {let R=z(h,e.resource,r),b=Object.keys(R).length>0?await o.rawFindById(e.resource,e.resourceId,R):a,x=S(b);if(x.id=x.id??e.resourceId,!j(x,h))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((T=(m=this.authorization)==null?void 0:m.update)!=null&&T.postMutation){let g=S(s);g.id=g.id??e.resourceId;let h=this.authorization.update.postMutation({ctx:e.context,value:g});if(typeof h=="boolean"){if(!h)throw new Error("Not authorized")}else {let R=z(h,e.resource,r),b=Object.keys(R).length>0?await o.rawFindById(e.resource,e.resourceId,R):s,x=S(b);if(x.id=x.id??e.resourceId,!j(x,h))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)}},Ve=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=U(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 d=c.inputValidator["~standard"].validate(s.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.issues.map(y=>{var m;let f=(m=y.path)==null?void 0:m.map(T=>typeof T=="object"&&"key"in T?String(T.key):String(T)).join(".");return f?`${f}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}return s.input=l.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=U(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(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return 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 ii(i){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>i({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var ke=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Ne(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:lt,query:ct}),n={},r={};for(let[a,u]of Object.entries(t))u._type==="mutation"?n[a]=u:r[a]=u;return new Ve(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}},ai=ke.create;var X=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 S(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(([d,l])=>[d,{value:l,_meta:{timestamp:r}}]))}),s=S(o.data),c={};for(let d of Object.keys(u))d in s&&(c[d]=s[d]);return c}};var xn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function q(i){var r,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 dt(i){let e=q(i);return xn[e]}var Sn="42701";function ee(i){var t;if(i.code===Sn)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 qe(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 vn(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`
|
|
2
2
|
DO $$ BEGIN
|
|
3
|
-
CREATE TYPE ${kysely.sql.id(u)} AS ENUM (${kysely.sql.raw(
|
|
3
|
+
CREATE TYPE ${kysely.sql.id(u)} AS ENUM (${kysely.sql.raw(s)});
|
|
4
4
|
EXCEPTION
|
|
5
5
|
WHEN duplicate_object THEN null;
|
|
6
6
|
END $$;
|
|
7
|
-
`.execute(i);}catch(
|
|
7
|
+
`.execute(i);}catch(s){n==null||n.warn("Could not create enum type",u,s);}}}function te(i,e){return i.some(t=>t.name===e)}function wn(i,e){return (i==null?void 0:i.columns.some(t=>t.name===e))??false}function $e(i,e){let[t]=e.split(".");return te(i,t)}function Qe(i,e,t,n=false){let r=i;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&$e(t,e.references)&&(r=r.references(e.references)),r}function Mn(i,e,t,n,r){let a=[];for(let[u,o]of Object.entries(i.fields)){let s=e==null?void 0:e.columns.find(d=>d.name===u),c=o.getStorageFieldType();s?(s.dataType,c.type):(a.push({name:u,storageFieldType:c}),c.references&&!$e(t,c.references)&&n.push({tableName:r,columnName:u,references:c.references}));}return a}function yt(i,e){return e==="postgres"&&!!i.enumValues&&i.enumValues.length>0&&!!i.enumName}async function In(i,e,t,n,r,a){if(t.length===0)return;let u=i.schema.createTable(e);for(let{name:o,storageFieldType:s}of t)if(yt(s,r))u=u.addColumn(o,kysely.sql.raw(s.enumName),c=>Qe(c,s,n));else {let c=qe(s,r);u=u.addColumn(o,c,d=>Qe(d,s,n));}await u.execute().catch(o=>{if(!ee(o))throw a==null||a.error("Error creating table",e,o),o});}async function Cn(i,e,t,n,r,a,u){for(let{name:o,storageFieldType:s}of t){let c=s.references?$e(n,s.references):false,d=yt(s,a)?kysely.sql.raw(s.enumName):qe(s,a);await i.schema.alterTable(e).addColumn(o,d,l=>Qe(l,s,n,!c)).execute().catch(l=>{if(!ee(l))throw u==null||u.error("Error adding column",o,l),l}),s.references&&!c&&!r.some(l=>l.tableName===e&&l.columnName===o)&&r.push({tableName:e,columnName:o,references:s.references}),s.index&&await i.schema.createIndex(`${e}_${o}_index`).on(e).column(o).execute().catch(()=>{});}}async function Ln(i,e,t,n,r,a){let u=`${e}_meta`,o=[];for(let[s,c]of Object.entries(t.fields)){let d=c.getStorageFieldType();wn(n,s)||o.push({name:s,storageFieldType:d});}if(!n&&o.length>0){let s=i.schema.createTable(u);for(let{name:c,storageFieldType:d}of o)s=s.addColumn(c,"varchar",l=>{let p=l;return d.primary&&(p=p.primaryKey(),te(r,e)&&(p=p.references(`${e}.${c}`))),p});await s.execute().catch(c=>{if(!ee(c))throw a==null||a.error("Error creating meta table",u,c),c});}else if(n)for(let{name:s,storageFieldType:c}of o)await i.schema.alterTable(u).addColumn(s,"varchar",d=>{let l=d;return c.primary&&(l=l.primaryKey(),te(r,e)&&(l=l.references(`${e}.${s}`))),l}).execute().catch(d=>{if(!ee(d))throw a==null||a.error("Error adding meta column",s,d),d});}async function pt(i,e,t,n,r){let[a,u]=n.split("."),o=`${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(o)}
|
|
10
10
|
FOREIGN KEY (${kysely.sql.id(t)})
|
|
11
|
-
REFERENCES ${kysely.sql.id(
|
|
12
|
-
`.execute(i);}catch(a){te(a)||r==null||r.warn("Could not add foreign key constraint",e,t,n,a);}}async function In(i,e,t,n){for(let{tableName:r,columnName:o,references:u}of e){let s=t.find(d=>d.name===r),a=s==null?void 0:s.columns.find(d=>d.name===o),[c]=u.split(".");s&&a&&ne(t,c)&&await pt(i,r,o,u,n);}}async function Cn(i,e,t,n){for(let[r,o]of Object.entries(e)){let u=`${r}_meta`,s=t.find(a=>a.name===u);if(s)for(let[a,c]of Object.entries(o.fields)){let d=c.getStorageFieldType(),l=s.columns.find(p=>p.name===a);d.primary&&l&&ne(t,r)&&await pt(i,u,a,`${r}.${a}`,n);}}}async function mt(i,e,t){let n=$(i),r=await i.introspection.getTables(),o=[];await bn(i,e,n,t);for(let[s,a]of Object.entries(e)){let c=r.find(p=>p.name===s),d=r.find(p=>p.name===`${s}_meta`),l=vn(a,c,r,o,s);if(c)for(let[p,y]of Object.entries(a.fields)){let f=c.columns.find(T=>T.name===p),m=y.getStorageFieldType(),h=$e(m,n);f&&f.dataType!==h&&(t==null||t.warn("Column type mismatch:",p,"expected to have type:",h,"but has type:",f.dataType));}!c&&l.length>0?await Sn(i,s,l,r,n,t):c&&await wn(i,s,l,r,o,n,t),await Mn(i,s,a,d,r,t);}let u=await i.introspection.getTables();await In(i,o,u,t),await Cn(i,e,u,t);}function ge(i,e,t,n){if(!i)throw new Error("Schema not initialized");let r=i[e];if(!r)throw new Error("Resource not found");let o=n.$or,u=n.$and;return (o?t.or:t.and)(o?n.$or.map(s=>ge(i,e,t,s)):u?n.$and.map(s=>ge(i,e,t,s)):Object.entries(n).map(([s,a])=>{var c,d;if(r.fields[s])return (a==null?void 0:a.$eq)!==void 0?t(`${e}.${s}`,a.$eq===null?"is":"=",a.$eq):(a==null?void 0:a.$in)!==void 0?t(`${e}.${s}`,"in",a.$in):(a==null?void 0:a.$not)!==void 0?((c=a==null?void 0:a.$not)==null?void 0:c.$in)!==void 0?t(`${e}.${s}`,"not in",a.$not.$in):((d=a==null?void 0:a.$not)==null?void 0:d.$eq)!==void 0?t(`${e}.${s}`,a.$not.$eq===null?"is not":"!=",a.$not.$eq):t(`${e}.${s}`,a.$not===null?"is not":"!=",a.$not):(a==null?void 0:a.$gt)!==void 0?t(`${e}.${s}`,">",a.$gt):(a==null?void 0:a.$gte)!==void 0?t(`${e}.${s}`,">=",a.$gte):(a==null?void 0:a.$lt)!==void 0?t(`${e}.${s}`,"<",a.$lt):(a==null?void 0:a.$lte)!==void 0?t(`${e}.${s}`,"<=",a.$lte):t(`${e}.${s}`,a===null?"is":"=",a);if(r.relations[s]){let l=r.relations[s],p=l.entity.name;return l.type==="many"?t.exists(be(i,p,t.selectFrom(p).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),a)):ge(i,p,t,a)}return null}).filter(Boolean))}function Re(i,e,t,n){let r=i[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let o of n.$and)t=Re(i,e,t,o);return t}else if(n.$or){for(let o of n.$or)t=Re(i,e,t,o);return t}for(let[o,u]of Object.entries(n)){if(!r.relations[o])continue;let s=r.relations[o],a=s.entity.name,c=s.type==="one"?"id":s.foreignColumn,d=s.type==="one"?s.relationalColumn:"id";t=t.leftJoin(a,`${a}.${c}`,`${e}.${d}`),u instanceof Object&&!Array.isArray(u)&&u!==null&&(t=Re(i,a,t,u));}return t}function be(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=Re(i,e,t,n),t.where(r=>ge(i,e,r,n)))}function Ln(i,e,t,n,r){let o=$(r),u=e[t];if(o==="sqlite"&&(u!=null&&u.fields)){let s=Object.keys(u.fields),a=i.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);return a}return i.selectFrom(n).selectAll(n)}function An(i,e,t,n,r){let o=$(r),u=e[t];if(o==="sqlite"&&(u!=null&&u.fields)){let s=Object.keys(u.fields),a=i.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);return a}return i.selectFrom(n).selectAll(n)}function xe(i,e,t,n,r,o){if(!n)return t;if(!i)throw new Error("Schema not initialized");let u=i[e];if(!u)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:s,jsonArrayFrom:a}=r;for(let c of Object.keys(n)){if(!u.relations[c])throw new Error(`Relation ${c} not found in resource ${e}`);let d=u.relations[c],l=d.entity.name,p=n[c],y=d.type==="one"?"id":d.foreignColumn,f=d.type==="one"?d.relationalColumn:"id",m=d.type==="one"?s:a,h=pe(p)?p:null,T=h==null?void 0:h.include;t=t.select(g=>{let R=`${l}_meta`,b=An(g,i,l,l,o).whereRef(`${l}.${y}`,"=",`${e}.${f}`).select(x=>s(Ln(x,i,l,R,o).whereRef(`${R}.id`,"=",`${l}.id`)).as("_meta"));if(h!=null&&h.where&&(b=be(i,l,b,h.where)),h!=null&&h.orderBy)for(let x of h.orderBy)b=b.orderBy(`${l}.${x.key}`,x.direction);return (h==null?void 0:h.limit)!==void 0&&(b=b.limit(h.limit)),T&&Object.keys(T).length>0&&(b=xe(i,l,b,T,r,o)),m(b).as(c)});}return t}var Fe=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=dt(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 mt(this.db,e,t);}selectMetaColumns(e,t,n){var u;let r=$(this.db),o=(u=this.schema)==null?void 0:u[t];if(r==="sqlite"&&(o!=null&&o.fields)){let s=Object.keys(o.fields),a=e.selectFrom(n);for(let c of s)a=a.select(`${n}.${c}`);return a}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,o=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(a=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(a,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));o=xe(this.schema,e,o,n,this.dialectHelpers,this.db);let u=await o.executeTakeFirst();if(!u)return;let s=this.parseRelationalJsonStrings(u,e);return this.convertToMaterializedLiveType(s,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return S(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:o,sort:u}=e,s=`${t}_meta`,a=this.db.selectFrom(t).selectAll(t).select(d=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(d,t,s).whereRef(`${s}.id`,"=",`${t}.id`)).as("_meta"));a=be(this.schema,t,a,n),a=xe(this.schema,t,a,r,this.dialectHelpers,this.db),o!==void 0&&(a=a.limit(o)),u!==void 0&&u.forEach(d=>{a=a.orderBy(d.key,d.direction);});let c=await a.execute();return c.length===0?[]:c.map(d=>{let l=this.parseRelationalJsonStrings(d,t);return this.convertToMaterializedLiveType(l,t)})}async find(e,t){return (await this.get({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort})).map(r=>S(r))}async rawInsert(e,t,n,r,o){var m,h,T,g,R,b,x,w,E,D,k,Z;let u=(h=(m=this.server)==null?void 0:m.router)==null?void 0:h.getHooks(e),s=(T=this.schema)==null?void 0:T[e],[a,c]=((g=s==null?void 0:s.mergeMutation)==null?void 0:g.call(s,"set",n.value,void 0))??[n,n.value];if(!c)return {data:n,acceptedValues:null};let d=a,l={...d,value:{...d.value,id:{value:t}}};if(u!=null&&u.beforeInsert){let L=S(l);L.id=t;let M=await u.beforeInsert({ctx:o,value:L,rawValue:l,db:this});M&&(d=M);}let p={},y={};for(let[L,M]of Object.entries(d.value)){let A=(R=M._meta)==null?void 0:R.timestamp;if(!A)continue;let C=(x=(b=s==null?void 0:s.fields[L])==null?void 0:b.getStorageFieldType)==null?void 0:x.call(b);(C==null?void 0:C.type)==="jsonb"||(C==null?void 0:C.type)==="json"?p[L]=JSON.stringify(M.value):p[L]=M.value,y[L]=A;}await this.db.insertInto(e).values({...p,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute(),(E=(w=this.logger)==null?void 0:w.debug)==null||E.call(w,"[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",d,r,o==null?void 0:o.messageId);if(f&&((Z=(D=this.logger)==null?void 0:D.debug)==null||Z.call(D,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:((k=f.meta)==null?void 0:k.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,d)),u!=null&&u.afterInsert){let L={...d,value:{...d.value,id:{value:t}}},M=S(L);M.id=t,await u.afterInsert({ctx:o,value:M,rawValue:L,db:this});}return {data:d,acceptedValues:c}}async rawUpdate(e,t,n,r,o){var h,T,g,R,b,x,w,E,D,k,Z,L;let u=(T=(h=this.server)==null?void 0:h.router)==null?void 0:T.getHooks(e),s=(g=this.schema)==null?void 0:g[e],a=await this.rawFindById(e,t),[c,d]=((R=s==null?void 0:s.mergeMutation)==null?void 0:R.call(s,"set",n.value,a))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let l=c,p={...l,value:{...l.value,id:{value:t}}};if(u!=null&&u.beforeUpdate){let M=S(p);M.id=t;let A;if(a){let O={...a,value:{...a.value,id:{value:t}}};A=S(O),A.id=t;}let C=await u.beforeUpdate({ctx:o,value:M,rawValue:p,previousValue:A,previousRawValue:a,db:this});C&&(l=C);}let y={},f={};for(let[M,A]of Object.entries(l.value)){let C=(b=A._meta)==null?void 0:b.timestamp;if(!C)continue;let O=(w=(x=s==null?void 0:s.fields[M])==null?void 0:x.getStorageFieldType)==null?void 0:w.call(x);(O==null?void 0:O.type)==="jsonb"||(O==null?void 0:O.type)==="json"?y[M]=JSON.stringify(A.value):y[M]=A.value,f[M]=C;}if(Object.keys(y).length===0)return {data:l,acceptedValues:d};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(M=>M.column("id").doUpdateSet(f)).execute()]),(D=(E=this.logger)==null?void 0:E.debug)==null||D.call(E,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(o==null?void 0:o.messageId)??"(none)",hasContext:!!o,contextKeys:o?Object.keys(o):[]});let m=this.buildMutation(e,t,"UPDATE",l,r,o==null?void 0:o.messageId);if(m){(L=(k=this.logger)==null?void 0:k.debug)==null||L.call(k,"[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 M=await this.rawFindById(e,t);M&&this.trackMutation(m,M);}if(u!=null&&u.afterUpdate){let M=await this.rawFindById(e,t);if(M){let A={...M,value:{...M.value,id:{value:t}}},C=S(A);C.id=t;let O;if(a){let ht={...a,value:{...a.value,id:{value:t}}};O=S(ht),O.id=t;}await u.afterUpdate({ctx:o,value:C,rawValue:A,previousValue:O,previousRawValue:a,db:this});}}return {data:l,acceptedValues:d}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let o=Math.random().toString(36).substring(2,15),u=this.mutationStack,s=[];this.mutationStack=s;let a=await this.db.savepoint(o).execute(),c=false,d=false;try{return await e({trx:this,commit:async()=>{await a.releaseSavepoint(o).execute(),c=!0,u.push(...s);},rollback:async()=>{await a.rollbackToSavepoint(o).execute(),d=!0,s.length=0;}}).then(l=>a.isCommitted||a.isRolledBack||c||d?l:a.releaseSavepoint(o).execute().then(()=>(u.push(...s),l)))}catch(l){throw d||await a.rollbackToSavepoint(o).execute().catch(()=>{}),s.length=0,l}finally{this.mutationStack=u;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let o=new i(r,this.schema,this.logger,this.server);return o.mutationStack=t,await e({trx:o,commit:async()=>{var u,s;await r.commit().execute(),(s=(u=this.logger)==null?void 0:u.debug)==null||s.call(u,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:a})=>{var c;return {id:a.id,resource:a.resource,resourceId:a.resourceId,procedure:a.procedure,hasMeta:!!a.meta,originMutationId:((c=a.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 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:c})=>{var d;return {id:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure,hasMeta:!!c.meta,originMutationId:((d=c.meta)==null?void 0:d.originMutationId)??"(none)"}})}),this.notifyMutations(t),u}))}catch(o){throw await r.rollback().execute(),t.length=0,o}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var o,u;if($(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(s=>this.parseRelationalJsonStrings(s,t));let r={};for(let[s,a]of Object.entries(e))if(s==="_meta"&&typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{r[s]=JSON.parse(a);}catch{r[s]=a;}else r[s]=a;else if(this.isRelationalField(t,s))if(typeof a=="string")if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{let c=JSON.parse(a);if(this.schema){let d=this.schema[t],l=(o=d==null?void 0:d.relations)==null?void 0:o[s];if(l){let p=l.entity.name;r[s]=this.parseRelationalJsonStrings(c,p);}else r[s]=c;}else r[s]=c;}catch{r[s]=a;}else r[s]=a;else if(typeof a=="object"&&a!==null&&!Array.isArray(a))if(this.schema){let c=this.schema[t],d=(u=c==null?void 0:c.relations)==null?void 0:u[s];if(d){let l=d.entity.name;r[s]=this.parseRelationalJsonStrings(a,l);}else r[s]=a;}else r[s]=a;else Array.isArray(a)?r[s]=a.map(c=>{var d,l;if(typeof c=="string")try{let p=JSON.parse(c);if(this.schema){let y=this.schema[t],f=(d=y==null?void 0:y.relations)==null?void 0:d[s];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(p,m)}}return p}catch{return c}if(typeof c=="object"&&c!==null&&this.schema){let p=this.schema[t],y=(l=p==null?void 0:p.relations)==null?void 0:l[s];if(y){let f=y.entity.name;return this.parseRelationalJsonStrings(c,f)}}return c}):r[s]=a;else r[s]=a;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((o,[u,s])=>{var l,p,y,f,m,h,T,g,R;if(u==="_meta")return o;let a=(p=(l=n==null?void 0:n.fields[u])==null?void 0:l.getStorageFieldType)==null?void 0:p.call(l),c=(a==null?void 0:a.type)==="jsonb"||(a==null?void 0:a.type)==="json",d=(n==null?void 0:n.relations)&&u in n.relations;if(u==="id")o[u]={value:s};else if(c)o[u]={value:s,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[u]}};else if(d){let b=n.relations[u].entity,x=(b==null?void 0:b.name)??t;Array.isArray(s)?o[u]={value:s.map(w=>this.convertToMaterializedLiveType(w,x)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[u],relation:true}}:s!==null&&typeof s=="object"?o[u]={...this.convertToMaterializedLiveType(s,x),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[u],relation:true}}:o[u]={value:s,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[u],relation:true}};}else Array.isArray(s)?o[u]={value:s,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[u]}}:typeof s=="object"&&s!==null&&!(s instanceof Date)?o[u]={value:s,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[u]}}:o[u]={value:s,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[u]}};return o},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",r=typeof t.startTransaction=="function",o=typeof t.savepoint=="function",u=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||o&&u}buildMutation(e,t,n,r,o,u){var a;let s={};for(let[c,d]of Object.entries(r.value)){if(c==="id")continue;let l=(a=d._meta)==null?void 0:a.timestamp;l&&(s[c]={value:d.value,_meta:{timestamp:l}});}return Object.keys(s).length===0?null:{id:o??de(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:s,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:o}of n)this.server.notifySubscribers(r,o);}}};var _e=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=He({level:e.logLevel??F.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new me({router:{get:async(n,r)=>{var l;let{headers:o,cookies:u,queryParams:s,context:a}=(r==null?void 0:r.context)??{};if(!(r!=null&&r.batcher))throw new Error("Batcher is required");let c={...n,type:"QUERY",headers:o,cookies:u,queryParams:s,context:a},d=await((l=this.router.routes[n.resource])==null?void 0:l.handleQuery({req:c,batcher:r.batcher}));return (d==null?void 0:d.data)??[]},incrementQueryStep:(n,r={})=>{var s;let o=(s=this.router.routes[n.query.resource])==null?void 0:s.getAuthorizationClause({...n.query,type:"QUERY",headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context});if(typeof o=="boolean"&&!o)throw new Error("Not authorized");let u=J(n.query.where,typeof o=="object"?o:void 0);return {...n,query:{...n.query,where:u}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:o,context:u,...s}=t,a={headers:n,cookies:r,queryParams:o,context:u},c=e.subscription?this.queryEngine.subscribe(s,l=>{var p;(p=e.subscription)==null||p.call(e,l);},a):void 0;return {data:await this.queryEngine.get(s,{context:a}),unsubscribe:c}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){let t=await this.wrapInMiddlewares(async p=>{let y=this.router.routes[p.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:p,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:r,cookies:o,queryParams:u,context:s}=e.req,a={headers:r,cookies:o,queryParams:u,context:s},c=t.buildQueryRequest(),d=e.subscription?this.queryEngine.subscribe(c,p=>{var y;(y=e.subscription)==null||y.call(e,p);},a):void 0,l=await this.queryEngine.get(c,{context:a});return e.subscription?{data:l,unsubscribe:d,query:c}:l.map(p=>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)}},Li=_e.create;exports.ProcedureRoute=Ne;exports.Route=Ve;exports.RouteFactory=Qe;exports.Router=Pe;exports.SQLStorage=Fe;exports.Server=_e;exports.Storage=ee;exports.createMiddleware=Zr;exports.createServerDB=U;exports.expressAdapter=Fr;exports.routeFactory=Yr;exports.router=Gr;exports.server=Li;
|
|
11
|
+
REFERENCES ${kysely.sql.id(a)} (${kysely.sql.id(u)})
|
|
12
|
+
`.execute(i);}catch(s){ee(s)||r==null||r.warn("Could not add foreign key constraint",e,t,n,s);}}async function An(i,e,t,n){for(let{tableName:r,columnName:a,references:u}of e){let o=t.find(d=>d.name===r),s=o==null?void 0:o.columns.find(d=>d.name===a),[c]=u.split(".");o&&s&&te(t,c)&&await pt(i,r,a,u,n);}}async function jn(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 d=c.getStorageFieldType(),l=o.columns.find(p=>p.name===s);d.primary&&l&&te(t,r)&&await pt(i,u,s,`${r}.${s}`,n);}}}async function mt(i,e,t){let n=q(i),r=await i.introspection.getTables(),a=[];await vn(i,e,n,t);for(let[o,s]of Object.entries(e)){let c=r.find(p=>p.name===o),d=r.find(p=>p.name===`${o}_meta`),l=Mn(s,c,r,a,o);if(c)for(let[p,y]of Object.entries(s.fields)){let f=c.columns.find(g=>g.name===p),m=y.getStorageFieldType(),T=qe(m,n);f&&f.dataType!==T&&(t==null||t.warn("Column type mismatch:",p,"expected to have type:",T,"but has type:",f.dataType));}!c&&l.length>0?await In(i,o,l,r,n,t):c&&await Cn(i,o,l,r,a,n,t),await Ln(i,o,s,d,r,t);}let u=await i.introspection.getTables();await An(i,a,u,t),await jn(i,e,u,t);}function ge(i,e,t,n){if(!i)throw new Error("Schema not initialized");let r=i[e];if(!r)throw new Error("Resource not found");let a=n.$or,u=n.$and;return (a?t.or:t.and)(a?n.$or.map(o=>ge(i,e,t,o)):u?n.$and.map(o=>ge(i,e,t,o)):Object.entries(n).map(([o,s])=>{var c,d;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):((d=s==null?void 0:s.$not)==null?void 0:d.$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 l=r.relations[o],p=l.entity.name;return l.type==="many"?t.exists(be(i,p,t.selectFrom(p).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),s)):ge(i,p,t,s)}return null}).filter(Boolean))}function Re(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=Re(i,e,t,a);return t}else if(n.$or){for(let a of n.$or)t=Re(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,d=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(s,`${s}.${c}`,`${e}.${d}`),u instanceof Object&&!Array.isArray(u)&&u!==null&&(t=Re(i,s,t,u));}return t}function be(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=Re(i,e,t,n),t.where(r=>ge(i,e,r,n)))}function En(i,e,t,n,r){let a=q(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 On(i,e,t,n,r){let a=q(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 xe(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 d=u.relations[c],l=d.entity.name,p=n[c],y=d.type==="one"?"id":d.foreignColumn,f=d.type==="one"?d.relationalColumn:"id",m=d.type==="one"?o:s,T=ye(p)?p:null,g=T==null?void 0:T.include;t=t.select(h=>{let R=`${l}_meta`,b=On(h,i,l,l,a).whereRef(`${l}.${y}`,"=",`${e}.${f}`).select(x=>o(En(x,i,l,R,a).whereRef(`${R}.id`,"=",`${l}.id`)).as("_meta"));if(T!=null&&T.where&&(b=be(i,l,b,T.where)),T!=null&&T.orderBy)for(let x of T.orderBy)b=b.orderBy(`${l}.${x.key}`,x.direction);return (T==null?void 0:T.limit)!==void 0&&(b=b.limit(T.limit)),g&&Object.keys(g).length>0&&(b=xe(i,l,b,g,r,a)),m(b).as(c)});}return t}var De=class i extends X{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=dt(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 mt(this.db,e,t);}selectMetaColumns(e,t,n){var u;let r=q(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=xe(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 S(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(d=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(d,t,o).whereRef(`${o}.id`,"=",`${t}.id`)).as("_meta"));s=be(this.schema,t,s,n),s=xe(this.schema,t,s,r,this.dialectHelpers,this.db),a!==void 0&&(s=s.limit(a)),u!==void 0&&u.forEach(d=>{s=s.orderBy(d.key,d.direction);});let c=await s.execute();return c.length===0?[]:c.map(d=>{let l=this.parseRelationalJsonStrings(d,t);return this.convertToMaterializedLiveType(l,t)})}async find(e,t){return (await this.get({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort})).map(r=>S(r))}async rawInsert(e,t,n,r,a){var m,T,g,h,R,b,x,w,O,$,G;let u=(m=this.server)==null?void 0:m.getHooks(e),o=(T=this.schema)==null?void 0:T[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 d=s,l={...d,value:{...d.value,id:{value:t}}};if(u!=null&&u.beforeInsert){let L=S(l);L.id=t;let M=await u.beforeInsert({ctx:a,value:L,rawValue:l,db:this});M&&(d=M);}let p={},y={};for(let[L,M]of Object.entries(d.value)){let A=(h=M._meta)==null?void 0:h.timestamp;if(!A)continue;let C=(b=(R=o==null?void 0:o.fields[L])==null?void 0:R.getStorageFieldType)==null?void 0:b.call(R);(C==null?void 0:C.type)==="jsonb"||(C==null?void 0:C.type)==="json"?p[L]=JSON.stringify(M.value):p[L]=M.value,y[L]=A;}await this.db.insertInto(e).values({...p,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute(),(w=(x=this.logger)==null?void 0:x.debug)==null||w.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",d,r,a==null?void 0:a.messageId);if(f&&((G=(O=this.logger)==null?void 0:O.debug)==null||G.call(O,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:(($=f.meta)==null?void 0:$.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,d)),u!=null&&u.afterInsert){let L={...d,value:{...d.value,id:{value:t}}},M=S(L);M.id=t,await u.afterInsert({ctx:a,value:M,rawValue:L,db:this});}return {data:d,acceptedValues:c}}async rawUpdate(e,t,n,r,a){var T,g,h,R,b,x,w,O,$,G,L;let u=(T=this.server)==null?void 0:T.getHooks(e),o=(g=this.schema)==null?void 0:g[e],s=await this.rawFindById(e,t),[c,d]=((h=o==null?void 0:o.mergeMutation)==null?void 0:h.call(o,"set",n.value,s))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let l=c,p={...l,value:{...l.value,id:{value:t}}};if(u!=null&&u.beforeUpdate){let M=S(p);M.id=t;let A;if(s){let E={...s,value:{...s.value,id:{value:t}}};A=S(E),A.id=t;}let C=await u.beforeUpdate({ctx:a,value:M,rawValue:p,previousValue:A,previousRawValue:s,db:this});C&&(l=C);}let y={},f={};for(let[M,A]of Object.entries(l.value)){let C=(R=A._meta)==null?void 0:R.timestamp;if(!C)continue;let E=(x=(b=o==null?void 0:o.fields[M])==null?void 0:b.getStorageFieldType)==null?void 0:x.call(b);(E==null?void 0:E.type)==="jsonb"||(E==null?void 0:E.type)==="json"?y[M]=JSON.stringify(A.value):y[M]=A.value,f[M]=C;}if(Object.keys(y).length===0)return {data:l,acceptedValues:d};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(M=>M.column("id").doUpdateSet(f)).execute()]),(O=(w=this.logger)==null?void 0:w.debug)==null||O.call(w,"[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",l,r,a==null?void 0:a.messageId);if(m){(L=($=this.logger)==null?void 0:$.debug)==null||L.call($,"[rawUpdate] Mutation built, tracking",{mutationId:m.id,hasMeta:!!m.meta,originMutationId:((G=m.meta)==null?void 0:G.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let M=await this.rawFindById(e,t);M&&this.trackMutation(m,M);}if(u!=null&&u.afterUpdate){let M=await this.rawFindById(e,t);if(M){let A={...M,value:{...M.value,id:{value:t}}},C=S(A);C.id=t;let E;if(s){let ht={...s,value:{...s.value,id:{value:t}}};E=S(ht),E.id=t;}await u.afterUpdate({ctx:a,value:C,rawValue:A,previousValue:E,previousRawValue:s,db:this});}}return {data:l,acceptedValues:d}}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,d=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(),d=!0,o.length=0;}}).then(l=>s.isCommitted||s.isRolledBack||c||d?l:s.releaseSavepoint(a).execute().then(()=>(u.push(...o),l)))}catch(l){throw d||await s.rollbackToSavepoint(a).execute().catch(()=>{}),o.length=0,l}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 d;return {id:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure,hasMeta:!!c.meta,originMutationId:((d=c.meta)==null?void 0:d.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(q(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 d=this.schema[t],l=(a=d==null?void 0:d.relations)==null?void 0:a[o];if(l){let p=l.entity.name;r[o]=this.parseRelationalJsonStrings(c,p);}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],d=(u=c==null?void 0:c.relations)==null?void 0:u[o];if(d){let l=d.entity.name;r[o]=this.parseRelationalJsonStrings(s,l);}else r[o]=s;}else r[o]=s;else Array.isArray(s)?r[o]=s.map(c=>{var d,l;if(typeof c=="string")try{let p=JSON.parse(c);if(this.schema){let y=this.schema[t],f=(d=y==null?void 0:y.relations)==null?void 0:d[o];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(p,m)}}return p}catch{return c}if(typeof c=="object"&&c!==null&&this.schema){let p=this.schema[t],y=(l=p==null?void 0:p.relations)==null?void 0:l[o];if(y){let f=y.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 l,p,y,f,m,T,g,h,R;if(u==="_meta")return a;let s=(p=(l=n==null?void 0:n.fields[u])==null?void 0:l.getStorageFieldType)==null?void 0:p.call(l),c=(s==null?void 0:s.type)==="jsonb"||(s==null?void 0:s.type)==="json",d=(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:(y=e==null?void 0:e._meta)==null?void 0:y[u]}};else if(d){let b=n.relations[u].entity,x=(b==null?void 0:b.name)??t;Array.isArray(o)?a[u]={value:o.map(w=>this.convertToMaterializedLiveType(w,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:(T=e==null?void 0:e._meta)==null?void 0:T[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:(h=e==null?void 0:e._meta)==null?void 0:h[u]}}:a[u]={value:o,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[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,d]of Object.entries(r.value)){if(c==="id")continue;let l=(s=d._meta)==null?void 0:s.timestamp;l&&(o[c]={value:d.value,_meta:{timestamp:l}});}return Object.keys(o).length===0?null:{id:a??le(),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 _e=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=We({level:e.logLevel??D.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=Ie([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 pe({router:{get:async(a,u)=>{var y;let{headers:o,cookies:s,queryParams:c,context:d}=(u==null?void 0:u.context)??{};if(!(u!=null&&u.batcher))throw new Error("Batcher is required");let l={...a,type:"QUERY",headers:o,cookies:s,queryParams:c,context:d},p=await((y=this.router.routes[a.resource])==null?void 0:y.handleQuery({req:l,batcher:u.batcher}));return (p==null?void 0:p.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=W(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,l=>{var p;(p=e.subscription)==null||p.call(e,l);},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 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:a,queryParams:u,context:o}=e.req,s={headers:r,cookies:a,queryParams:u,context:o},c=t.buildQueryRequest(),d=e.subscription?this.queryEngine.subscribe(c,p=>{var y;(y=e.subscription)==null||y.call(e,p);},s):void 0,l=await this.queryEngine.get(c,{context:s});return e.subscription?{data:l,unsubscribe:d,query:c}:l.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)=>a=>r({req:a,next:n}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},ki=_e.create;exports.ProcedureRoute=Ve;exports.Route=Ne;exports.RouteFactory=ke;exports.Router=Pe;exports.SQLStorage=De;exports.Server=_e;exports.Storage=X;exports.createMiddleware=ii;exports.createServerDB=U;exports.defineHooks=Rr;exports.expressAdapter=Hr;exports.mergeEntityHooks=Ie;exports.mergeHooks=br;exports.routeFactory=ai;exports.router=ri;exports.server=ki;
|
package/dist/server.d.cts
CHANGED
|
@@ -366,13 +366,16 @@ declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends M
|
|
|
366
366
|
withProcedures<T extends Record<string, Procedure<any, any, any>>>(procedureFactory: (opts: {
|
|
367
367
|
mutation: MutationCreator<TSchema, TContext>;
|
|
368
368
|
query: QueryCreator<TSchema, TContext>;
|
|
369
|
-
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: T[K]
|
|
369
|
+
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: Extract<T[K], Mutation<any, any, Record<string, any>>>; }, { [K_1 in keyof T as T[K_1] extends Query<any, any, Record<string, any>> ? K_1 : never]: Extract<T[K_1], Query<any, any, Record<string, any>>>; }, TSchema, TContext>;
|
|
370
370
|
/**
|
|
371
371
|
* @deprecated Use `withProcedures` instead
|
|
372
372
|
*/
|
|
373
373
|
withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
|
|
374
374
|
mutation: MutationCreator<TSchema, TContext>;
|
|
375
|
-
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: T[K]
|
|
375
|
+
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: Extract<T[K], Mutation<any, any, Record<string, any>>>; }, { [K_1 in keyof T as T[K_1] extends Query<any, any, Record<string, any>> ? K_1 : never]: Extract<T[K_1], Query<any, any, Record<string, any>>>; }, TSchema, TContext>;
|
|
376
|
+
/**
|
|
377
|
+
* @deprecated Declare hooks with `defineHooks` and pass them to `server({ hooks })` instead.
|
|
378
|
+
*/
|
|
376
379
|
withHooks(hooks: Hooks<TResourceSchema, TSchema, TContext>): Route<TResourceSchema, TMiddleware, TCustomMutations, TCustomQueries, TSchema, TContext>;
|
|
377
380
|
getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
|
|
378
381
|
private handleSet;
|
|
@@ -414,6 +417,55 @@ declare class RouteFactory<TSchema extends Schema<any> = Schema<any>, TContext =
|
|
|
414
417
|
declare const routeFactory: typeof RouteFactory.create;
|
|
415
418
|
type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>, Record<string, any>, any, any>;
|
|
416
419
|
|
|
420
|
+
/** biome-ignore-all lint/suspicious/noExplicitAny: hooks operate generically over any entity shape */
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Schema-keyed registry of lifecycle hooks.
|
|
424
|
+
*
|
|
425
|
+
* Top-level keys are constrained to entity names on `TSchema`. Per-entity
|
|
426
|
+
* payloads (`value`, `rawValue`, `previousValue`, …) are inferred from the
|
|
427
|
+
* corresponding `TSchema[K]` collection shape.
|
|
428
|
+
*/
|
|
429
|
+
type HooksRegistry<TSchema extends Schema<any>, TContext = Record<string, any>> = {
|
|
430
|
+
[K in keyof TSchema]?: TSchema[K] extends LiveObjectAny ? Hooks<TSchema[K], TSchema, TContext> : never;
|
|
431
|
+
};
|
|
432
|
+
/**
|
|
433
|
+
* Declares lifecycle hooks for a schema.
|
|
434
|
+
*
|
|
435
|
+
* Identity function whose generic parameters constrain the returned object's
|
|
436
|
+
* top-level keys to schema entity names and thread `TContext` through to
|
|
437
|
+
* handler payloads.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* ```ts
|
|
441
|
+
* const hooks = defineHooks<typeof schema, AppContext>({
|
|
442
|
+
* posts: {
|
|
443
|
+
* beforeInsert: ({ ctx, value }) => {
|
|
444
|
+
* if (ctx?.role !== "admin") throw new Error("Unauthorized");
|
|
445
|
+
* },
|
|
446
|
+
* },
|
|
447
|
+
* });
|
|
448
|
+
* ```
|
|
449
|
+
*/
|
|
450
|
+
declare const defineHooks: <TSchema extends Schema<any>, TContext = Record<string, any>>(definition: HooksRegistry<TSchema, TContext>) => HooksRegistry<TSchema, TContext>;
|
|
451
|
+
type AnyHooks = Hooks<any, any, any>;
|
|
452
|
+
/**
|
|
453
|
+
* Combines per-entity hook slices by chaining handlers for the same entity and
|
|
454
|
+
* hook name in argument order.
|
|
455
|
+
*
|
|
456
|
+
* `before*` handlers thread their return value through the chain (a returned
|
|
457
|
+
* raw value replaces the current value for subsequent handlers). `after*`
|
|
458
|
+
* handlers simply run sequentially.
|
|
459
|
+
*/
|
|
460
|
+
declare const mergeEntityHooks: (slices: Array<AnyHooks | undefined>) => AnyHooks | undefined;
|
|
461
|
+
/**
|
|
462
|
+
* Combines multiple `defineHooks` slices into a single registry. Handlers for
|
|
463
|
+
* the same entity and hook name run sequentially in argument order; a slice
|
|
464
|
+
* that transforms a value in `beforeInsert` / `beforeUpdate` hands the result
|
|
465
|
+
* to subsequent slices.
|
|
466
|
+
*/
|
|
467
|
+
declare const mergeHooks: <TSchema extends Schema<any>, TContext = Record<string, any>>(...definitions: HooksRegistry<TSchema, TContext>[]) => HooksRegistry<TSchema, TContext>;
|
|
468
|
+
|
|
417
469
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
418
470
|
|
|
419
471
|
declare class SQLStorage extends Storage {
|
|
@@ -500,6 +552,9 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
500
552
|
readonly schema: Schema<any>;
|
|
501
553
|
readonly middlewares: Set<Middleware<any>>;
|
|
502
554
|
readonly logger: Logger;
|
|
555
|
+
readonly hooksRegistry: Map<string, Hooks<any, any, any>>;
|
|
556
|
+
private readonly initPromise;
|
|
557
|
+
private initError?;
|
|
503
558
|
contextProvider?: ContextProvider<TContext>;
|
|
504
559
|
private constructor();
|
|
505
560
|
static create<TRouter extends AnyRouter, TContext>(opts: {
|
|
@@ -508,6 +563,7 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
508
563
|
schema: Schema<any>;
|
|
509
564
|
middlewares?: Middleware<any>[];
|
|
510
565
|
contextProvider: ContextProvider<TContext>;
|
|
566
|
+
hooks?: HooksRegistry<any, TContext>;
|
|
511
567
|
logLevel?: LogLevel;
|
|
512
568
|
}): Server<TRouter, TContext>;
|
|
513
569
|
static create<TRouter extends AnyRouter>(opts: {
|
|
@@ -515,8 +571,10 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
515
571
|
storage: Storage;
|
|
516
572
|
schema: Schema<any>;
|
|
517
573
|
middlewares?: Middleware<any>[];
|
|
574
|
+
hooks?: HooksRegistry<any, Record<string, any>>;
|
|
518
575
|
logLevel?: LogLevel;
|
|
519
576
|
}): Server<TRouter, Record<string, any>>;
|
|
577
|
+
getHooks(resourceName: string): Hooks<any, any, any> | undefined;
|
|
520
578
|
handleQuery(opts: {
|
|
521
579
|
req: QueryRequest;
|
|
522
580
|
subscription?: (mutation: DefaultMutation) => void;
|
|
@@ -531,7 +589,8 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
531
589
|
use(middleware: Middleware<any>): this;
|
|
532
590
|
context(contextProvider: ContextProvider<TContext>): this;
|
|
533
591
|
private wrapInMiddlewares;
|
|
592
|
+
private ensureInitialized;
|
|
534
593
|
}
|
|
535
594
|
declare const server: typeof Server.create;
|
|
536
595
|
|
|
537
|
-
export { type AfterInsertHook, type AfterUpdateHook, type AnyProcedureRoute, type AnyRoute, type AnyRouteOrProcedure, type AnyRouter, type Authorization, type BaseRequest, type BeforeInsertHook, type BeforeUpdateHook, type ContextProvider, type Hooks, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationRequest, type MutationResult, type NextFunction, type Procedure, ProcedureRoute, type Query, type QueryProcedureRequest, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, type ServerCollection, type ServerDB, Storage, type TypedMiddleware, createMiddleware, createServerDB, expressAdapter, routeFactory, router, server };
|
|
596
|
+
export { type AfterInsertHook, type AfterUpdateHook, type AnyProcedureRoute, type AnyRoute, type AnyRouteOrProcedure, type AnyRouter, type Authorization, type BaseRequest, type BeforeInsertHook, type BeforeUpdateHook, type ContextProvider, type Hooks, type HooksRegistry, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationRequest, type MutationResult, type NextFunction, type Procedure, ProcedureRoute, type Query, type QueryProcedureRequest, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, type ServerCollection, type ServerDB, Storage, type TypedMiddleware, createMiddleware, createServerDB, defineHooks, expressAdapter, mergeEntityHooks, mergeHooks, routeFactory, router, server };
|
package/dist/server.d.ts
CHANGED
|
@@ -366,13 +366,16 @@ declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends M
|
|
|
366
366
|
withProcedures<T extends Record<string, Procedure<any, any, any>>>(procedureFactory: (opts: {
|
|
367
367
|
mutation: MutationCreator<TSchema, TContext>;
|
|
368
368
|
query: QueryCreator<TSchema, TContext>;
|
|
369
|
-
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: T[K]
|
|
369
|
+
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: Extract<T[K], Mutation<any, any, Record<string, any>>>; }, { [K_1 in keyof T as T[K_1] extends Query<any, any, Record<string, any>> ? K_1 : never]: Extract<T[K_1], Query<any, any, Record<string, any>>>; }, TSchema, TContext>;
|
|
370
370
|
/**
|
|
371
371
|
* @deprecated Use `withProcedures` instead
|
|
372
372
|
*/
|
|
373
373
|
withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
|
|
374
374
|
mutation: MutationCreator<TSchema, TContext>;
|
|
375
|
-
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: T[K]
|
|
375
|
+
}) => T): Route<TResourceSchema, TMiddleware, { [K in keyof T as T[K] extends Mutation<any, any, Record<string, any>> ? K : never]: Extract<T[K], Mutation<any, any, Record<string, any>>>; }, { [K_1 in keyof T as T[K_1] extends Query<any, any, Record<string, any>> ? K_1 : never]: Extract<T[K_1], Query<any, any, Record<string, any>>>; }, TSchema, TContext>;
|
|
376
|
+
/**
|
|
377
|
+
* @deprecated Declare hooks with `defineHooks` and pass them to `server({ hooks })` instead.
|
|
378
|
+
*/
|
|
376
379
|
withHooks(hooks: Hooks<TResourceSchema, TSchema, TContext>): Route<TResourceSchema, TMiddleware, TCustomMutations, TCustomQueries, TSchema, TContext>;
|
|
377
380
|
getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
|
|
378
381
|
private handleSet;
|
|
@@ -414,6 +417,55 @@ declare class RouteFactory<TSchema extends Schema<any> = Schema<any>, TContext =
|
|
|
414
417
|
declare const routeFactory: typeof RouteFactory.create;
|
|
415
418
|
type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>, Record<string, any>, any, any>;
|
|
416
419
|
|
|
420
|
+
/** biome-ignore-all lint/suspicious/noExplicitAny: hooks operate generically over any entity shape */
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Schema-keyed registry of lifecycle hooks.
|
|
424
|
+
*
|
|
425
|
+
* Top-level keys are constrained to entity names on `TSchema`. Per-entity
|
|
426
|
+
* payloads (`value`, `rawValue`, `previousValue`, …) are inferred from the
|
|
427
|
+
* corresponding `TSchema[K]` collection shape.
|
|
428
|
+
*/
|
|
429
|
+
type HooksRegistry<TSchema extends Schema<any>, TContext = Record<string, any>> = {
|
|
430
|
+
[K in keyof TSchema]?: TSchema[K] extends LiveObjectAny ? Hooks<TSchema[K], TSchema, TContext> : never;
|
|
431
|
+
};
|
|
432
|
+
/**
|
|
433
|
+
* Declares lifecycle hooks for a schema.
|
|
434
|
+
*
|
|
435
|
+
* Identity function whose generic parameters constrain the returned object's
|
|
436
|
+
* top-level keys to schema entity names and thread `TContext` through to
|
|
437
|
+
* handler payloads.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* ```ts
|
|
441
|
+
* const hooks = defineHooks<typeof schema, AppContext>({
|
|
442
|
+
* posts: {
|
|
443
|
+
* beforeInsert: ({ ctx, value }) => {
|
|
444
|
+
* if (ctx?.role !== "admin") throw new Error("Unauthorized");
|
|
445
|
+
* },
|
|
446
|
+
* },
|
|
447
|
+
* });
|
|
448
|
+
* ```
|
|
449
|
+
*/
|
|
450
|
+
declare const defineHooks: <TSchema extends Schema<any>, TContext = Record<string, any>>(definition: HooksRegistry<TSchema, TContext>) => HooksRegistry<TSchema, TContext>;
|
|
451
|
+
type AnyHooks = Hooks<any, any, any>;
|
|
452
|
+
/**
|
|
453
|
+
* Combines per-entity hook slices by chaining handlers for the same entity and
|
|
454
|
+
* hook name in argument order.
|
|
455
|
+
*
|
|
456
|
+
* `before*` handlers thread their return value through the chain (a returned
|
|
457
|
+
* raw value replaces the current value for subsequent handlers). `after*`
|
|
458
|
+
* handlers simply run sequentially.
|
|
459
|
+
*/
|
|
460
|
+
declare const mergeEntityHooks: (slices: Array<AnyHooks | undefined>) => AnyHooks | undefined;
|
|
461
|
+
/**
|
|
462
|
+
* Combines multiple `defineHooks` slices into a single registry. Handlers for
|
|
463
|
+
* the same entity and hook name run sequentially in argument order; a slice
|
|
464
|
+
* that transforms a value in `beforeInsert` / `beforeUpdate` hands the result
|
|
465
|
+
* to subsequent slices.
|
|
466
|
+
*/
|
|
467
|
+
declare const mergeHooks: <TSchema extends Schema<any>, TContext = Record<string, any>>(...definitions: HooksRegistry<TSchema, TContext>[]) => HooksRegistry<TSchema, TContext>;
|
|
468
|
+
|
|
417
469
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
418
470
|
|
|
419
471
|
declare class SQLStorage extends Storage {
|
|
@@ -500,6 +552,9 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
500
552
|
readonly schema: Schema<any>;
|
|
501
553
|
readonly middlewares: Set<Middleware<any>>;
|
|
502
554
|
readonly logger: Logger;
|
|
555
|
+
readonly hooksRegistry: Map<string, Hooks<any, any, any>>;
|
|
556
|
+
private readonly initPromise;
|
|
557
|
+
private initError?;
|
|
503
558
|
contextProvider?: ContextProvider<TContext>;
|
|
504
559
|
private constructor();
|
|
505
560
|
static create<TRouter extends AnyRouter, TContext>(opts: {
|
|
@@ -508,6 +563,7 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
508
563
|
schema: Schema<any>;
|
|
509
564
|
middlewares?: Middleware<any>[];
|
|
510
565
|
contextProvider: ContextProvider<TContext>;
|
|
566
|
+
hooks?: HooksRegistry<any, TContext>;
|
|
511
567
|
logLevel?: LogLevel;
|
|
512
568
|
}): Server<TRouter, TContext>;
|
|
513
569
|
static create<TRouter extends AnyRouter>(opts: {
|
|
@@ -515,8 +571,10 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
515
571
|
storage: Storage;
|
|
516
572
|
schema: Schema<any>;
|
|
517
573
|
middlewares?: Middleware<any>[];
|
|
574
|
+
hooks?: HooksRegistry<any, Record<string, any>>;
|
|
518
575
|
logLevel?: LogLevel;
|
|
519
576
|
}): Server<TRouter, Record<string, any>>;
|
|
577
|
+
getHooks(resourceName: string): Hooks<any, any, any> | undefined;
|
|
520
578
|
handleQuery(opts: {
|
|
521
579
|
req: QueryRequest;
|
|
522
580
|
subscription?: (mutation: DefaultMutation) => void;
|
|
@@ -531,7 +589,8 @@ declare class Server<TRouter extends AnyRouter, TContext = Record<string, any>>
|
|
|
531
589
|
use(middleware: Middleware<any>): this;
|
|
532
590
|
context(contextProvider: ContextProvider<TContext>): this;
|
|
533
591
|
private wrapInMiddlewares;
|
|
592
|
+
private ensureInitialized;
|
|
534
593
|
}
|
|
535
594
|
declare const server: typeof Server.create;
|
|
536
595
|
|
|
537
|
-
export { type AfterInsertHook, type AfterUpdateHook, type AnyProcedureRoute, type AnyRoute, type AnyRouteOrProcedure, type AnyRouter, type Authorization, type BaseRequest, type BeforeInsertHook, type BeforeUpdateHook, type ContextProvider, type Hooks, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationRequest, type MutationResult, type NextFunction, type Procedure, ProcedureRoute, type Query, type QueryProcedureRequest, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, type ServerCollection, type ServerDB, Storage, type TypedMiddleware, createMiddleware, createServerDB, expressAdapter, routeFactory, router, server };
|
|
596
|
+
export { type AfterInsertHook, type AfterUpdateHook, type AnyProcedureRoute, type AnyRoute, type AnyRouteOrProcedure, type AnyRouter, type Authorization, type BaseRequest, type BeforeInsertHook, type BeforeUpdateHook, type ContextProvider, type Hooks, type HooksRegistry, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationRequest, type MutationResult, type NextFunction, type Procedure, ProcedureRoute, type Query, type QueryProcedureRequest, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, type ServerCollection, type ServerDB, Storage, type TypedMiddleware, createMiddleware, createServerDB, defineHooks, expressAdapter, mergeEntityHooks, mergeHooks, routeFactory, router, server };
|