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