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