@blitznocode/blitz-orm 0.9.3 → 0.9.4

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/index.js CHANGED
@@ -6,11 +6,7 @@ var immer = require('immer');
6
6
  var objectTraversal = require('object-traversal');
7
7
  var uuid = require('uuid');
8
8
  var types = require('util/types');
9
- var Ur = require('robot3');
10
-
11
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
-
13
- var Ur__default = /*#__PURE__*/_interopDefault(Ur);
9
+ var robot3 = require('robot3');
14
10
 
15
11
  var qt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var tr=e=>{let t=[],n=new Map;return e.forEach(p=>{let{dbPath:a,contentType:d}=p,s=`${a}-${d}`;n.has(s)||(n.set(s,!0),t.push(p));}),t},Xt=async(e,t,n)=>{let a=(()=>{let h="",m=[];h+=`
16
12
  `,Object.keys(t.entities).forEach(M=>{let P=t.entities[M],{idFields:R,dataFields:g,linkFields:b,name:k}=P,y=[],I=[],T=[];if("extends"in P){let F=t.entities[P.extends];F.dataFields&&F.dataFields.forEach(w=>{y.push(w.dbPath);}),F.linkFields&&F.linkFields.forEach(w=>{I.push(w.path);}),F.idFields&&F.idFields.forEach(w=>{T.push(w);});}h+=`${k} sub ${"extends"in P?P.extends:"entity"},
@@ -63,11 +59,11 @@ ${h}`})(),d=e.dbConnectors[0].id,s=n.typeDB.get(d)?.session,B=n.typeDB.get(d)?.c
63
59
  `,n+=`fetch
64
60
  `,n+=`?queryPath as "queryPath"
65
61
  ;`,i){let m=i.filter(M=>M.$fieldType==="data");m&&m.length>0&&a(m,o);let E=i.filter(M=>M.$fieldType==="link");E&&E.length>0&&s(E,o,o);let $=i.filter(M=>M.$fieldType==="role");$&&$.length>0&&d($,o,o);}}})(t),e.tqlRequest=B?L:n;};var zt=e=>{let t=e.dataFields?.map(d=>d.path)||[],n=e.linkFields?.map(d=>d.path)||[],p=Object.keys(e.roles||{})||[];return [...t,...n,...p]},vt=(e,t)=>Object.keys(e||{}).some(p=>{if(!Array.isArray(e[p])){let a=t.idFields?.includes(p),d=t.dataFields?.some(s=>(s.dbPath===p||s.path===p)&&s?.validations?.unique);return a||d}return !1}),Wt=(e,t)=>{let n=t.dataFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],p=t.linkFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],a=Object.keys(t.roles||{}).map(s=>({path:s,dbPath:s}))||[],d=[...n,...p,...a];return Object.entries(e||{}).reduce((s,[B,L])=>{let u=d.find(r=>r.path===B);return s[u?.dbPath||B]=L,s},{})},de=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let p=(r,l)=>typeof l=="string"?r.idFields?.includes(l):r.idFields?.includes(l.$path),a=(r,l,o,f,c)=>({$path:l,$dbPath:f,$thingType:"attribute",$as:r.$as||l,$var:l,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:o,$id:r.$id,$filter:r.$filter,$isVirtual:c,$filterProcessed:!0}),d=(r,l,o,f,c)=>{let{target:i,oppositeLinkFieldsPlayedBy:h}=o;return h.map(m=>{let E=i==="role"?m.thingType:"relation",$=i==="role"?m.thing:o.relation,M={[`$${E}`]:$},P=O(n,M),R=r?.$fields?.filter(b=>p(P,b)).length===0,g=[];return typeof r!="string"?r.$fields?R?g=[...r.$fields,...P.idFields]:g=r.$fields:g=zt(P):g=["id"],r.$excludedFields&&(g=g.filter(b=>p(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:E,$plays:o.plays,$playedBy:m,$path:m.path,$dbPath:c,$as:r.$as||l,$var:l,$thing:$,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:i,$intermediary:m.relation,$justId:f,$id:r.$id,$filter:Wt(r.$filter,P),$idNotIncluded:R,$filterByUnique:vt(r.$filter,P),$filterProcessed:!0}})},s=(r,l,o,f,c)=>o.playedBy.map(i=>{let{thing:h,thingType:m,relation:E}=i,$={[`$${m}`]:h},M=O(n,$),P=r?.$fields?.filter(g=>M?.idFields?.includes(g)||M?.idFields?.includes(g.$path)).length===0,R=[];return typeof r!="string"?r.$fields?P?R=[...r.$fields,...M.idFields]:R=r.$fields:R=zt(M):R=["id"],r.$excludedFields&&(R=R.filter(g=>p(M,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:m,$path:l,$dbPath:c,$as:r.$as||l,$var:l,$thing:h,$fields:R,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:f,$id:r.$id,$filter:Wt(r.$filter,M),$idNotIncluded:P,$filterByUnique:vt(r.$filter,M),$playedBy:i,$filterProcessed:!0}}),B=(r,l)=>{let o=typeof r=="string"?r:r.$path,f=typeof r=="string",c=l.dataFields?.find(m=>m.path===o),i=l.linkFields?.find(m=>m.path===o),h=l.roles?.[o];if(c){let m=c.isVirtual&&c.default;return a(r,o,f,c.dbPath,m)}else {if(i)return d(r,o,i,f,i.dbPath);if(h)return s(r,o,h,f,h.dbPath)}return null},u=(r=>immer.produce(r,l=>objectTraversal.traverse(l,o=>{let{value:f,meta:c}=o,i=f;if(radash.isObject(i)){if(i.$id){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},m=O(n,h);if(!m?.name)throw new Error(`Schema not found for ${i.$thing}`);if(i.$path=m.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),m?.idFields?.length===1){let[E]=m.idFields;i.$filter={...i.$filter,[E]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i||"$thing"in i){let h=O(n,i);if(!h?.name)throw new Error(`Schema not found for ${i.$thing}`);i.$path=h.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),radash.isObject(i)&&"$thing"in i){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[H]=c.nodePath;let m=O(n,h);if(i.$filter&&(i.$filterByUnique=vt(i.$filter,m),i.$filterProcessed||(i.$filter=Wt(i.$filter,m))),i.$fields){i.$fields.filter(M=>m?.idFields?.includes(M)||m?.idFields?.includes(M.$path)).length>0||(i.$fields=[...i.$fields,...Array.isArray(m.idFields)?m.idFields:[]],i.$idNotIncluded=!0);let $=i.$fields?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}else {let $=zt(m)?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}i.$excludedFields&&(i.$fields=i.$fields.filter(E=>p(m,E)?!0:!i.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=u;};var yt=async(e,t)=>{let n=t.dbConnectors[0].id,p=e.typeDB?.get(n)?.session,a=e.typeDB?.get(n)?.client;if(!p||!p.isOpen()){if(!a)throw new Error("Client not found");p=await a.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(n,{client:a,session:p});}return {client:a,session:p}};var ue=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:p,tqlRequest:a,config:d}=e;if(!p)throw new Error("BQL request not parsed");if(!a)throw new Error("TQL request not built");let s=new typedbDriver.TypeDBOptions;if(s.infer=!0,Array.isArray(a)){let L=await radash.parallel(a.length,a,async u=>{let{session:r}=await yt(n,d),l=await r.transaction(typedbDriver.TransactionType.READ,s);if(!l)throw new Error("Can't create transaction");let f=await l.query.fetch(u).collect();return await l.close(),f});t.rawTqlRes=L,t.isBatched=!0;}else {let{session:L}=await yt(n,d),u=await L.transaction(typedbDriver.TransactionType.READ,s);if(!u)throw new Error("Can't create transaction");let l=await u.query.fetch(a).collect();await u.close(),t.rawTqlRes=l;}};var he=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,p=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,a=/filterByUnique:([a-zA-Z0-9_\-·]+)/,d=e.match(t),s=e.match(n),B=e.match(p),L=e.match(a);return {as:d?d[1]:null,justId:s?s[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:L?L[1]:null}},ur=e=>{try{let n=(a=>{let d=a.replace("$metadata:","");return d=d.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),d=d.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,B,L)=>/^{.*}$/.test(L)?`:${L}`:`:${B}"${L}"`),d=d.replace(/\[([^\]]+)\]/g,(s,B)=>`[${B.split(",").map(L=>L.trim().startsWith("{")&&L.trim().endsWith("}")?L.trim():`"${L.trim()}"`).join(",")}]`),d})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:p,schema:a,config:d}=e,{rawTqlRes:s,isBatched:B}=t;if(n){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let L=(i,h)=>{let{$metaData:m}=i,{as:E}=ur(m),$=Object.entries(i).filter(([M])=>M!=="type"&&!M.includes("$")).map(([M,P])=>{let R=h.dataFields?.find(y=>y.path===M||y.dbPath===M),g=M==="id",b=Array.isArray(E)?E.find(y=>y[M])?.[M]:M,k;if(R?.cardinality==="ONE"){if(k=P[0]?P[0].value:d.query?.returnNulls?null:void 0,R.contentType==="DATE"&&(k=k&&`${k}Z`),g)return [[b,k],["$id",k]].filter(([y,I])=>I!==void 0)}else if(R?.cardinality==="MANY"){if(!radash.isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return d.query?.returnNulls?[[b,null]]:[];R.contentType==="DATE"?k=P.map(y=>`${y.value}Z`):k=P.map(y=>y.value);}return [[b,k]].filter(([y,I])=>I!==void 0)}).flat();return Object.fromEntries([...$])},u=i=>i.reduce((h,m)=>{let{$roleFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T?.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return k.length>0?h[P]=M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls&&(h[P]=null),h},{}),r=i=>i.reduce((h,m)=>{let{$linkFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return h[P]=k.length>0?M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls?null:void 0,h},{}),l=i=>{let h=Object.keys(i),m=h.find(y=>y.endsWith(".$dataFields"));if(!m)throw new Error("No datafields");let E=i[m],$=m.split(".")[m.split(".").length-2];if(E.$metaData=$,E.length===0)throw new Error("No datafields");let M=E.type,P={$thing:M.label,$thingType:M.root,[H]:i.queryPath.value},R={[`$${P.$thingType}`]:P.$thing},g=O(a,R),b=h.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(I=>I.path===y.split(".").pop())).map(y=>({$linkFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(I=>I.path===y.split(".").pop())?.cardinality})),k=h.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:P,currentSchema:g,linkFields:b,roleFields:k}},o=i=>i.map(h=>{let{dataFields:m,currentSchema:E,linkFields:$,roleFields:M,schemaValue:P}=l(h),R=L(m,E),g=r($),b=u(M),k=p?.$fields?.every(I=>!E?.idFields?.includes(I)&&!E?.idFields?.includes(I.$path));return {...g,...b,...P,...!d.query?.noMetadata&&p.$id?{$id:Array.isArray(p.$id)?R.id:p.$id}:{},...k?Object.fromEntries(Object.entries(R).filter(([I])=>!E?.idFields?.includes(I))):R}}),c=(i=>{let h=m=>{let E=o(m);return p.$id&&!Array.isArray(p.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return B?i.map(h):h(i)})(s);t.bqlRes=c;};var hr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,fr=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$e=e=>{let n=e.toString().replace(hr,"").trim().split("=>")[0].split("{")[0].replace(fr,"").trim(),p=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return p?(p.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(d=>d.includes("{")&&d.includes("}")?(d.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):d.trim()).filter(Boolean):[]};var lt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(n){let{fn:a}=t.default,s=$e(a).filter(B=>!(B in e));if(s.length)throw new Error(`Virtual field: Missing arguments ${s.join(", ")}`)}return "default"in t?t.default?.fn(e):void 0};var me=async(e,t)=>{let{schema:n,enrichedBqlQuery:p}=e,{bqlRes:a}=t;if(!a)return;let s=(B=>immer.produce(B,L=>objectTraversal.traverse(L,({value:u})=>{if(radash.isObject(u)){let r=u;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let l=O(n,r),{virtualFields:o}=l,f=r[H];if(!f)throw new Error("[Internal] QueryPath is missing");let c=objectTraversal.getNodeByPath(p,f),i=c.$fields.map(m=>m.$path),h=c.$excludedFields;o.forEach(m=>{if(h?.includes(m)||i.length>0&&!i.includes(m))return;let E=l.dataFields?.find($=>$.path===m);if(E?.default){let $=lt({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[m]=$;}else if(r[m]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${m}`)}),h&&h.forEach(m=>{if(typeof m!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[m];});}}})))(a);t.bqlRes=s;};var Fe=async(e,t)=>{let{config:n}=e,{bqlRes:p}=t;if(!p)return;let d=(L=>immer.produce(L,u=>objectTraversal.traverse(u,({value:r})=>{radash.isObject(r);})))(p),B=(L=>immer.produce(L,u=>objectTraversal.traverse(u,({value:r})=>{if(radash.isObject(r)){let l=r;Object.keys(l).forEach(o=>{l[o]===void 0&&delete l[o];}),Object.getOwnPropertySymbols(l).forEach(o=>{delete l[o];}),n.query?.noMetadata===!0&&Object.keys(l).forEach(o=>{o.startsWith("$")&&delete l[o];});}})))(d);t.bqlRes=B;};var Br={query:[de,le,ue,fe,me,Fe]},Ee=async(e,t,n={},p=!0)=>{for(let a of e){let d=await a(t,n);if(d&&Array.isArray(d))for(let s of d)await Ee(s.pipeline,s.req,s.res,!1);}return p&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Tt=(e,t,n,p)=>Ee(Br.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:p},{});var ct=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var we=(e,t,n)=>{let p=radash.isArray(e[t])?e[t]:[e[t]];if(!p.every(a=>typeof a=="object"))if(p.every(a=>typeof a=="string")){let a=ct(t,n),[d]=a,s=e.$op==="create"?"link":"replace",B=d.thing,L=d.thingType;if(p.some(u=>u.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:s,$thing:B,$thingType:L,$bzId:`S_${uuid.v4()}`};}else throw new Error("[Mutation Error] Replace can only be used with a single id or an array of ids")};var gt=(e,t,n)=>{let p=O(n,t),{usedDataFields:a}=U(p,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&a.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&a.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Mt=(e,t,n)=>{let p=O(n,t),{usedFields:a}=U(p,t);return t.$op?(gt(e,t,n),t.$op):t.$id||t.$filter?a.length>0?(gt(e,{...t,$op:"update"},n),"update"):(gt(e,{...t,$op:"link"},n),"link"):(gt(e,{...t,$op:"create"},n),"create")};var Te=(e,t)=>{let p=(radash.isArray(e.$root)?e.$root:[e.$root]).map(a=>{let d=Mt(a,a,t);return {...{...a.$thing?{}:{$thing:a.$entity||a.$relation},...a.$thingType?{}:{$thingType:oe(a,t)},...a.$op?{}:{$op:d},...a.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...a}});e.$root=radash.isArray(e.$root)?p:p[0];};var kt=(e,t)=>{let n=t[bt];return types.isSet(n)?n.has("clean")?(Reflect.set(t,bt,n.add("clean")),!0):!1:(Reflect.set(t,bt,new Set(["clean"])),!0)};var Me=(e,t,n)=>{if(kt("split_ids",e)){let p=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(a=>{if(radash.isObject(a)&&"$id"in a&&radash.isArray(a.$id)){let d=a;if(O(n,d),!d.$bzId)throw new Error("[Internal Error] No bzId found");return d.$id.map((s,B)=>({...K(d),$id:s,$bzId:`${d.$bzId}_${B}`,...J(d)}))}return a});(p.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=p);}};var Le=(e,t,n,p)=>{let a=(radash.isArray(e[t])?e[t]:[e[t]]).map(d=>{let s=ct(t,n),[B]=s,L=Mt(e,{...d,$thing:B.thing,$thingType:B.thingType},p),u=d.$bzId?d.$bzId:d.$tempId?d.$tempId:`N_${uuid.v4()}`;return {...d,[tt]:n,$thing:B.thing,$thingType:B.thingType,$op:L,$bzId:u}});e[t]=radash.isArray(e[t])?a:a[0];};var Qe=(e,t,n)=>{let p=e[t];p&&(radash.isArray(p)?p:[p]).forEach(a=>{let d=O(n,a),{unidentifiedFields:s}=U(d,a),{computedFields:B,virtualFields:L}=d,u=radash.listify(a,(o,f)=>f!==void 0?o:void 0),r=u.filter(o=>L?.includes(o));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(B.filter(o=>!u.includes(o)).forEach(o=>{let f=d.dataFields?.find(E=>E.path===o),i=d.linkFields?.find(E=>E.path===o)?.oppositeLinkFieldsPlayedBy[0],h="roles"in d?ne(d.roles,(E,$)=>E===o):void 0,m=f||i||h;if(!m)throw new Error(`no field Def for ${o}`);if(a.$op==="create"&&!a[o]){let E=lt({currentThing:a,fieldSchema:m,mandatoryDependencies:!0});a[o]=E;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(a)}`)});};var Ie=(e,t,n)=>{let p=ct(t,n),[a]=p;e[t]={$thing:a.thing,$thingType:a.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[tt]:n};};var Lt=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let p=`on${se(e.$op)}`;return n.pre.filter(s=>s.triggers[p]?.()).flatMap(s=>s.actions)}return []};var Re=(e,t,n)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(a=>{if("$thing"in a){let{requiredFields:d,enumFields:s,fnValidatedFields:B,dataFields:L}=O(n,a);if("$op"in a&&a.$op==="create"&&d.forEach(u=>{if(!(u in a))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in a&&a.$op==="update"||a.$op==="create")&&s.forEach(u=>{if(u in a){let r=L?.find(l=>l.path===u)?.validations?.enum;if(!r)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(radash.isArray(a[u]))a[u].some(l=>{if(!r.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(r&&!r.includes(a[u]))throw new Error(`[Validations] Option "${a[u]}" is not a valid option for field "${u}".`)}}),("$op"in a&&a.$op==="update"||a.$op==="create")&&B.forEach(u=>{if(u in a)try{let r=L?.find(l=>l.path===u)?.validations?.fn;if(!r)throw new Error("Missing validation function.");if(!r(a[u]))throw new Error("Failed validation function.")}catch(r){throw new Error(`[Validations:attribute:${u}] ${r.message}`)}}),radash.isObject(a)&&"$thing"in a){let u=a.$thing,r=a,l=radash.clone(K(e)),o=radash.clone(K(r));Lt(r,n).forEach(c=>{if(c.type==="validate"){if(c.severity!=="error")return;try{let i=c.fn(o,l);if(i===!1)throw new Error(`${c.message}.`);if(i!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(i){throw new Error(`[Validations:thing:${u}] ${i.message}`)}}});}}});};var Oe=(e,t,n)=>{let p=(radash.isArray(e[t])?e[t]:[e[t]]).map(a=>{if(wt(a)){let d=Lt(a,n).filter(L=>L.type==="transform"),s=radash.clone(K(e)),B=radash.clone(K(a));return d.forEach(L=>{let u=L.fn(B,s);Object.keys(u).length!==0&&(a={...B,...u});}),a}});e[t]=radash.isArray(e[t])?p:p[0];};var Or=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(kt("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},qr=(e,t)=>{},Ht=(e,t)=>{let p=immer.produce({$rootWrap:{$root:e}},a=>objectTraversal.traverse(a,({value:d,parent:s,key:B,meta:L})=>{if(!(!s||!B)&&radash.isObject(d)){if(!("$root"in d)){if(!("$thing"in d||"$entity"in d||"$relation"in d))throw B==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(immer.isDraft(d)?immer.current(d):d)}`)}let u=d;Object.keys(u).forEach(r=>{if(Or(u,r),r!=="$root"&&r.startsWith("$"))return;let l=r!=="$root"?xt(t,u,r):{fieldType:"rootField"};if(!l)throw new Error(`[Internal] Field ${r} not found in schema`);if("contentType"in l)return qr();if(["rootField","linkField","roleField"].includes(l.fieldType)){if(["linkField","roleField"].includes(l.fieldType)&&we(u,r,l),l.fieldType==="rootField"){if(!("$root"in u))throw new Error(`[Internal] Field ${r} is a rootField but the object is not a root`);Te(u,t);}let o=radash.isArray(u[r])?u[r]:[u[r]],f=L.nodePath?.split(".").slice(1).join(".");o.forEach(i=>{if(i){if(l?.cardinality==="ONE"&&!i.$op&&!i.$id&&!i.$filter&&!i.$tempId&&u.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${f}.${r}`);if(i.$tempId&&!(i.$op===void 0||i.$op==="link"||i.$op==="create"||i.$op==="update"))throw new Error(`Invalid op ${i.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes(l.fieldType)&&(u[r]===null?Ie(u,r,l):Le(u,r,l,t)),Me(u,r,t),["rootField","linkField","roleField"].includes(l.fieldType)&&Qe(u,r,t),(radash.isArray(u[r])?u[r]:[u[r]]).forEach(i=>{let h=O(t,i),{unidentifiedFields:m,usedLinkFields:E}=U(h,i);if(m.length>0)throw new Error(`Unknown fields: [${m.join(",")}] in ${JSON.stringify(d)}`);if(E.length>1){let $=h.linkFields?.filter(M=>E.includes(M.path));$?.some((M,P)=>$.some((R,g)=>{if(P!==g&&M.target!==R.target&&M.relation===R.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),Oe(u,r,t),Re(u,r,t);}});}}));return radash.isArray(p.$rootWrap.$root),p.$rootWrap.$root};var qe=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:p}=await yt(t,n),a=await p.transaction(typedbDriver.TransactionType.WRITE);if(!a)throw new Error("Can't create transaction");let d=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;d&&await a.query.delete(d);let B=s&&a.query.insert(s);try{let L=B?await B.collect():void 0;return await a.commit(),await a.close(),{insertions:L}}catch(L){throw await a.close(),new Error(`Transaction failed: ${L.message}`)}};var De=async(e,t,n,p)=>{let a=[...t,...n],d=a.map(s=>{let B=e.insertions?.find(L=>L.get(`${s.$bzId}`))?.get(`${s.$bzId}`);if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!B&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let L=B?.asThing().iid;if(p.mutation?.noMetadata)return Object.entries(s).filter(([l,o])=>!l.startsWith("$")).reduce((l,[o,f])=>{if(s.$thingType==="relation"){let c=a.filter(i=>i.$id&&i.$bzId===f);if(c.length>1)throw new Error(`Multiple things with the same bzId ${f}`);return c.length===1?(l[o]=c[0].$id,l):(l[o]=f,l)}return l[o]=f,l},{});let u=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:L,...s,[s.path]:s.$id,...u}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return radash.clone(d)};var xe=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(d=>d.startsWith("$")).forEach(d=>delete n[d]),Object.keys(n).filter(d=>typeof d=="symbol").forEach(d=>delete n[d])),n);return immer.produce(e,n=>objectTraversal.traverse(n,t))};var ve=async(e,t)=>{let n=u=>{let r=[],l=[],o=h=>{if(h.$id)return h.$id;let m=O(t,h),{idFields:E}=m;if(!E)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[$]=E;if(!$)throw new Error(`no idField: ${JSON.stringify(h)}`);let M=m.dataFields?.find(g=>g.path===$),P=lt({currentThing:h,fieldSchema:M,mandatoryDependencies:!0}),R=h[$]||h.$id||P;if(!R)throw new Error(`no idValue: ${JSON.stringify(h)}`);return R},f=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(h)}`);if(l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);r.push({...h,$id:m});return}h.$tempId&&h.$op==="match"||r.push(h);},c=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m),l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);l.push({...h,$id:m});return}l.push(h);};return objectTraversal.traverse(u,({value:h,parent:m,meta:E})=>{if(!radash.isObject(h))return;let $=h;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let M=O(t,$),{dataFields:P,roleFields:R,linkFields:g,usedFields:b}=U(M,$),k=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let T=b.filter(w=>P?.includes(w)),A=b.filter(w=>R?.includes(w)),F=b.filter(w=>g?.includes(w));if(T.length>0)return "update";if(A.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...radash.shake(radash.pick($,P||[""])),$op:k(),$bzId:$.$tempId?$.$tempId:$.$bzId};f(y);let I=$[tt];if(I?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let T=I.relation===$.$thing,A=T?$.$bzId:`LT_${uuid.v4()}`,w=ae(u,m,E).$bzId;if(!w)throw new Error("No parent id found");if($[Symbol.for("relation")]==="$self")return;let Q=()=>{if($.$op==="delete")return T?"match":"delete";if($.$op==="unlink")return T?"unlink":"delete";if($.$op==="link"||$.$op==="create")return T?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},C={$bzId:A,$thing:I.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:Q(),...T?{}:{[I.path]:$.$bzId},[I.plays]:w,[tt]:I,[ot]:"linkField"};c(C),($.$op==="unlink"||Q()==="unlink")&&T&&c({$thing:I.relation,$thingType:"relation",$bzId:A,$op:"match",[I.plays]:w,[tt]:I,[ot]:"linkField"});}if($.$thingType==="relation"){let T=mt($,(w,Q)=>R.includes(w)),A=radash.mapEntries(T,(w,Q)=>radash.isArray(Q)?[w,Q]:radash.isObject(Q)?[w,Q.$bzId]:[w,Q]),F=mt(h,(w,Q)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(T).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},Q=O(t,$).roles,C=radash.mapEntries(A,(N,D)=>{let z=Q[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(V=>V.$bzId||V)]}return [N,D.$bzId||D]}),S={...F,$thing:$.$thing,$thingType:"relation",$op:w(),...C,$bzId:$.$bzId,[ot]:"roleField"};c(S);return}if($.$op==="match"||$.$op==="update"&&Object.keys(T).length>0){let w=0;Object.entries(T).forEach(([Q,C])=>{let S=radash.isArray(C)?C:[C],N=D=>D==="create"||D==="replace"?"link":D;S.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let V={...F,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[Q]:D.$bzId,$bzId:$.$bzId,[ot]:"roleField"};c(V);});});}}}}}),[r,l]},[p,a]=n(e),d=p.reduce((u,r)=>{if(!r.$bzId)return [...u,r];let l=u.findIndex(o=>o.$bzId===r.$bzId);if(l===-1)return [...u,r];if(u[l].$op==="create"&&r.$op==="match")return u;if(u[l].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...u.slice(0,l),r,...u.slice(l+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${u[l].$op}. Current: ${r.$op}`)},[]),s=a.reduce((u,r)=>{let l=u.find(o=>(o.$id&&o.$id===r.$id||o.$bzId&&o.$bzId===r.$bzId)&&o.$thing===r.$thing&&o.$op===r.$op);if(l){let o={...l};return Object.keys(r).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let i=l[c],h=r[c];Array.isArray(i)&&Array.isArray(h)?o[c]=Array.from(new Set([...i,...h])):!Array.isArray(i)&&Array.isArray(h)?i!==void 0?o[c]=Array.from(new Set([i,...h])):o[c]=h:Array.isArray(i)&&!Array.isArray(h)?h!==void 0&&(o[c]=Array.from(new Set([...i,h]))):i!==null&&h!==null&&i!==void 0&&h!==void 0?o[c]=Array.from(new Set([i,h])):i==null&&(o[c]=h);}),[...u.filter(c=>!((c.$id&&c.$id===r.$id||c.$bzId&&c.$bzId===r.$bzId)&&c.$thing===r.$thing&&c.$op===r.$op)),o]}return [...u,r]},[]);d.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&s.filter(r=>r.$bzId===u.$bzId||r.$tempId&&r.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(xe(u))}`)}});let B=[...d,...s];return new Set(B.filter(u=>u.$tempId).map(u=>u.$tempId)).forEach(u=>{if(B.filter(r=>r.$tempId===u&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:d,mergedEdges:s}};var We=async(e,t,n)=>{let p=o=>{let f=o.$op,c=`$${o.$bzId}`,i=O(n,o),{idFields:h,defaultDBConnector:m}=i,E=m?.path||o.$thing,$=o.$id,M=h?.[0],P=radash.listify(o,(A,F)=>{if(A.startsWith("$")||A===M||F===void 0||F===null)return "";let w=i.dataFields?.find(S=>S.path===A);if(!w?.path)return "";let C=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${C} '${F}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${C} ${F}`;if(w.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${C} ${F.toISOString().replace("Z","")}`:`has ${C} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(A=>A),R=`${c}-atts`,g=radash.listify(o,A=>{if(A.startsWith("$")||A===M)return "";let F=i.dataFields?.find(C=>C.path===A);if(!F?.path)return "";let Q=F.dbPath;return `{${R} isa ${Q};}`}).filter(A=>A),b=radash.isArray($)?`like '${$.join("|")}'`:`'${$}'`,k=$?[`has ${M} ${b}`]:[],y=[...k,...P].filter(A=>A).join(","),I=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${c} isa ${[E,...k].filter(A=>A).join(",")};`;if(f==="update"){if(!g.length)throw new Error("update without attributes");return `${c} isa ${[E,...k].filter(A=>A).join(",")}, has ${R};
66
- ${g.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${c} isa ${[E,...k].filter(A=>A).join(",")};`:"";if(wt(o))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${c} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${c} ${P.join(",")};`:"",deletion:f==="delete"?`${c} isa ${E};`:f==="update"&&g.length?`${c} has ${R};`:""};throw new Error("in attributes")},a=o=>{let f=o.$op,c=O(n,o),i=`$${o.$bzId}`,h=o.$id,m=c.defaultDBConnector?.path||o.$thing,E="roles"in c?radash.listify(c.roles,F=>F):[],$="roles"in c?radash.mapEntries(c.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},M=radash.listify(o,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in c))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(C=>({path:Q,id:C})):{path:Q,id:w}}).filter(F=>F).flat(),P=M.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),R=M.length>0?`( ${P.join(" , ")} )`:"",g=o[ot];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=R?`${i} ${R} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",k=`${i} ${g==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${k};`:f==="unlink"?`${i} ${R};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},d=(o,f)=>{let c=f==="edges"?a:p;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k}=c(M);return radash.shake({preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k},y=>!y)}).filter(M=>M);let{preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=c(o);return radash.shake({preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},M=>!M)},s=d(e),B=Array.isArray(s)?s:[s],L=d(t,"edges"),u=Array.isArray(L)?L:[L],r=[...B,...u];return radash.shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var Kr=Symbol.for("grandChildOfCreate"),_e=async(e,t,n,p)=>{let a=(g,b)=>Object.keys(g).filter(k=>k.startsWith("$")?!1:b?!O(t,g).dataFields?.find(I=>I.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let d=[];if(objectTraversal.traverse(e,({parent:g,key:b,value:k})=>{g&&b&&!b.includes("$")&&radash.isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(I=>{if(radash.isObject(I)){if(g.$op!=="create")d.includes(I.$op)||d.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!g&&radash.isObject(k)&&(d.includes(k.$op)||d.push(k.$op));}),!d.includes("delete")&&!d.includes("unlink")&&!d.includes("replace")&&!d.includes("update")&&!d.includes("link"))return;let B=(g=>{let b=(k,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in k)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(radash.isObject(k[w])||Array.isArray(k[w]))){let Q=k[w];Array.isArray(Q)&&Q.length>0?Q.forEach(C=>{I.push({$path:w,...b(C)});}):I.push({$path:w,...b(Q)});}else T[w]=k[w];return {...T,$fields:I}};return g.map(k=>b(k,!0))})(Array.isArray(e)?e:[e]),L=await Tt(B,n,t,p),u=(g,b)=>{let k=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:k,key:b}}else return {beforePath:"root",ids:k,key:b}},r=(g,b)=>{let k=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${k}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,k,y]=g.split(/[[\]]/);return k.split(",").map(T=>`${b}${T}${y}`)}else return [g]},o={};(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,parent:I}=k;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{radash.isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),o[A]={$objectPath:T,$ids:F};}else {let F=I[y];radash.isObject(F)?(o[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(o[A]={$objectPath:T,$ids:[F.toString()]});}}})))(L||{});let c=g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;T&&y&&!y.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[Kr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):radash.isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),i=c(e),m=(g=>{let b=(T,A)=>{let F=[];T.filter(S=>S).forEach(S=>{let N=Object.keys(S).filter(D=>!D.startsWith("$")).length;if(Array.isArray(S.$id)&&N>0){let D=S.$id.map(z=>({...S,$id:z}));F=[...F,...D];}else F.push({...S});});let w=[],Q=[],C=F.filter(S=>{let D=["delete","update","unlink"].includes(S.$op||""),z=a(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&z>0||S.$filter)&&D)return !0;Q.push({...S});});return C.length>0?C.forEach(S=>{let D=(j=>{let ut=(()=>{let v={};for(let x in j){let X=O(t,j);!x.startsWith("$")&&X.dataFields?.find(at=>at.path===x)&&(v[x]=j[x]);}return v})(),ht=Object.keys(j),G=ht.filter(v=>!v.startsWith("$")),At=[],Ft=(v,x)=>{if(v===G.length){let at={...x};ht.forEach(W=>{W.startsWith("$")&&(at[W]=j[W]);}),At.push(at);return}let X={...x,[G[v]]:j[G[v]],...J(x),...ut};Ft(v+1,X),Ft(v+1,x);};return Ft(0,{...J(j)}),At})(S).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(nt=>!nt.startsWith("$")).length===0)),z=[],V=r(S.$objectPath),Y=o[V]?o[V].$ids:[],q=D.map((j,nt)=>{let ut=O(t,j),G=Object.keys(j).filter(x=>!x.includes("$")&&!ut.dataFields?.some(X=>X.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(W=>!W.$id||Array.isArray(W.$id)||W.$filter):j[x]:[j[x]]).map(W=>{let Rt=r(W.$objectPath);return {idsToKey:(Ct=>{let Yt=[],$t=Ct.split("."),Ze=$t.slice(0,$t.length-1).join("."),Ye=$t.slice($t.length-1,$t.length)[0].split("___")[1];for(let St in o)if(St.startsWith(Ze)&&St.endsWith(Ye)){let Ot=St.split("."),Ge=Ot.slice(Ot.length-1,Ot.length)[0].split("___")[0];Yt.push(Ge);}return Yt})(Rt),key:x,multiple:W}})).filter(x=>x!==void 0),v=(x=>{let X=x.map(W=>W.map(it=>it.idsToKey));return (W=>W.length>0?W.reduce((it,ft)=>it.concat(ft),[]).reduce((it,ft)=>it?ft.filter(Ct=>it.includes(Ct)):ft):[])(X)})(G).filter(x=>!z.includes(x));if(z=[...z,...v],Y=Y.filter(x=>!v.includes(x)),nt===D.length-1&&Y.length>0)return {...j,$id:Y,$bzId:`T1_${uuid.v4()}`,...J(j)};if(v.length>0)return {...j,$id:v,$bzId:`T2_${uuid.v4()}`,...J(j)}}).filter(j=>j!==void 0),Je=(()=>{if(q.length===0&&!A?.$id)return C;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],nt=[];return j.forEach(ut=>{let ht=r({...S.$objectPath,ids:ut}),G=o[ht];G&&nt.push({...S,$id:G.$ids,...J(S),$bzId:`T_${uuid.v4()}`});}),nt}else return q.filter(j=>j!==void 0)})();w=[...Q,...Je].map(k);}):w=F.map(k),w},k=T=>{let A={...T,$bzId:T.$tempId??`T3_${uuid.v4()}`,...J(T)},F=O(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],C=b(Q,T);A[w]=C.length>0?C:void 0;}),A},y=[];return g.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>k(T))})(Array.isArray(i)?i:[i]),E=g=>g.map(b=>{let k=a(b,!0),y={...b};return k.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},C=jt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&C==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let S=r(Q.$objectPath),D=l(S).map(q=>o[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let V=z.filter(q=>!F.includes(q)),Pt=F.filter(q=>!z.includes(q)),Y=J(Q);V.length>0&&A.push({...Q,$op:"unlink",$id:V,$bzId:`T4_${uuid.v4()}`,id:void 0,...Y}),Pt.length>0&&Pt.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...Y});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...Y});}),y[I]=E(A);}),y}),$=c(E(c(m)));return (g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;y&&T&&!y?.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=o[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),C=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,S=jt(t,T,F.$objectPath.key);if(F.$op==="link"&&C&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(C)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{value:y,meta:I}=k;radash.isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};var{createMachine:Jr,interpret:Zr,transition:et,reduce:rt,state:Yr,invoke:dt,guard:Gr}=Ur__default.default,Ve=Yr,Ut=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Xr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),tn=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),en=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),rn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),nn=async e=>Object.keys(e.bql.current).length?Ht(e.bql.current,e.schema):Ht(e.bql.raw,e.schema),on=async e=>_e(e.bql.current,e.schema,e.config,e.handles),sn=async e=>ve(e.bql.current,e.schema),an=async e=>We(e.bql.things,e.bql.edges,e.schema),ln=async e=>qe(e.typeDB.tqlMutation,e.handles,e.config),cn=async e=>De(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),dn=()=>!0,pt=et("error","error",rt((e,t)=>({...e,error:t.error}))),pn=Jr("enrich",{enrich:dt(nn,et("done","preQuery",Gr(dn),rt(Ut)),et("done","parseBQL",rt(Ut)),pt),preQuery:dt(on,et("done","parseBQL",rt(Ut)),pt),parseBQL:dt(sn,et("done","buildMutation",rt(tn)),pt),buildMutation:dt(an,et("done","runMutation",rt(en)),pt),runMutation:dt(ln,et("done","parseMutation",rt(rn)),pt),parseMutation:dt(cn,et("done","success",rt(Xr)),pt),success:Ve(),error:Ve()},e=>e),un=async e=>new Promise((t,n)=>{Zr(pn,p=>{p.machine.state.name==="success"&&t(p.context),p.machine.state.name==="error"&&n(p.context);},e);}),He=async(e,t,n,p)=>un({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:p,depthLevel:0,error:null});immer.enableMapSet();var Zt=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async p=>{if(p.provider==="typeDB"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(p.url);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(p.provider==="typeDBCluster"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(p.addresses,p.credentials);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=ie(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),Xt(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let p={...this.config,query:{...qt.query,...this.config.query,...n}};return Tt(t,p,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let p={...this.config,mutation:{...qt.mutation,...this.config.mutation,...n}},[a,d]=await radash.tryit(He)(t,this.schema,p,this.dbHandles);if(a)throw console.error(a.error.stack.split(`
62
+ ${g.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${c} isa ${[E,...k].filter(A=>A).join(",")};`:"";if(wt(o))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${c} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${c} ${P.join(",")};`:"",deletion:f==="delete"?`${c} isa ${E};`:f==="update"&&g.length?`${c} has ${R};`:""};throw new Error("in attributes")},a=o=>{let f=o.$op,c=O(n,o),i=`$${o.$bzId}`,h=o.$id,m=c.defaultDBConnector?.path||o.$thing,E="roles"in c?radash.listify(c.roles,F=>F):[],$="roles"in c?radash.mapEntries(c.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},M=radash.listify(o,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in c))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(C=>({path:Q,id:C})):{path:Q,id:w}}).filter(F=>F).flat(),P=M.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),R=M.length>0?`( ${P.join(" , ")} )`:"",g=o[ot];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=R?`${i} ${R} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",k=`${i} ${g==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${k};`:f==="unlink"?`${i} ${R};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},d=(o,f)=>{let c=f==="edges"?a:p;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k}=c(M);return radash.shake({preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k},y=>!y)}).filter(M=>M);let{preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=c(o);return radash.shake({preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},M=>!M)},s=d(e),B=Array.isArray(s)?s:[s],L=d(t,"edges"),u=Array.isArray(L)?L:[L],r=[...B,...u];return radash.shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var Kr=Symbol.for("grandChildOfCreate"),_e=async(e,t,n,p)=>{let a=(g,b)=>Object.keys(g).filter(k=>k.startsWith("$")?!1:b?!O(t,g).dataFields?.find(I=>I.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let d=[];if(objectTraversal.traverse(e,({parent:g,key:b,value:k})=>{g&&b&&!b.includes("$")&&radash.isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(I=>{if(radash.isObject(I)){if(g.$op!=="create")d.includes(I.$op)||d.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!g&&radash.isObject(k)&&(d.includes(k.$op)||d.push(k.$op));}),!d.includes("delete")&&!d.includes("unlink")&&!d.includes("replace")&&!d.includes("update")&&!d.includes("link"))return;let B=(g=>{let b=(k,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in k)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(radash.isObject(k[w])||Array.isArray(k[w]))){let Q=k[w];Array.isArray(Q)&&Q.length>0?Q.forEach(C=>{I.push({$path:w,...b(C)});}):I.push({$path:w,...b(Q)});}else T[w]=k[w];return {...T,$fields:I}};return g.map(k=>b(k,!0))})(Array.isArray(e)?e:[e]),L=await Tt(B,n,t,p),u=(g,b)=>{let k=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:k,key:b}}else return {beforePath:"root",ids:k,key:b}},r=(g,b)=>{let k=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${k}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,k,y]=g.split(/[[\]]/);return k.split(",").map(T=>`${b}${T}${y}`)}else return [g]},o={};(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,parent:I}=k;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{radash.isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),o[A]={$objectPath:T,$ids:F};}else {let F=I[y];radash.isObject(F)?(o[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(o[A]={$objectPath:T,$ids:[F.toString()]});}}})))(L||{});let c=g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;T&&y&&!y.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[Kr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):radash.isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),i=c(e),m=(g=>{let b=(T,A)=>{let F=[];T.filter(S=>S).forEach(S=>{let N=Object.keys(S).filter(D=>!D.startsWith("$")).length;if(Array.isArray(S.$id)&&N>0){let D=S.$id.map(z=>({...S,$id:z}));F=[...F,...D];}else F.push({...S});});let w=[],Q=[],C=F.filter(S=>{let D=["delete","update","unlink"].includes(S.$op||""),z=a(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&z>0||S.$filter)&&D)return !0;Q.push({...S});});return C.length>0?C.forEach(S=>{let D=(j=>{let ut=(()=>{let v={};for(let x in j){let X=O(t,j);!x.startsWith("$")&&X.dataFields?.find(at=>at.path===x)&&(v[x]=j[x]);}return v})(),ht=Object.keys(j),G=ht.filter(v=>!v.startsWith("$")),At=[],Ft=(v,x)=>{if(v===G.length){let at={...x};ht.forEach(W=>{W.startsWith("$")&&(at[W]=j[W]);}),At.push(at);return}let X={...x,[G[v]]:j[G[v]],...J(x),...ut};Ft(v+1,X),Ft(v+1,x);};return Ft(0,{...J(j)}),At})(S).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(nt=>!nt.startsWith("$")).length===0)),z=[],V=r(S.$objectPath),Y=o[V]?o[V].$ids:[],q=D.map((j,nt)=>{let ut=O(t,j),G=Object.keys(j).filter(x=>!x.includes("$")&&!ut.dataFields?.some(X=>X.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(W=>!W.$id||Array.isArray(W.$id)||W.$filter):j[x]:[j[x]]).map(W=>{let Rt=r(W.$objectPath);return {idsToKey:(Ct=>{let Yt=[],$t=Ct.split("."),Ze=$t.slice(0,$t.length-1).join("."),Ye=$t.slice($t.length-1,$t.length)[0].split("___")[1];for(let St in o)if(St.startsWith(Ze)&&St.endsWith(Ye)){let Ot=St.split("."),Ge=Ot.slice(Ot.length-1,Ot.length)[0].split("___")[0];Yt.push(Ge);}return Yt})(Rt),key:x,multiple:W}})).filter(x=>x!==void 0),v=(x=>{let X=x.map(W=>W.map(it=>it.idsToKey));return (W=>W.length>0?W.reduce((it,ft)=>it.concat(ft),[]).reduce((it,ft)=>it?ft.filter(Ct=>it.includes(Ct)):ft):[])(X)})(G).filter(x=>!z.includes(x));if(z=[...z,...v],Y=Y.filter(x=>!v.includes(x)),nt===D.length-1&&Y.length>0)return {...j,$id:Y,$bzId:`T1_${uuid.v4()}`,...J(j)};if(v.length>0)return {...j,$id:v,$bzId:`T2_${uuid.v4()}`,...J(j)}}).filter(j=>j!==void 0),Je=(()=>{if(q.length===0&&!A?.$id)return C;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],nt=[];return j.forEach(ut=>{let ht=r({...S.$objectPath,ids:ut}),G=o[ht];G&&nt.push({...S,$id:G.$ids,...J(S),$bzId:`T_${uuid.v4()}`});}),nt}else return q.filter(j=>j!==void 0)})();w=[...Q,...Je].map(k);}):w=F.map(k),w},k=T=>{let A={...T,$bzId:T.$tempId??`T3_${uuid.v4()}`,...J(T)},F=O(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],C=b(Q,T);A[w]=C.length>0?C:void 0;}),A},y=[];return g.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>k(T))})(Array.isArray(i)?i:[i]),E=g=>g.map(b=>{let k=a(b,!0),y={...b};return k.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},C=jt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&C==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let S=r(Q.$objectPath),D=l(S).map(q=>o[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let V=z.filter(q=>!F.includes(q)),Pt=F.filter(q=>!z.includes(q)),Y=J(Q);V.length>0&&A.push({...Q,$op:"unlink",$id:V,$bzId:`T4_${uuid.v4()}`,id:void 0,...Y}),Pt.length>0&&Pt.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...Y});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...Y});}),y[I]=E(A);}),y}),$=c(E(c(m)));return (g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;y&&T&&!y?.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=o[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),C=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,S=jt(t,T,F.$objectPath.key);if(F.$op==="link"&&C&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(C)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{value:y,meta:I}=k;radash.isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};var Ut=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Yr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Gr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Xr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),tn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),en=async e=>Object.keys(e.bql.current).length?Ht(e.bql.current,e.schema):Ht(e.bql.raw,e.schema),rn=async e=>_e(e.bql.current,e.schema,e.config,e.handles),nn=async e=>ve(e.bql.current,e.schema),on=async e=>We(e.bql.things,e.bql.edges,e.schema),sn=async e=>qe(e.typeDB.tqlMutation,e.handles,e.config),an=async e=>De(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),ln=()=>!0,pt=robot3.transition("error","error",robot3.reduce((e,t)=>({...e,error:t.error}))),cn=robot3.createMachine("enrich",{enrich:robot3.invoke(en,robot3.transition("done","preQuery",robot3.guard(ln),robot3.reduce(Ut)),robot3.transition("done","parseBQL",robot3.reduce(Ut)),pt),preQuery:robot3.invoke(rn,robot3.transition("done","parseBQL",robot3.reduce(Ut)),pt),parseBQL:robot3.invoke(nn,robot3.transition("done","buildMutation",robot3.reduce(Gr)),pt),buildMutation:robot3.invoke(on,robot3.transition("done","runMutation",robot3.reduce(Xr)),pt),runMutation:robot3.invoke(sn,robot3.transition("done","parseMutation",robot3.reduce(tn)),pt),parseMutation:robot3.invoke(an,robot3.transition("done","success",robot3.reduce(Yr)),pt),success:robot3.state(),error:robot3.state()},e=>e),dn=async e=>new Promise((t,n)=>{robot3.interpret(cn,p=>{p.machine.state.name==="success"&&t(p.context),p.machine.state.name==="error"&&n(p.context);},e);}),He=async(e,t,n,p)=>dn({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:p,depthLevel:0,error:null});immer.enableMapSet();var Zt=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async p=>{if(p.provider==="typeDB"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(p.url);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(p.provider==="typeDBCluster"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(p.addresses,p.credentials);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=ie(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),Xt(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let p={...this.config,query:{...qt.query,...this.config.query,...n}};return Tt(t,p,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let p={...this.config,mutation:{...qt.mutation,...this.config.mutation,...n}},[a,d]=await radash.tryit(He)(t,this.schema,p,this.dbHandles);if(a)throw console.error(a.error.stack.split(`
67
63
  `).slice(0,4).join(`
68
- `)),new Error(a.error.message);return d.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Bs=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
64
+ `)),new Error(a.error.message);return d.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},ys=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
69
65
  //! Todo: Sandbox the function in computeFunction()
70
66
  //! reads all the insertions and gets the first match. This means each id must be unique
71
67
  //!old
72
68
 
73
- module.exports = Bs;
69
+ module.exports = ys;
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import { enableMapSet, produce, isDraft, current } from 'immer';
4
4
  import { traverse, getNodeByPath } from 'object-traversal';
5
5
  import { v4 } from 'uuid';
6
6
  import { isSet } from 'util/types';
7
- import Ur from 'robot3';
7
+ import { transition, reduce, createMachine, invoke, guard, state, interpret } from 'robot3';
8
8
 
9
9
  var qt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var tr=e=>{let t=[],n=new Map;return e.forEach(p=>{let{dbPath:a,contentType:d}=p,s=`${a}-${d}`;n.has(s)||(n.set(s,!0),t.push(p));}),t},Xt=async(e,t,n)=>{let a=(()=>{let h="",m=[];h+=`
10
10
  `,Object.keys(t.entities).forEach(M=>{let P=t.entities[M],{idFields:R,dataFields:g,linkFields:b,name:k}=P,y=[],I=[],T=[];if("extends"in P){let F=t.entities[P.extends];F.dataFields&&F.dataFields.forEach(w=>{y.push(w.dbPath);}),F.linkFields&&F.linkFields.forEach(w=>{I.push(w.path);}),F.idFields&&F.idFields.forEach(w=>{T.push(w);});}h+=`${k} sub ${"extends"in P?P.extends:"entity"},
@@ -57,11 +57,11 @@ ${h}`})(),d=e.dbConnectors[0].id,s=n.typeDB.get(d)?.session,B=n.typeDB.get(d)?.c
57
57
  `,n+=`fetch
58
58
  `,n+=`?queryPath as "queryPath"
59
59
  ;`,i){let m=i.filter(M=>M.$fieldType==="data");m&&m.length>0&&a(m,o);let E=i.filter(M=>M.$fieldType==="link");E&&E.length>0&&s(E,o,o);let $=i.filter(M=>M.$fieldType==="role");$&&$.length>0&&d($,o,o);}}})(t),e.tqlRequest=B?L:n;};var zt=e=>{let t=e.dataFields?.map(d=>d.path)||[],n=e.linkFields?.map(d=>d.path)||[],p=Object.keys(e.roles||{})||[];return [...t,...n,...p]},vt=(e,t)=>Object.keys(e||{}).some(p=>{if(!Array.isArray(e[p])){let a=t.idFields?.includes(p),d=t.dataFields?.some(s=>(s.dbPath===p||s.path===p)&&s?.validations?.unique);return a||d}return !1}),Wt=(e,t)=>{let n=t.dataFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],p=t.linkFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],a=Object.keys(t.roles||{}).map(s=>({path:s,dbPath:s}))||[],d=[...n,...p,...a];return Object.entries(e||{}).reduce((s,[B,L])=>{let u=d.find(r=>r.path===B);return s[u?.dbPath||B]=L,s},{})},de=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let p=(r,l)=>typeof l=="string"?r.idFields?.includes(l):r.idFields?.includes(l.$path),a=(r,l,o,f,c)=>({$path:l,$dbPath:f,$thingType:"attribute",$as:r.$as||l,$var:l,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:o,$id:r.$id,$filter:r.$filter,$isVirtual:c,$filterProcessed:!0}),d=(r,l,o,f,c)=>{let{target:i,oppositeLinkFieldsPlayedBy:h}=o;return h.map(m=>{let E=i==="role"?m.thingType:"relation",$=i==="role"?m.thing:o.relation,M={[`$${E}`]:$},P=O(n,M),R=r?.$fields?.filter(b=>p(P,b)).length===0,g=[];return typeof r!="string"?r.$fields?R?g=[...r.$fields,...P.idFields]:g=r.$fields:g=zt(P):g=["id"],r.$excludedFields&&(g=g.filter(b=>p(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:E,$plays:o.plays,$playedBy:m,$path:m.path,$dbPath:c,$as:r.$as||l,$var:l,$thing:$,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:i,$intermediary:m.relation,$justId:f,$id:r.$id,$filter:Wt(r.$filter,P),$idNotIncluded:R,$filterByUnique:vt(r.$filter,P),$filterProcessed:!0}})},s=(r,l,o,f,c)=>o.playedBy.map(i=>{let{thing:h,thingType:m,relation:E}=i,$={[`$${m}`]:h},M=O(n,$),P=r?.$fields?.filter(g=>M?.idFields?.includes(g)||M?.idFields?.includes(g.$path)).length===0,R=[];return typeof r!="string"?r.$fields?P?R=[...r.$fields,...M.idFields]:R=r.$fields:R=zt(M):R=["id"],r.$excludedFields&&(R=R.filter(g=>p(M,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:m,$path:l,$dbPath:c,$as:r.$as||l,$var:l,$thing:h,$fields:R,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:f,$id:r.$id,$filter:Wt(r.$filter,M),$idNotIncluded:P,$filterByUnique:vt(r.$filter,M),$playedBy:i,$filterProcessed:!0}}),B=(r,l)=>{let o=typeof r=="string"?r:r.$path,f=typeof r=="string",c=l.dataFields?.find(m=>m.path===o),i=l.linkFields?.find(m=>m.path===o),h=l.roles?.[o];if(c){let m=c.isVirtual&&c.default;return a(r,o,f,c.dbPath,m)}else {if(i)return d(r,o,i,f,i.dbPath);if(h)return s(r,o,h,f,h.dbPath)}return null},u=(r=>produce(r,l=>traverse(l,o=>{let{value:f,meta:c}=o,i=f;if(isObject(i)){if(i.$id){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},m=O(n,h);if(!m?.name)throw new Error(`Schema not found for ${i.$thing}`);if(i.$path=m.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),m?.idFields?.length===1){let[E]=m.idFields;i.$filter={...i.$filter,[E]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i||"$thing"in i){let h=O(n,i);if(!h?.name)throw new Error(`Schema not found for ${i.$thing}`);i.$path=h.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),isObject(i)&&"$thing"in i){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[H]=c.nodePath;let m=O(n,h);if(i.$filter&&(i.$filterByUnique=vt(i.$filter,m),i.$filterProcessed||(i.$filter=Wt(i.$filter,m))),i.$fields){i.$fields.filter(M=>m?.idFields?.includes(M)||m?.idFields?.includes(M.$path)).length>0||(i.$fields=[...i.$fields,...Array.isArray(m.idFields)?m.idFields:[]],i.$idNotIncluded=!0);let $=i.$fields?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}else {let $=zt(m)?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}i.$excludedFields&&(i.$fields=i.$fields.filter(E=>p(m,E)?!0:!i.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=u;};var yt=async(e,t)=>{let n=t.dbConnectors[0].id,p=e.typeDB?.get(n)?.session,a=e.typeDB?.get(n)?.client;if(!p||!p.isOpen()){if(!a)throw new Error("Client not found");p=await a.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:a,session:p});}return {client:a,session:p}};var ue=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:p,tqlRequest:a,config:d}=e;if(!p)throw new Error("BQL request not parsed");if(!a)throw new Error("TQL request not built");let s=new TypeDBOptions;if(s.infer=!0,Array.isArray(a)){let L=await parallel(a.length,a,async u=>{let{session:r}=await yt(n,d),l=await r.transaction(TransactionType.READ,s);if(!l)throw new Error("Can't create transaction");let f=await l.query.fetch(u).collect();return await l.close(),f});t.rawTqlRes=L,t.isBatched=!0;}else {let{session:L}=await yt(n,d),u=await L.transaction(TransactionType.READ,s);if(!u)throw new Error("Can't create transaction");let l=await u.query.fetch(a).collect();await u.close(),t.rawTqlRes=l;}};var he=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,p=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,a=/filterByUnique:([a-zA-Z0-9_\-·]+)/,d=e.match(t),s=e.match(n),B=e.match(p),L=e.match(a);return {as:d?d[1]:null,justId:s?s[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:L?L[1]:null}},ur=e=>{try{let n=(a=>{let d=a.replace("$metadata:","");return d=d.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),d=d.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,B,L)=>/^{.*}$/.test(L)?`:${L}`:`:${B}"${L}"`),d=d.replace(/\[([^\]]+)\]/g,(s,B)=>`[${B.split(",").map(L=>L.trim().startsWith("{")&&L.trim().endsWith("}")?L.trim():`"${L.trim()}"`).join(",")}]`),d})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:p,schema:a,config:d}=e,{rawTqlRes:s,isBatched:B}=t;if(n){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let L=(i,h)=>{let{$metaData:m}=i,{as:E}=ur(m),$=Object.entries(i).filter(([M])=>M!=="type"&&!M.includes("$")).map(([M,P])=>{let R=h.dataFields?.find(y=>y.path===M||y.dbPath===M),g=M==="id",b=Array.isArray(E)?E.find(y=>y[M])?.[M]:M,k;if(R?.cardinality==="ONE"){if(k=P[0]?P[0].value:d.query?.returnNulls?null:void 0,R.contentType==="DATE"&&(k=k&&`${k}Z`),g)return [[b,k],["$id",k]].filter(([y,I])=>I!==void 0)}else if(R?.cardinality==="MANY"){if(!isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return d.query?.returnNulls?[[b,null]]:[];R.contentType==="DATE"?k=P.map(y=>`${y.value}Z`):k=P.map(y=>y.value);}return [[b,k]].filter(([y,I])=>I!==void 0)}).flat();return Object.fromEntries([...$])},u=i=>i.reduce((h,m)=>{let{$roleFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T?.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return k.length>0?h[P]=M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls&&(h[P]=null),h},{}),r=i=>i.reduce((h,m)=>{let{$linkFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return h[P]=k.length>0?M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls?null:void 0,h},{}),l=i=>{let h=Object.keys(i),m=h.find(y=>y.endsWith(".$dataFields"));if(!m)throw new Error("No datafields");let E=i[m],$=m.split(".")[m.split(".").length-2];if(E.$metaData=$,E.length===0)throw new Error("No datafields");let M=E.type,P={$thing:M.label,$thingType:M.root,[H]:i.queryPath.value},R={[`$${P.$thingType}`]:P.$thing},g=O(a,R),b=h.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(I=>I.path===y.split(".").pop())).map(y=>({$linkFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(I=>I.path===y.split(".").pop())?.cardinality})),k=h.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:P,currentSchema:g,linkFields:b,roleFields:k}},o=i=>i.map(h=>{let{dataFields:m,currentSchema:E,linkFields:$,roleFields:M,schemaValue:P}=l(h),R=L(m,E),g=r($),b=u(M),k=p?.$fields?.every(I=>!E?.idFields?.includes(I)&&!E?.idFields?.includes(I.$path));return {...g,...b,...P,...!d.query?.noMetadata&&p.$id?{$id:Array.isArray(p.$id)?R.id:p.$id}:{},...k?Object.fromEntries(Object.entries(R).filter(([I])=>!E?.idFields?.includes(I))):R}}),c=(i=>{let h=m=>{let E=o(m);return p.$id&&!Array.isArray(p.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return B?i.map(h):h(i)})(s);t.bqlRes=c;};var hr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,fr=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$e=e=>{let n=e.toString().replace(hr,"").trim().split("=>")[0].split("{")[0].replace(fr,"").trim(),p=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return p?(p.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(d=>d.includes("{")&&d.includes("}")?(d.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):d.trim()).filter(Boolean):[]};var lt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(n){let{fn:a}=t.default,s=$e(a).filter(B=>!(B in e));if(s.length)throw new Error(`Virtual field: Missing arguments ${s.join(", ")}`)}return "default"in t?t.default?.fn(e):void 0};var me=async(e,t)=>{let{schema:n,enrichedBqlQuery:p}=e,{bqlRes:a}=t;if(!a)return;let s=(B=>produce(B,L=>traverse(L,({value:u})=>{if(isObject(u)){let r=u;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let l=O(n,r),{virtualFields:o}=l,f=r[H];if(!f)throw new Error("[Internal] QueryPath is missing");let c=getNodeByPath(p,f),i=c.$fields.map(m=>m.$path),h=c.$excludedFields;o.forEach(m=>{if(h?.includes(m)||i.length>0&&!i.includes(m))return;let E=l.dataFields?.find($=>$.path===m);if(E?.default){let $=lt({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[m]=$;}else if(r[m]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${m}`)}),h&&h.forEach(m=>{if(typeof m!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[m];});}}})))(a);t.bqlRes=s;};var Fe=async(e,t)=>{let{config:n}=e,{bqlRes:p}=t;if(!p)return;let d=(L=>produce(L,u=>traverse(u,({value:r})=>{isObject(r);})))(p),B=(L=>produce(L,u=>traverse(u,({value:r})=>{if(isObject(r)){let l=r;Object.keys(l).forEach(o=>{l[o]===void 0&&delete l[o];}),Object.getOwnPropertySymbols(l).forEach(o=>{delete l[o];}),n.query?.noMetadata===!0&&Object.keys(l).forEach(o=>{o.startsWith("$")&&delete l[o];});}})))(d);t.bqlRes=B;};var Br={query:[de,le,ue,fe,me,Fe]},Ee=async(e,t,n={},p=!0)=>{for(let a of e){let d=await a(t,n);if(d&&Array.isArray(d))for(let s of d)await Ee(s.pipeline,s.req,s.res,!1);}return p&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Tt=(e,t,n,p)=>Ee(Br.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:p},{});var ct=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var we=(e,t,n)=>{let p=isArray(e[t])?e[t]:[e[t]];if(!p.every(a=>typeof a=="object"))if(p.every(a=>typeof a=="string")){let a=ct(t,n),[d]=a,s=e.$op==="create"?"link":"replace",B=d.thing,L=d.thingType;if(p.some(u=>u.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:s,$thing:B,$thingType:L,$bzId:`S_${v4()}`};}else throw new Error("[Mutation Error] Replace can only be used with a single id or an array of ids")};var gt=(e,t,n)=>{let p=O(n,t),{usedDataFields:a}=U(p,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&a.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&a.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Mt=(e,t,n)=>{let p=O(n,t),{usedFields:a}=U(p,t);return t.$op?(gt(e,t,n),t.$op):t.$id||t.$filter?a.length>0?(gt(e,{...t,$op:"update"},n),"update"):(gt(e,{...t,$op:"link"},n),"link"):(gt(e,{...t,$op:"create"},n),"create")};var Te=(e,t)=>{let p=(isArray(e.$root)?e.$root:[e.$root]).map(a=>{let d=Mt(a,a,t);return {...{...a.$thing?{}:{$thing:a.$entity||a.$relation},...a.$thingType?{}:{$thingType:oe(a,t)},...a.$op?{}:{$op:d},...a.$bzId?{}:{$bzId:`R_${v4()}`}},...a}});e.$root=isArray(e.$root)?p:p[0];};var kt=(e,t)=>{let n=t[bt];return isSet(n)?n.has("clean")?(Reflect.set(t,bt,n.add("clean")),!0):!1:(Reflect.set(t,bt,new Set(["clean"])),!0)};var Me=(e,t,n)=>{if(kt("split_ids",e)){let p=(isArray(e[t])?e[t]:[e[t]]).flatMap(a=>{if(isObject(a)&&"$id"in a&&isArray(a.$id)){let d=a;if(O(n,d),!d.$bzId)throw new Error("[Internal Error] No bzId found");return d.$id.map((s,B)=>({...K(d),$id:s,$bzId:`${d.$bzId}_${B}`,...J(d)}))}return a});(p.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=p);}};var Le=(e,t,n,p)=>{let a=(isArray(e[t])?e[t]:[e[t]]).map(d=>{let s=ct(t,n),[B]=s,L=Mt(e,{...d,$thing:B.thing,$thingType:B.thingType},p),u=d.$bzId?d.$bzId:d.$tempId?d.$tempId:`N_${v4()}`;return {...d,[tt]:n,$thing:B.thing,$thingType:B.thingType,$op:L,$bzId:u}});e[t]=isArray(e[t])?a:a[0];};var Qe=(e,t,n)=>{let p=e[t];p&&(isArray(p)?p:[p]).forEach(a=>{let d=O(n,a),{unidentifiedFields:s}=U(d,a),{computedFields:B,virtualFields:L}=d,u=listify(a,(o,f)=>f!==void 0?o:void 0),r=u.filter(o=>L?.includes(o));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(B.filter(o=>!u.includes(o)).forEach(o=>{let f=d.dataFields?.find(E=>E.path===o),i=d.linkFields?.find(E=>E.path===o)?.oppositeLinkFieldsPlayedBy[0],h="roles"in d?ne(d.roles,(E,$)=>E===o):void 0,m=f||i||h;if(!m)throw new Error(`no field Def for ${o}`);if(a.$op==="create"&&!a[o]){let E=lt({currentThing:a,fieldSchema:m,mandatoryDependencies:!0});a[o]=E;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(a)}`)});};var Ie=(e,t,n)=>{let p=ct(t,n),[a]=p;e[t]={$thing:a.thing,$thingType:a.thingType,$op:"unlink",$bzId:`U_${v4()}`,[tt]:n};};var Lt=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let p=`on${se(e.$op)}`;return n.pre.filter(s=>s.triggers[p]?.()).flatMap(s=>s.actions)}return []};var Re=(e,t,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(a=>{if("$thing"in a){let{requiredFields:d,enumFields:s,fnValidatedFields:B,dataFields:L}=O(n,a);if("$op"in a&&a.$op==="create"&&d.forEach(u=>{if(!(u in a))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in a&&a.$op==="update"||a.$op==="create")&&s.forEach(u=>{if(u in a){let r=L?.find(l=>l.path===u)?.validations?.enum;if(!r)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(a[u]))a[u].some(l=>{if(!r.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(r&&!r.includes(a[u]))throw new Error(`[Validations] Option "${a[u]}" is not a valid option for field "${u}".`)}}),("$op"in a&&a.$op==="update"||a.$op==="create")&&B.forEach(u=>{if(u in a)try{let r=L?.find(l=>l.path===u)?.validations?.fn;if(!r)throw new Error("Missing validation function.");if(!r(a[u]))throw new Error("Failed validation function.")}catch(r){throw new Error(`[Validations:attribute:${u}] ${r.message}`)}}),isObject(a)&&"$thing"in a){let u=a.$thing,r=a,l=clone(K(e)),o=clone(K(r));Lt(r,n).forEach(c=>{if(c.type==="validate"){if(c.severity!=="error")return;try{let i=c.fn(o,l);if(i===!1)throw new Error(`${c.message}.`);if(i!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(i){throw new Error(`[Validations:thing:${u}] ${i.message}`)}}});}}});};var Oe=(e,t,n)=>{let p=(isArray(e[t])?e[t]:[e[t]]).map(a=>{if(wt(a)){let d=Lt(a,n).filter(L=>L.type==="transform"),s=clone(K(e)),B=clone(K(a));return d.forEach(L=>{let u=L.fn(B,s);Object.keys(u).length!==0&&(a={...B,...u});}),a}});e[t]=isArray(e[t])?p:p[0];};var Or=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(kt("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},qr=(e,t)=>{},Ht=(e,t)=>{let p=produce({$rootWrap:{$root:e}},a=>traverse(a,({value:d,parent:s,key:B,meta:L})=>{if(!(!s||!B)&&isObject(d)){if(!("$root"in d)){if(!("$thing"in d||"$entity"in d||"$relation"in d))throw B==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(d)?current(d):d)}`)}let u=d;Object.keys(u).forEach(r=>{if(Or(u,r),r!=="$root"&&r.startsWith("$"))return;let l=r!=="$root"?xt(t,u,r):{fieldType:"rootField"};if(!l)throw new Error(`[Internal] Field ${r} not found in schema`);if("contentType"in l)return qr();if(["rootField","linkField","roleField"].includes(l.fieldType)){if(["linkField","roleField"].includes(l.fieldType)&&we(u,r,l),l.fieldType==="rootField"){if(!("$root"in u))throw new Error(`[Internal] Field ${r} is a rootField but the object is not a root`);Te(u,t);}let o=isArray(u[r])?u[r]:[u[r]],f=L.nodePath?.split(".").slice(1).join(".");o.forEach(i=>{if(i){if(l?.cardinality==="ONE"&&!i.$op&&!i.$id&&!i.$filter&&!i.$tempId&&u.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${f}.${r}`);if(i.$tempId&&!(i.$op===void 0||i.$op==="link"||i.$op==="create"||i.$op==="update"))throw new Error(`Invalid op ${i.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes(l.fieldType)&&(u[r]===null?Ie(u,r,l):Le(u,r,l,t)),Me(u,r,t),["rootField","linkField","roleField"].includes(l.fieldType)&&Qe(u,r,t),(isArray(u[r])?u[r]:[u[r]]).forEach(i=>{let h=O(t,i),{unidentifiedFields:m,usedLinkFields:E}=U(h,i);if(m.length>0)throw new Error(`Unknown fields: [${m.join(",")}] in ${JSON.stringify(d)}`);if(E.length>1){let $=h.linkFields?.filter(M=>E.includes(M.path));$?.some((M,P)=>$.some((R,g)=>{if(P!==g&&M.target!==R.target&&M.relation===R.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),Oe(u,r,t),Re(u,r,t);}});}}));return isArray(p.$rootWrap.$root),p.$rootWrap.$root};var qe=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:p}=await yt(t,n),a=await p.transaction(TransactionType.WRITE);if(!a)throw new Error("Can't create transaction");let d=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;d&&await a.query.delete(d);let B=s&&a.query.insert(s);try{let L=B?await B.collect():void 0;return await a.commit(),await a.close(),{insertions:L}}catch(L){throw await a.close(),new Error(`Transaction failed: ${L.message}`)}};var De=async(e,t,n,p)=>{let a=[...t,...n],d=a.map(s=>{let B=e.insertions?.find(L=>L.get(`${s.$bzId}`))?.get(`${s.$bzId}`);if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!B&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let L=B?.asThing().iid;if(p.mutation?.noMetadata)return Object.entries(s).filter(([l,o])=>!l.startsWith("$")).reduce((l,[o,f])=>{if(s.$thingType==="relation"){let c=a.filter(i=>i.$id&&i.$bzId===f);if(c.length>1)throw new Error(`Multiple things with the same bzId ${f}`);return c.length===1?(l[o]=c[0].$id,l):(l[o]=f,l)}return l[o]=f,l},{});let u=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:L,...s,[s.path]:s.$id,...u}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(d)};var xe=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(d=>d.startsWith("$")).forEach(d=>delete n[d]),Object.keys(n).filter(d=>typeof d=="symbol").forEach(d=>delete n[d])),n);return produce(e,n=>traverse(n,t))};var ve=async(e,t)=>{let n=u=>{let r=[],l=[],o=h=>{if(h.$id)return h.$id;let m=O(t,h),{idFields:E}=m;if(!E)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[$]=E;if(!$)throw new Error(`no idField: ${JSON.stringify(h)}`);let M=m.dataFields?.find(g=>g.path===$),P=lt({currentThing:h,fieldSchema:M,mandatoryDependencies:!0}),R=h[$]||h.$id||P;if(!R)throw new Error(`no idValue: ${JSON.stringify(h)}`);return R},f=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(h)}`);if(l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);r.push({...h,$id:m});return}h.$tempId&&h.$op==="match"||r.push(h);},c=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m),l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);l.push({...h,$id:m});return}l.push(h);};return traverse(u,({value:h,parent:m,meta:E})=>{if(!isObject(h))return;let $=h;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let M=O(t,$),{dataFields:P,roleFields:R,linkFields:g,usedFields:b}=U(M,$),k=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let T=b.filter(w=>P?.includes(w)),A=b.filter(w=>R?.includes(w)),F=b.filter(w=>g?.includes(w));if(T.length>0)return "update";if(A.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...shake(pick($,P||[""])),$op:k(),$bzId:$.$tempId?$.$tempId:$.$bzId};f(y);let I=$[tt];if(I?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let T=I.relation===$.$thing,A=T?$.$bzId:`LT_${v4()}`,w=ae(u,m,E).$bzId;if(!w)throw new Error("No parent id found");if($[Symbol.for("relation")]==="$self")return;let Q=()=>{if($.$op==="delete")return T?"match":"delete";if($.$op==="unlink")return T?"unlink":"delete";if($.$op==="link"||$.$op==="create")return T?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},C={$bzId:A,$thing:I.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:Q(),...T?{}:{[I.path]:$.$bzId},[I.plays]:w,[tt]:I,[ot]:"linkField"};c(C),($.$op==="unlink"||Q()==="unlink")&&T&&c({$thing:I.relation,$thingType:"relation",$bzId:A,$op:"match",[I.plays]:w,[tt]:I,[ot]:"linkField"});}if($.$thingType==="relation"){let T=mt($,(w,Q)=>R.includes(w)),A=mapEntries(T,(w,Q)=>isArray(Q)?[w,Q]:isObject(Q)?[w,Q.$bzId]:[w,Q]),F=mt(h,(w,Q)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(T).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},Q=O(t,$).roles,C=mapEntries(A,(N,D)=>{let z=Q[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(V=>V.$bzId||V)]}return [N,D.$bzId||D]}),S={...F,$thing:$.$thing,$thingType:"relation",$op:w(),...C,$bzId:$.$bzId,[ot]:"roleField"};c(S);return}if($.$op==="match"||$.$op==="update"&&Object.keys(T).length>0){let w=0;Object.entries(T).forEach(([Q,C])=>{let S=isArray(C)?C:[C],N=D=>D==="create"||D==="replace"?"link":D;S.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let V={...F,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[Q]:D.$bzId,$bzId:$.$bzId,[ot]:"roleField"};c(V);});});}}}}}),[r,l]},[p,a]=n(e),d=p.reduce((u,r)=>{if(!r.$bzId)return [...u,r];let l=u.findIndex(o=>o.$bzId===r.$bzId);if(l===-1)return [...u,r];if(u[l].$op==="create"&&r.$op==="match")return u;if(u[l].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...u.slice(0,l),r,...u.slice(l+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${u[l].$op}. Current: ${r.$op}`)},[]),s=a.reduce((u,r)=>{let l=u.find(o=>(o.$id&&o.$id===r.$id||o.$bzId&&o.$bzId===r.$bzId)&&o.$thing===r.$thing&&o.$op===r.$op);if(l){let o={...l};return Object.keys(r).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let i=l[c],h=r[c];Array.isArray(i)&&Array.isArray(h)?o[c]=Array.from(new Set([...i,...h])):!Array.isArray(i)&&Array.isArray(h)?i!==void 0?o[c]=Array.from(new Set([i,...h])):o[c]=h:Array.isArray(i)&&!Array.isArray(h)?h!==void 0&&(o[c]=Array.from(new Set([...i,h]))):i!==null&&h!==null&&i!==void 0&&h!==void 0?o[c]=Array.from(new Set([i,h])):i==null&&(o[c]=h);}),[...u.filter(c=>!((c.$id&&c.$id===r.$id||c.$bzId&&c.$bzId===r.$bzId)&&c.$thing===r.$thing&&c.$op===r.$op)),o]}return [...u,r]},[]);d.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&s.filter(r=>r.$bzId===u.$bzId||r.$tempId&&r.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(xe(u))}`)}});let B=[...d,...s];return new Set(B.filter(u=>u.$tempId).map(u=>u.$tempId)).forEach(u=>{if(B.filter(r=>r.$tempId===u&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:d,mergedEdges:s}};var We=async(e,t,n)=>{let p=o=>{let f=o.$op,c=`$${o.$bzId}`,i=O(n,o),{idFields:h,defaultDBConnector:m}=i,E=m?.path||o.$thing,$=o.$id,M=h?.[0],P=listify(o,(A,F)=>{if(A.startsWith("$")||A===M||F===void 0||F===null)return "";let w=i.dataFields?.find(S=>S.path===A);if(!w?.path)return "";let C=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${C} '${F}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${C} ${F}`;if(w.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${C} ${F.toISOString().replace("Z","")}`:`has ${C} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(A=>A),R=`${c}-atts`,g=listify(o,A=>{if(A.startsWith("$")||A===M)return "";let F=i.dataFields?.find(C=>C.path===A);if(!F?.path)return "";let Q=F.dbPath;return `{${R} isa ${Q};}`}).filter(A=>A),b=isArray($)?`like '${$.join("|")}'`:`'${$}'`,k=$?[`has ${M} ${b}`]:[],y=[...k,...P].filter(A=>A).join(","),I=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${c} isa ${[E,...k].filter(A=>A).join(",")};`;if(f==="update"){if(!g.length)throw new Error("update without attributes");return `${c} isa ${[E,...k].filter(A=>A).join(",")}, has ${R};
60
- ${g.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${c} isa ${[E,...k].filter(A=>A).join(",")};`:"";if(wt(o))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${c} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${c} ${P.join(",")};`:"",deletion:f==="delete"?`${c} isa ${E};`:f==="update"&&g.length?`${c} has ${R};`:""};throw new Error("in attributes")},a=o=>{let f=o.$op,c=O(n,o),i=`$${o.$bzId}`,h=o.$id,m=c.defaultDBConnector?.path||o.$thing,E="roles"in c?listify(c.roles,F=>F):[],$="roles"in c?mapEntries(c.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},M=listify(o,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in c))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(C=>({path:Q,id:C})):{path:Q,id:w}}).filter(F=>F).flat(),P=M.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),R=M.length>0?`( ${P.join(" , ")} )`:"",g=o[ot];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=R?`${i} ${R} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",k=`${i} ${g==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${k};`:f==="unlink"?`${i} ${R};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},d=(o,f)=>{let c=f==="edges"?a:p;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k}=c(M);return shake({preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k},y=>!y)}).filter(M=>M);let{preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=c(o);return shake({preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},M=>!M)},s=d(e),B=Array.isArray(s)?s:[s],L=d(t,"edges"),u=Array.isArray(L)?L:[L],r=[...B,...u];return shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var Kr=Symbol.for("grandChildOfCreate"),_e=async(e,t,n,p)=>{let a=(g,b)=>Object.keys(g).filter(k=>k.startsWith("$")?!1:b?!O(t,g).dataFields?.find(I=>I.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let d=[];if(traverse(e,({parent:g,key:b,value:k})=>{g&&b&&!b.includes("$")&&isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(I=>{if(isObject(I)){if(g.$op!=="create")d.includes(I.$op)||d.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!g&&isObject(k)&&(d.includes(k.$op)||d.push(k.$op));}),!d.includes("delete")&&!d.includes("unlink")&&!d.includes("replace")&&!d.includes("update")&&!d.includes("link"))return;let B=(g=>{let b=(k,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in k)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(isObject(k[w])||Array.isArray(k[w]))){let Q=k[w];Array.isArray(Q)&&Q.length>0?Q.forEach(C=>{I.push({$path:w,...b(C)});}):I.push({$path:w,...b(Q)});}else T[w]=k[w];return {...T,$fields:I}};return g.map(k=>b(k,!0))})(Array.isArray(e)?e:[e]),L=await Tt(B,n,t,p),u=(g,b)=>{let k=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:k,key:b}}else return {beforePath:"root",ids:k,key:b}},r=(g,b)=>{let k=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${k}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,k,y]=g.split(/[[\]]/);return k.split(",").map(T=>`${b}${T}${y}`)}else return [g]},o={};(g=>produce(g,b=>traverse(b,k=>{let{key:y,parent:I}=k;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),o[A]={$objectPath:T,$ids:F};}else {let F=I[y];isObject(F)?(o[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(o[A]={$objectPath:T,$ids:[F.toString()]});}}})))(L||{});let c=g=>produce(g,b=>traverse(b,k=>{let{key:y,value:I,parent:T}=k;T&&y&&!y.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[Kr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),i=c(e),m=(g=>{let b=(T,A)=>{let F=[];T.filter(S=>S).forEach(S=>{let N=Object.keys(S).filter(D=>!D.startsWith("$")).length;if(Array.isArray(S.$id)&&N>0){let D=S.$id.map(z=>({...S,$id:z}));F=[...F,...D];}else F.push({...S});});let w=[],Q=[],C=F.filter(S=>{let D=["delete","update","unlink"].includes(S.$op||""),z=a(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&z>0||S.$filter)&&D)return !0;Q.push({...S});});return C.length>0?C.forEach(S=>{let D=(j=>{let ut=(()=>{let v={};for(let x in j){let X=O(t,j);!x.startsWith("$")&&X.dataFields?.find(at=>at.path===x)&&(v[x]=j[x]);}return v})(),ht=Object.keys(j),G=ht.filter(v=>!v.startsWith("$")),At=[],Ft=(v,x)=>{if(v===G.length){let at={...x};ht.forEach(W=>{W.startsWith("$")&&(at[W]=j[W]);}),At.push(at);return}let X={...x,[G[v]]:j[G[v]],...J(x),...ut};Ft(v+1,X),Ft(v+1,x);};return Ft(0,{...J(j)}),At})(S).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(nt=>!nt.startsWith("$")).length===0)),z=[],V=r(S.$objectPath),Y=o[V]?o[V].$ids:[],q=D.map((j,nt)=>{let ut=O(t,j),G=Object.keys(j).filter(x=>!x.includes("$")&&!ut.dataFields?.some(X=>X.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(W=>!W.$id||Array.isArray(W.$id)||W.$filter):j[x]:[j[x]]).map(W=>{let Rt=r(W.$objectPath);return {idsToKey:(Ct=>{let Yt=[],$t=Ct.split("."),Ze=$t.slice(0,$t.length-1).join("."),Ye=$t.slice($t.length-1,$t.length)[0].split("___")[1];for(let St in o)if(St.startsWith(Ze)&&St.endsWith(Ye)){let Ot=St.split("."),Ge=Ot.slice(Ot.length-1,Ot.length)[0].split("___")[0];Yt.push(Ge);}return Yt})(Rt),key:x,multiple:W}})).filter(x=>x!==void 0),v=(x=>{let X=x.map(W=>W.map(it=>it.idsToKey));return (W=>W.length>0?W.reduce((it,ft)=>it.concat(ft),[]).reduce((it,ft)=>it?ft.filter(Ct=>it.includes(Ct)):ft):[])(X)})(G).filter(x=>!z.includes(x));if(z=[...z,...v],Y=Y.filter(x=>!v.includes(x)),nt===D.length-1&&Y.length>0)return {...j,$id:Y,$bzId:`T1_${v4()}`,...J(j)};if(v.length>0)return {...j,$id:v,$bzId:`T2_${v4()}`,...J(j)}}).filter(j=>j!==void 0),Je=(()=>{if(q.length===0&&!A?.$id)return C;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],nt=[];return j.forEach(ut=>{let ht=r({...S.$objectPath,ids:ut}),G=o[ht];G&&nt.push({...S,$id:G.$ids,...J(S),$bzId:`T_${v4()}`});}),nt}else return q.filter(j=>j!==void 0)})();w=[...Q,...Je].map(k);}):w=F.map(k),w},k=T=>{let A={...T,$bzId:T.$tempId??`T3_${v4()}`,...J(T)},F=O(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],C=b(Q,T);A[w]=C.length>0?C:void 0;}),A},y=[];return g.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>k(T))})(Array.isArray(i)?i:[i]),E=g=>g.map(b=>{let k=a(b,!0),y={...b};return k.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},C=jt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&C==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let S=r(Q.$objectPath),D=l(S).map(q=>o[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let V=z.filter(q=>!F.includes(q)),Pt=F.filter(q=>!z.includes(q)),Y=J(Q);V.length>0&&A.push({...Q,$op:"unlink",$id:V,$bzId:`T4_${v4()}`,id:void 0,...Y}),Pt.length>0&&Pt.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${v4()}`,...Y});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${v4()}`,...Y});}),y[I]=E(A);}),y}),$=c(E(c(m)));return (g=>produce(g,b=>traverse(b,k=>{let{key:y,value:I,parent:T}=k;y&&T&&!y?.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=o[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),C=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,S=jt(t,T,F.$objectPath.key);if(F.$op==="link"&&C&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(C)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(g=>produce(g,b=>traverse(b,k=>{let{value:y,meta:I}=k;isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};var{createMachine:Jr,interpret:Zr,transition:et,reduce:rt,state:Yr,invoke:dt,guard:Gr}=Ur,Ve=Yr,Ut=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Xr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),tn=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),en=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),rn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),nn=async e=>Object.keys(e.bql.current).length?Ht(e.bql.current,e.schema):Ht(e.bql.raw,e.schema),on=async e=>_e(e.bql.current,e.schema,e.config,e.handles),sn=async e=>ve(e.bql.current,e.schema),an=async e=>We(e.bql.things,e.bql.edges,e.schema),ln=async e=>qe(e.typeDB.tqlMutation,e.handles,e.config),cn=async e=>De(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),dn=()=>!0,pt=et("error","error",rt((e,t)=>({...e,error:t.error}))),pn=Jr("enrich",{enrich:dt(nn,et("done","preQuery",Gr(dn),rt(Ut)),et("done","parseBQL",rt(Ut)),pt),preQuery:dt(on,et("done","parseBQL",rt(Ut)),pt),parseBQL:dt(sn,et("done","buildMutation",rt(tn)),pt),buildMutation:dt(an,et("done","runMutation",rt(en)),pt),runMutation:dt(ln,et("done","parseMutation",rt(rn)),pt),parseMutation:dt(cn,et("done","success",rt(Xr)),pt),success:Ve(),error:Ve()},e=>e),un=async e=>new Promise((t,n)=>{Zr(pn,p=>{p.machine.state.name==="success"&&t(p.context),p.machine.state.name==="error"&&n(p.context);},e);}),He=async(e,t,n,p)=>un({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:p,depthLevel:0,error:null});enableMapSet();var Zt=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async p=>{if(p.provider==="typeDB"&&p.dbName){let[a,d]=await tryit(TypeDB.coreDriver)(p.url);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(p.provider==="typeDBCluster"&&p.dbName){let[a,d]=await tryit(TypeDB.cloudDriver)(p.addresses,p.credentials);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=ie(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),Xt(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let p={...this.config,query:{...qt.query,...this.config.query,...n}};return Tt(t,p,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let p={...this.config,mutation:{...qt.mutation,...this.config.mutation,...n}},[a,d]=await tryit(He)(t,this.schema,p,this.dbHandles);if(a)throw console.error(a.error.stack.split(`
60
+ ${g.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${c} isa ${[E,...k].filter(A=>A).join(",")};`:"";if(wt(o))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${c} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${c} ${P.join(",")};`:"",deletion:f==="delete"?`${c} isa ${E};`:f==="update"&&g.length?`${c} has ${R};`:""};throw new Error("in attributes")},a=o=>{let f=o.$op,c=O(n,o),i=`$${o.$bzId}`,h=o.$id,m=c.defaultDBConnector?.path||o.$thing,E="roles"in c?listify(c.roles,F=>F):[],$="roles"in c?mapEntries(c.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},M=listify(o,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in c))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(C=>({path:Q,id:C})):{path:Q,id:w}}).filter(F=>F).flat(),P=M.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),R=M.length>0?`( ${P.join(" , ")} )`:"",g=o[ot];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=R?`${i} ${R} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",k=`${i} ${g==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${k};`:f==="unlink"?`${i} ${R};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},d=(o,f)=>{let c=f==="edges"?a:p;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k}=c(M);return shake({preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k},y=>!y)}).filter(M=>M);let{preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=c(o);return shake({preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},M=>!M)},s=d(e),B=Array.isArray(s)?s:[s],L=d(t,"edges"),u=Array.isArray(L)?L:[L],r=[...B,...u];return shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var Kr=Symbol.for("grandChildOfCreate"),_e=async(e,t,n,p)=>{let a=(g,b)=>Object.keys(g).filter(k=>k.startsWith("$")?!1:b?!O(t,g).dataFields?.find(I=>I.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let d=[];if(traverse(e,({parent:g,key:b,value:k})=>{g&&b&&!b.includes("$")&&isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(I=>{if(isObject(I)){if(g.$op!=="create")d.includes(I.$op)||d.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!g&&isObject(k)&&(d.includes(k.$op)||d.push(k.$op));}),!d.includes("delete")&&!d.includes("unlink")&&!d.includes("replace")&&!d.includes("update")&&!d.includes("link"))return;let B=(g=>{let b=(k,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in k)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(isObject(k[w])||Array.isArray(k[w]))){let Q=k[w];Array.isArray(Q)&&Q.length>0?Q.forEach(C=>{I.push({$path:w,...b(C)});}):I.push({$path:w,...b(Q)});}else T[w]=k[w];return {...T,$fields:I}};return g.map(k=>b(k,!0))})(Array.isArray(e)?e:[e]),L=await Tt(B,n,t,p),u=(g,b)=>{let k=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:k,key:b}}else return {beforePath:"root",ids:k,key:b}},r=(g,b)=>{let k=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${k}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,k,y]=g.split(/[[\]]/);return k.split(",").map(T=>`${b}${T}${y}`)}else return [g]},o={};(g=>produce(g,b=>traverse(b,k=>{let{key:y,parent:I}=k;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),o[A]={$objectPath:T,$ids:F};}else {let F=I[y];isObject(F)?(o[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(o[A]={$objectPath:T,$ids:[F.toString()]});}}})))(L||{});let c=g=>produce(g,b=>traverse(b,k=>{let{key:y,value:I,parent:T}=k;T&&y&&!y.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[Kr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),i=c(e),m=(g=>{let b=(T,A)=>{let F=[];T.filter(S=>S).forEach(S=>{let N=Object.keys(S).filter(D=>!D.startsWith("$")).length;if(Array.isArray(S.$id)&&N>0){let D=S.$id.map(z=>({...S,$id:z}));F=[...F,...D];}else F.push({...S});});let w=[],Q=[],C=F.filter(S=>{let D=["delete","update","unlink"].includes(S.$op||""),z=a(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&z>0||S.$filter)&&D)return !0;Q.push({...S});});return C.length>0?C.forEach(S=>{let D=(j=>{let ut=(()=>{let v={};for(let x in j){let X=O(t,j);!x.startsWith("$")&&X.dataFields?.find(at=>at.path===x)&&(v[x]=j[x]);}return v})(),ht=Object.keys(j),G=ht.filter(v=>!v.startsWith("$")),At=[],Ft=(v,x)=>{if(v===G.length){let at={...x};ht.forEach(W=>{W.startsWith("$")&&(at[W]=j[W]);}),At.push(at);return}let X={...x,[G[v]]:j[G[v]],...J(x),...ut};Ft(v+1,X),Ft(v+1,x);};return Ft(0,{...J(j)}),At})(S).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(nt=>!nt.startsWith("$")).length===0)),z=[],V=r(S.$objectPath),Y=o[V]?o[V].$ids:[],q=D.map((j,nt)=>{let ut=O(t,j),G=Object.keys(j).filter(x=>!x.includes("$")&&!ut.dataFields?.some(X=>X.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(W=>!W.$id||Array.isArray(W.$id)||W.$filter):j[x]:[j[x]]).map(W=>{let Rt=r(W.$objectPath);return {idsToKey:(Ct=>{let Yt=[],$t=Ct.split("."),Ze=$t.slice(0,$t.length-1).join("."),Ye=$t.slice($t.length-1,$t.length)[0].split("___")[1];for(let St in o)if(St.startsWith(Ze)&&St.endsWith(Ye)){let Ot=St.split("."),Ge=Ot.slice(Ot.length-1,Ot.length)[0].split("___")[0];Yt.push(Ge);}return Yt})(Rt),key:x,multiple:W}})).filter(x=>x!==void 0),v=(x=>{let X=x.map(W=>W.map(it=>it.idsToKey));return (W=>W.length>0?W.reduce((it,ft)=>it.concat(ft),[]).reduce((it,ft)=>it?ft.filter(Ct=>it.includes(Ct)):ft):[])(X)})(G).filter(x=>!z.includes(x));if(z=[...z,...v],Y=Y.filter(x=>!v.includes(x)),nt===D.length-1&&Y.length>0)return {...j,$id:Y,$bzId:`T1_${v4()}`,...J(j)};if(v.length>0)return {...j,$id:v,$bzId:`T2_${v4()}`,...J(j)}}).filter(j=>j!==void 0),Je=(()=>{if(q.length===0&&!A?.$id)return C;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],nt=[];return j.forEach(ut=>{let ht=r({...S.$objectPath,ids:ut}),G=o[ht];G&&nt.push({...S,$id:G.$ids,...J(S),$bzId:`T_${v4()}`});}),nt}else return q.filter(j=>j!==void 0)})();w=[...Q,...Je].map(k);}):w=F.map(k),w},k=T=>{let A={...T,$bzId:T.$tempId??`T3_${v4()}`,...J(T)},F=O(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],C=b(Q,T);A[w]=C.length>0?C:void 0;}),A},y=[];return g.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>k(T))})(Array.isArray(i)?i:[i]),E=g=>g.map(b=>{let k=a(b,!0),y={...b};return k.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},C=jt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&C==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let S=r(Q.$objectPath),D=l(S).map(q=>o[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let V=z.filter(q=>!F.includes(q)),Pt=F.filter(q=>!z.includes(q)),Y=J(Q);V.length>0&&A.push({...Q,$op:"unlink",$id:V,$bzId:`T4_${v4()}`,id:void 0,...Y}),Pt.length>0&&Pt.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${v4()}`,...Y});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${v4()}`,...Y});}),y[I]=E(A);}),y}),$=c(E(c(m)));return (g=>produce(g,b=>traverse(b,k=>{let{key:y,value:I,parent:T}=k;y&&T&&!y?.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=o[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),C=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,S=jt(t,T,F.$objectPath.key);if(F.$op==="link"&&C&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(C)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(g=>produce(g,b=>traverse(b,k=>{let{value:y,meta:I}=k;isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};var Ut=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Yr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Gr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Xr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),tn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),en=async e=>Object.keys(e.bql.current).length?Ht(e.bql.current,e.schema):Ht(e.bql.raw,e.schema),rn=async e=>_e(e.bql.current,e.schema,e.config,e.handles),nn=async e=>ve(e.bql.current,e.schema),on=async e=>We(e.bql.things,e.bql.edges,e.schema),sn=async e=>qe(e.typeDB.tqlMutation,e.handles,e.config),an=async e=>De(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),ln=()=>!0,pt=transition("error","error",reduce((e,t)=>({...e,error:t.error}))),cn=createMachine("enrich",{enrich:invoke(en,transition("done","preQuery",guard(ln),reduce(Ut)),transition("done","parseBQL",reduce(Ut)),pt),preQuery:invoke(rn,transition("done","parseBQL",reduce(Ut)),pt),parseBQL:invoke(nn,transition("done","buildMutation",reduce(Gr)),pt),buildMutation:invoke(on,transition("done","runMutation",reduce(Xr)),pt),runMutation:invoke(sn,transition("done","parseMutation",reduce(tn)),pt),parseMutation:invoke(an,transition("done","success",reduce(Yr)),pt),success:state(),error:state()},e=>e),dn=async e=>new Promise((t,n)=>{interpret(cn,p=>{p.machine.state.name==="success"&&t(p.context),p.machine.state.name==="error"&&n(p.context);},e);}),He=async(e,t,n,p)=>dn({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:p,depthLevel:0,error:null});enableMapSet();var Zt=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async p=>{if(p.provider==="typeDB"&&p.dbName){let[a,d]=await tryit(TypeDB.coreDriver)(p.url);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(p.provider==="typeDBCluster"&&p.dbName){let[a,d]=await tryit(TypeDB.cloudDriver)(p.addresses,p.credentials);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=ie(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),Xt(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let p={...this.config,query:{...qt.query,...this.config.query,...n}};return Tt(t,p,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let p={...this.config,mutation:{...qt.mutation,...this.config.mutation,...n}},[a,d]=await tryit(He)(t,this.schema,p,this.dbHandles);if(a)throw console.error(a.error.stack.split(`
61
61
  `).slice(0,4).join(`
62
- `)),new Error(a.error.message);return d.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Bs=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
62
+ `)),new Error(a.error.message);return d.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},ys=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
63
63
  //! Todo: Sandbox the function in computeFunction()
64
64
  //! reads all the insertions and gets the first match. This means each id must be unique
65
65
  //!old
66
66
 
67
- export { Bs as default };
67
+ export { ys as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blitznocode/blitz-orm",
3
- "version": "0.9.3",
3
+ "version": "0.9.4",
4
4
  "main": "dist/index.cjs",
5
5
  "module": "./dist/index.mjs",
6
6
  "types": "dist/index.d.ts",