@blitznocode/blitz-orm 0.10.0 → 0.10.5

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { isObject, isArray, parallel, clone, shake, tryit, listify, pick, mapEntries, pascal, dash } from 'radash';
1
+ import { isObject, isArray, parallel, clone, shake, tryit, listify, pick, mapEntries } from 'radash';
2
2
  import { TypeDBOptions, TransactionType, SessionType, TypeDB } from 'typedb-driver';
3
3
  import { Surreal } from 'surrealdb.node';
4
4
  import { enableMapSet, produce, isDraft, current } from 'immer';
@@ -6,76 +6,47 @@ import { traverse, getNodeByPath } from 'object-traversal';
6
6
  import { v4 } from 'uuid';
7
7
  import { isSet } from 'util/types';
8
8
  import 'acorn';
9
- import { trainCase } from 'case-anything';
10
9
 
11
- var Ye={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var wn=t=>{let e=[],r=new Map;return t.forEach(n=>{let{dbPath:o,contentType:i}=n,p=`${o}-${i}`;r.has(p)||(r.set(p,!0),e.push(n));}),e},At=async(t,e,r)=>{let o=(()=>{let m="",y=[];m+=`
12
- `,Object.keys(e.entities).forEach(g=>{let Q=e.entities[g],{idFields:M,dataFields:L,linkFields:A,name:R}=Q,D=[],N=[],x=[];if("extends"in Q){let F=e.entities[Q.extends];F.dataFields&&F.dataFields.forEach(k=>{D.push(k.dbPath);}),F.linkFields&&F.linkFields.forEach(k=>{N.push(k.path);}),F.idFields&&F.idFields.forEach(k=>{x.push(k);});}m+=`${R} sub ${"extends"in Q?Q.extends:"entity"},
13
- `;let w=[];if(M&&M.length>0){let F=new Set(M),E=Array.from(F).map(b=>`${b}`).join(", ");x.includes(E)||(m+=` owns ${E} @key,
14
- `,w.push(E));}if(L&&L.length>0&&L.forEach(F=>{!D.includes(F.dbPath)&&!w.includes(F.dbPath)&&(m+=` owns ${F.dbPath},
15
- `),y.push({dbPath:F.dbPath,contentType:F.contentType});}),A&&A.length>0){let F=[];A.forEach(k=>{let{relation:E,plays:b}=k;!N.includes(k.path)&&!F.includes(`${E}:${b}`)&&(m+=` plays ${E}:${b},
16
- `,F.push(`${E}:${b}`));});}m=m.replace(/,\s*$/,`;
17
- `),m+=`
18
- `;}),Object.keys(e.relations).forEach(g=>{let Q=e.relations[g],{idFields:M,dataFields:L,roles:A,name:R,linkFields:D}=Q,N=[],x=[],w=[],F=[];if("extends"in Q){let E=e.relations[Q.extends];E.dataFields&&E.dataFields.forEach(b=>{N.push(b.dbPath);}),E.linkFields&&E.linkFields.forEach(b=>{x.push(b.dbPath);}),E.roles&&Object.values(E.roles).forEach(S=>{w.push(S.name);}),E.idFields&&E.idFields.forEach(b=>{F.push(b);});}m+=`${R} sub ${"extends"in Q?Q.extends:"relation"},
19
- `;let k=[];if(M&&M.length>0){let E=new Set(M),S=Array.from(E).map(_=>`${_}`).join(", ");F.includes(S)||(m+=` owns ${S} @key,
20
- `,k.push(S));}if(L&&L.length>0&&L.forEach(E=>{!N.includes(E.dbPath)&&!k.includes(E.dbPath)&&(m+=` owns ${E.dbPath},
21
- `),y.push({dbPath:E.dbPath,contentType:E.contentType});}),A&&Object.keys(A).forEach(E=>{w.includes(E)||(m+=` relates ${E},
22
- `);}),D&&D.length>0){let E=[];D.forEach(b=>{let{plays:S}=b;!x.includes(b.path)&&!E.includes(`${Q}:${S}`)&&(m+=` plays ${b.relation}:${S},
23
- `,E.push(`${Q}:${S}`));});}m=m.replace(/,\s*$/,`;
24
- `),m+=`
25
- `;});let B=`define
10
+ var Je={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var ln=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,l=`${o}-${n}`;r.has(l)||(r.set(l,!0),t.push(i));}),t},Rt=async(e,t,r)=>{let o=(()=>{let g="",y=[];g+=`
11
+ `,Object.keys(t.entities).forEach(m=>{let D=t.entities[m],{idFields:R,dataFields:A,linkFields:x,name:j}=D,N=[],se=[],K=[];if("extends"in D){let B=t.entities[D.extends];B.dataFields&&B.dataFields.forEach(Q=>{N.push(Q.dbPath);}),B.linkFields&&B.linkFields.forEach(Q=>{se.push(Q.path);}),B.idFields&&B.idFields.forEach(Q=>{K.push(Q);});}g+=`${j} sub ${"extends"in D?D.extends:"entity"},
12
+ `;let S=[];if(R&&R.length>0){let B=new Set(R),F=Array.from(B).map(E=>`${E}`).join(", ");K.includes(F)||(g+=` owns ${F} @key,
13
+ `,S.push(F));}if(A&&A.length>0&&A.forEach(B=>{!N.includes(B.dbPath)&&!S.includes(B.dbPath)&&(g+=` owns ${B.dbPath},
14
+ `),y.push({dbPath:B.dbPath,contentType:B.contentType});}),x&&x.length>0){let B=[];x.forEach(Q=>{let{relation:F,plays:E}=Q;!se.includes(Q.path)&&!B.includes(`${F}:${E}`)&&(g+=` plays ${F}:${E},
15
+ `,B.push(`${F}:${E}`));});}g=g.replace(/,\s*$/,`;
16
+ `),g+=`
17
+ `;}),Object.keys(t.relations).forEach(m=>{let D=t.relations[m],{idFields:R,dataFields:A,roles:x,name:j,linkFields:N}=D,se=[],K=[],S=[],B=[];if("extends"in D){let F=t.relations[D.extends];F.dataFields&&F.dataFields.forEach(E=>{se.push(E.dbPath);}),F.linkFields&&F.linkFields.forEach(E=>{K.push(E.dbPath);}),F.roles&&Object.values(F.roles).forEach(M=>{S.push(M.name);}),F.idFields&&F.idFields.forEach(E=>{B.push(E);});}g+=`${j} sub ${"extends"in D?D.extends:"relation"},
18
+ `;let Q=[];if(R&&R.length>0){let F=new Set(R),M=Array.from(F).map(L=>`${L}`).join(", ");B.includes(M)||(g+=` owns ${M} @key,
19
+ `,Q.push(M));}if(A&&A.length>0&&A.forEach(F=>{!se.includes(F.dbPath)&&!Q.includes(F.dbPath)&&(g+=` owns ${F.dbPath},
20
+ `),y.push({dbPath:F.dbPath,contentType:F.contentType});}),x&&Object.keys(x).forEach(F=>{S.includes(F)||(g+=` relates ${F},
21
+ `);}),N&&N.length>0){let F=[];N.forEach(E=>{let{plays:M}=E;!K.includes(E.path)&&!F.includes(`${D}:${M}`)&&(g+=` plays ${E.relation}:${M},
22
+ `,F.push(`${D}:${M}`));});}g=g.replace(/,\s*$/,`;
23
+ `),g+=`
24
+ `;});let w=`define
26
25
 
27
- `;return wn(y).forEach(g=>{B+=`${g.dbPath} sub attribute,
28
- `,g.contentType==="TEXT"||g.contentType==="ID"?B+=` value string;
29
- `:g.contentType==="EMAIL"?(B+=` value string,
30
- `,B+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
31
- `):g.contentType==="DATE"?B+=` value datetime;
32
- `:g.contentType==="BOOLEAN"?B+=` value boolean;
33
- `:g.contentType==="NUMBER"&&(B+=` value long;
34
- `);}),`${B}
26
+ `;return ln(y).forEach(m=>{if(w+=`${m.dbPath} sub attribute,
27
+ `,m.contentType==="TEXT"||m.contentType==="ID"||m.contentType==="JSON")w+=` value string;
28
+ `;else if(m.contentType==="EMAIL")w+=` value string,
29
+ `,w+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
30
+ `;else if(m.contentType==="DATE")w+=` value datetime;
31
+ `;else if(m.contentType==="BOOLEAN")w+=` value boolean;
32
+ `;else if(m.contentType==="NUMBER")w+=` value long;
33
+ `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${m.contentType}" is not implemented`)}),`${w}
35
34
 
36
- ${m}`})(),i=t.dbConnectors[0].id,p=r.typeDB.get(i)?.session,d=r.typeDB.get(i)?.client;if(!p){console.log("Session Status: ","NO SESSION");return}await p.close();let[{dbName:h}]=t.dbConnectors;await(await d.databases.get(h)).delete(),await d.databases.create(h);let s=await d.session(t.dbConnectors[0].dbName,SessionType.SCHEMA),a=await s.transaction(TransactionType.WRITE);await a.query.define(o),await a.commit(),await a.close();let u=await s.transaction(TransactionType.READ);(await(await u.query.match("match $a sub thing;")).collect()).forEach(async m=>{m.get("a");}),await u.close();};var Dt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Ct=(t,e,r)=>r?e:`${t}\xB7${e}`;var Ot=(t,e)=>Object.values(Object.fromEntries(Object.entries(t).filter(([r,n])=>e(r,n))))[0],Se=(t,e)=>Object.fromEntries(Object.entries(t).filter(([r,n])=>e(r,n))),xt=(t,e)=>{let r=[],n=produce(t,i=>traverse(i,({key:p,value:d,meta:h})=>{if(h.depth===2&&(p&&(d.dataFields=d.dataFields?.map($=>({...$,cardinality:$.cardinality||"ONE",dbPath:Ct(p,$.path,$.shared)}))),d.extends)){if(!d.defaultDBConnector.as)throw new Error(`[Schema] ${p} is extending a thing but missing the "as" property in its defaultDBConnector`);let $=i.entities[d.extends]||i.relations[d.extends];if(d.allExtends=[d.extends,...$.allExtends||[]],d.idFields=$.idFields?(d.idFields||[]).concat($.idFields):d.idFields,d.dataFields=$.dataFields?(d.dataFields||[]).concat($.dataFields.map(s=>{let a=d.extends,u=t.entities[a]||t.relations[a];for(;!u.dataFields?.find(f=>f.path===s.path);)a="extends"in u?u.extends:void 0,u=t.entities[a]||t.relations[a];return {...s,dbPath:Ct(a,s.path,s.shared)}})):d.dataFields,d.linkFields=$.linkFields?(d.linkFields||[]).concat($.linkFields):d.linkFields,"roles"in $){let s=d,a=$;s.roles=s.roles||{},s.roles={...s.roles,...a.roles},Object.keys(s.roles).length===0&&(s.roles={});}$?.hooks?.pre&&(d.hooks=d.hooks||{},d.hooks.pre=d.hooks.pre||[],d.hooks.pre=[...$?.hooks?.pre||[],...d?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(t,({key:i,value:p,meta:d})=>{if(i==="linkFields"){let $=(()=>{if(!d.nodePath)throw new Error("No path");let[a,u]=d.nodePath.split(".");return {thing:u,thingType:a==="entities"?"entity":a==="relations"?"relation":""}})(),s=Array.isArray(p)?p.map(a=>({...a,...$})):[{...p,...$}];r.push(...s);}}),produce(n,i=>traverse(i,({value:p,key:d,meta:h})=>{if(h.depth===2&&p.idFields&&!p.id){p.name=d;let $=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=$();let s=Object.keys(e).find(a=>e[a]?.get(p.defaultDBConnector.id));p.db=s,p.dbContext=Dt[s],p.computedFields=[],p.virtualFields=[],p.requiredFields=[],p.enumFields=[],p.fnValidatedFields=[],"roles"in p&&Object.entries(p.roles).forEach(([u,f])=>{f.fieldType="roleField",f.playedBy=r.filter(l=>l.relation===d&&l.plays===u)||[],f.name=u;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(u=>{if(u.fieldType="linkField",u.target==="relation"){u.oppositeLinkFieldsPlayedBy=[{plays:u.path,thing:u.relation,thingType:"relation"}];return}let f=r.filter(c=>c.relation===u.relation&&c.plays!==u.plays)||[];u.oppositeLinkFieldsPlayedBy=f;let{filter:l}=u;u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>c.target==="role"),l&&Array.isArray(l)&&(u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>l.some(m=>c.thing===m.$role)),u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>l.some(m=>c.thing===m.$thing))),l&&!Array.isArray(l)&&(u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>c.$role===l.$role),u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>c.thing===l.$thing));});}if(typeof p=="object"&&"playedBy"in p){let $=[...new Set(p.playedBy.map(s=>s.thing))];if($.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${d}, path:${h.nodePath}, played by: ${$.join(", ")}`);if(p.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${d}, path:${h.nodePath}`)}if(h.depth===4){let[$,s]=h.nodePath?.split(".")||[],a=i[$][s];p.validations&&(p.validations.required&&a.requiredFields.push(p.path),p.validations.enum&&a.enumFields.push(p.path),p.validations.fn&&a.fnValidatedFields.push(p.path)),p.default?p.isVirtual?a.virtualFields.push(p.path):a.computedFields.push(p.path):p.isVirtual&&a.virtualFields.push(p.path);}}))},G=(t,e)=>{if(e in t.entities)return t.entities[e];if(e in t.relations)return t.relations[e];throw new Error(`${e} is not defined in the schema`)},C=(t,e)=>{if(!e)throw new Error("[Internal] No node for getCurrentSchema");if(e.$thing){if(e.$thingType==="entity"){if(!(e.$thing in t.entities))throw new Error(`Missing entity '${e.$thing}' in the schema`);return t.entities[e.$thing]}if(e.$thingType==="relation"){if(!(e.$thing in t.relations))throw new Error(`Missing relation '${e.$thing}' in the schema`);return t.relations[e.$thing]}if(e.$thing in t.entities&&e.$thing in t.relations)throw new Error(`Ambiguous $thing ${e.$thing}`);if(e.$thing in t.entities)return t.entities[e.$thing];if(e.$thing in t.relations)return t.relations[e.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(e,null,2)}`)}if(e.$entity){if(!(e.$entity in t.entities))throw new Error(`Missing entity '${e.$entity}' in the schema`);return t.entities[e.$entity]}if(e.$relation){if(!(e.$relation in t.relations))throw new Error(`Missing relation '${e.$relation}' in the schema`);return t.relations[e.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(e,null,2)}`)},jt=(t,e)=>{let r=t.$thing||t.$entity||t.$relation;if(!r)throw new Error("[Internal] No thing found");if(t.$entity)return "entity";if(t.$relation)return "relation";if(e.entities[r])return "entity";if(e.relations[r])return "relation";throw new Error("No thing found")},et=(t,e,r)=>{let n=C(t,e),o=n.linkFields?.find(d=>d.path===r);if(o)return o;let i=n.dataFields?.find(d=>d.path===r);if(i)return i;let p="roles"in n?n.roles?.[r]:void 0;if(p)return p},tt=(t,e,r)=>et(t,e,r)?.cardinality,pe=(t,e)=>{let r=t.dataFields?.map(l=>l.path)||[],n=t.linkFields?.map(l=>l.path)||[],o="roles"in t?listify(t.roles,l=>l):[],i=[...r||[],...n||[],...o||[]],d=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!e)return {fields:i,dataFields:r,roleFields:o,linkFields:n};let h=e.$fields?e.$fields.map(l=>{if(typeof l=="string"){if(l.startsWith("$")||l.startsWith("%"))return;if(!i.includes(l))throw new Error(`Field ${l} not found in the schema`);return l}if("$path"in l&&typeof l.$path=="string")return l.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(e,l=>{if(!(l.startsWith("$")||l.startsWith("%"))){if(!i.includes(l))throw new Error(`[Schema] Field ${l} not found in the schema`);return l}}).filter(l=>l!==void 0),$=e.$filter?listify(e.$filter,l=>l.toString().startsWith("$")?void 0:l.toString()).filter(l=>l&&r?.includes(l)):[],s=e.$filter?listify(e.$filter,l=>l.toString().startsWith("$")?void 0:l.toString()).filter(l=>l&&[...o||[],...n||[]].includes(l)):[],a=[...h,...$].filter(l=>!l?.startsWith("%")).filter(l=>!d.includes(l)).filter(l=>l),u=e.$filter?Se(e.$filter,(l,c)=>$.includes(l)):{},f=e.$filter?Se(e.$filter,(l,c)=>s.includes(l)):{};return {fields:i,dataFields:r,roleFields:o,linkFields:n,usedFields:h,usedLinkFields:n.filter(l=>h.includes(l)),usedRoleFields:o.filter(l=>h.includes(l)),usedDataFields:r.filter(l=>h.includes(l)),unidentifiedFields:a,...$.length?{localFilters:u}:{},...s.length?{nestedFilters:f}:{}}};var Nt=t=>{if(typeof t!="string")throw new Error("capitalizeFirstLetter: string is not a string");return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()},_t=(t,e,r)=>{let o=(r.nodePath||"").split("."),i=isArray(e)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return e?getNodeByPath(t,i):{}},ye=t=>Reflect.ownKeys(t).filter(e=>typeof e=="symbol").reduce((e,r)=>(e[r]=t[r],e),{});var De=t=>isObject(t)&&("$entity"in t||"$relation"in t||"$thing"in t),me=t=>{if(Array.isArray(t))return t.map(e=>current(e));if(t&&typeof t=="object"){let e=isDraft(t)?current(t):t,r={};return Object.entries(e).forEach(([n,o])=>{r[n]=isDraft(o)?current(o):o;}),r}else return t},le=(t,e)=>{if(t===void 0)throw e?new Error(e):new Error("Value is undefined");return t},q=(t,e)=>{let r="";for(let n=0;n<e;n++)r+=" ";return `${r}${t}`};var Le=(t,e)=>{if(e.fieldType==="linkField"){let r=e.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${t} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${t} should have a player`);return r}else if(e.fieldType==="roleField"){if([...new Set(e.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${t} should have a single player`);if(!e.playedBy?.length)throw new Error(`[Internal] Field ${t} should have a player`);return e.playedBy}else throw new Error(`[Internal] Field ${t} is not a linkField or roleField`)};var zt=(t,e,r)=>{let n=isArray(t[e])?t[e]:[t[e]];if(!n.every(o=>typeof o=="object"))if(n.every(o=>typeof o=="string")){let o=Le(e,r),[i]=o,p=t.$op==="create"?"link":"replace",d=i.thing,h=i.thingType;if(n.some($=>$.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");t[e]={$id:t[e],$op:p,$thing:d,$thingType:h,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${e} Nodes: ${JSON.stringify(n)} Parent: ${JSON.stringify(t,null,2)})`)};var we=(t,e,r)=>{let n=C(r,e),{usedDataFields:o}=pe(n,e);if(e.$op){if(e.$op==="create"&&e.$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(e.$op)&&t.$op==="create")throw new Error(`[Wrong format] Cannot ${e.$op} under a create`);if(e.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(e.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return e.$op}};var Pe=(t,e,r)=>{let n=C(r,e),{usedFields:o}=pe(n,e);return e.$op?(we(t,e,r),e.$op):e.$id||e.$filter?o.length>0?(we(t,{...e,$op:"update"},r),"update"):(we(t,{...e,$op:"link"},r),"link"):e.$tempId?o.length>0?(we(t,{...e,$op:"create"},r),"create"):(we(t,{...e,$op:"create"},r),"link"):(we(t,{...e,$op:"create"},r),"create")};var Wt=(t,e)=>{let n=(isArray(t.$root)?t.$root:[t.$root]).map(o=>{let i=Pe(o,o,e);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:jt(o,e)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});t.$root=isArray(t.$root)?n:n[0];};var v=Symbol.for("queryPath"),Ie=Symbol.for("stepPrint"),Te=Symbol.for("edgeType"),ge=Symbol.for("edgeSchema");var Ce=(t,e)=>{let r=e[Ie];return isSet(r)?r.has("clean")?(Reflect.set(e,Ie,r.add("clean")),!0):!1:(Reflect.set(e,Ie,new Set(["clean"])),!0)};var Ht=(t,e,r)=>{if(Ce("split_ids",t)){let n=(isArray(t[e])?t[e]:[t[e]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let i=o;if(C(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((p,d)=>({...me(i),$id:p,$bzId:`${i.$bzId}_${d}`,...ye(i)}))}return o});(n.length>isArray(t[e])?t[e]:[t[e]].length)&&(t[e]=n);}};var Ut=(t,e,r,n)=>{let o=(isArray(t[e])?t[e]:[t[e]]).map(i=>{let p=Le(e,r),[d]=p,h=Pe(t,{...i,$thing:d.thing,$thingType:d.thingType},n),$=i.$bzId?i.$bzId:i.$tempId?i.$tempId:`N_${v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[ge]:r,$thing:d.thing,$thingType:d.thingType,$op:h,$bzId:$}});t[e]=isArray(t[e])?o:o[0];};var Pn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,In=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Kt=t=>{let r=t.toString().replace(Pn,"").trim().split("=>")[0].split("{")[0].replace(In,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(d=>d.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var Be=({currentThing:t,fieldSchema:e,mandatoryDependencies:r=!1})=>{if(!e||!e.default||!("fn"in e.default||"value"in e.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(e,null,3)}`);if(e.default.type==="value")return e.default.value;if(r){let{fn:o}=e.default,p=Kt(o).filter(d=>!(d in t));if(p.length)throw new Error(`Virtual field: Missing arguments ${p.join(", ")}`)}if(!e.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in e?e.default?.fn(t):void 0};var Jt=(t,e,r)=>{let n=t[e];n&&(isArray(n)?n:[n]).forEach(o=>{let i=C(r,o),{unidentifiedFields:p}=pe(i,o),{computedFields:d,virtualFields:h}=i,$=listify(o,(u,f)=>f!==void 0?u:void 0),s=$.filter(u=>h?.includes(u));if(s.length>0)throw new Error(`Virtual fields can't be sent to DB: "${s.join(",")}"`);if(d.filter(u=>!$.includes(u)).forEach(u=>{let f=i.dataFields?.find(B=>B.path===u),c=i.linkFields?.find(B=>B.path===u)?.oppositeLinkFieldsPlayedBy[0],m="roles"in i?Ot(i.roles,(B,T)=>B===u):void 0,y=f||c||m;if(!y)throw new Error(`no field Def for ${u}`);if(o.$op==="create"&&!o[u]){let B=Be({currentThing:o,fieldSchema:y,mandatoryDependencies:!0});o[u]=B;}}),p.length>0)throw new Error(`Unknown fields: [${p.join(",")}] in ${JSON.stringify(o)}`)});};var Oe=(t,e)=>{let r=C(e,t).hooks;if(r?.pre){let n=`on${Nt(t.$op)}`;return r.pre.filter(p=>!p.triggers||p.triggers[n]?.()).flatMap(p=>p.actions)}return []};var Gt=(t,e,r,n)=>{(isArray(t[e])?t[e]:[t[e]]).forEach(i=>{if("$thing"in i){let{requiredFields:p,enumFields:d,fnValidatedFields:h,dataFields:$}=C(r,i);if("$op"in i&&i.$op==="create"&&p.forEach(s=>{if(!(s in i))throw new Error(`[Validations] Required field "${s}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&d.forEach(s=>{if(s in i){let a=$?.find(u=>u.path===s)?.validations?.enum;if(!a)throw new Error(`[Validations] Enum field "${s}" is missing enum options.`);if(isArray(i[s]))i[s].some(u=>{if(!a.includes(u))throw new Error(`[Validations] Option "${u}" is not a valid option for field "${s}".`)});else if(a&&!a.includes(i[s]))throw new Error(`[Validations] Option "${i[s]}" is not a valid option for field "${s}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&h.forEach(s=>{if(s in i)try{let a=$?.find(u=>u.path===s)?.validations?.fn;if(!a)throw new Error("Missing validation function.");if(!a(i[s]))throw new Error("Failed validation function.")}catch(a){throw new Error(`[Validations:attribute:${s}] ${a.message}`)}}),isObject(i)&&"$thing"in i){let s=i.$thing,a=i,u=clone(me(t)),f=clone(me(a)),l=n.mutation?.context||{};Oe(a,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let y=m.fn(f,u,l);if(y===!1)throw new Error(`${m.message}.`);if(y!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(y){throw new Error(`[Validations:thing:${s}] ${y.message}`)}}});}}});};var tr=(t,e,r,n)=>{let o=(isArray(t[e])?t[e]:[t[e]]).map(i=>{if(De(i)){let p=Oe(i,r).filter(s=>s.type==="transform"),d=clone(me(t)),h=clone(me(i)),$=n.mutation?.context||{};return p.forEach(s=>{let a=s.fn(h,d,$);Object.keys(a).length!==0&&(i={...h,...a,...ye(i)});}),i}});t[e]=isArray(t[e])?o:o[0];};var rr=(t,e,r)=>{let n=Le(e,r),[o]=n;t[e]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[ge]:r};};var Hn=(t,e)=>{if(t[e]===void 0&&delete t[e],e==="$tempId")if(Ce("set_tempId",t))if(t.$tempId?.startsWith("_:")){let r=t.$tempId.substring(2);t.$tempId=r,t.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},vn=(t,e)=>{},it=(t,e,r)=>{let o=produce({$rootWrap:{$root:t}},i=>traverse(i,({value:p,parent:d,key:h,meta:$})=>{if(!(!d||!h)&&isObject(p)){if(!("$root"in p)){if(!("$thing"in p||"$entity"in p||"$relation"in p))throw h==="$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(p)?current(p):p)}`)}let s=p;Object.keys(s).forEach(a=>{if(Hn(s,a),a!=="$root"&&(a.startsWith("$")||a.startsWith("%")))return;let u=a!=="$root"?et(e,s,a):{fieldType:"rootField"};if(!u)throw new Error(`[Internal] Field ${a} not found in schema`);if("contentType"in u)return vn();if(["rootField","linkField","roleField"].includes(u.fieldType)){if(["linkField","roleField"].includes(u.fieldType)&&(s[a]===null?rr(s,a,u):zt(s,a,u)),u.fieldType==="rootField"){if(!("$root"in s))throw new Error(`[Internal] Field ${a} is a rootField but the object is not a root`);Wt(s,e);}let f=isArray(s[a])?s[a]:[s[a]],l=$.nodePath?.split(".").slice(1).join(".");f.forEach(m=>{if(m){if(u?.cardinality==="ONE"&&!m.$op&&!m.$id&&!m.$filter&&!m.$tempId&&s.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${l}.${a}`);if(m.$tempId&&!(m.$op===void 0||m.$op==="link"||m.$op==="create"||m.$op==="update"))throw new Error(`Invalid op ${m.$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(u.fieldType)&&Ut(s,a,u,e),Ht(s,a,e),["rootField","linkField","roleField"].includes(u.fieldType)&&Jt(s,a,e),(isArray(s[a])?s[a]:[s[a]]).forEach(m=>{let y=C(e,m),{unidentifiedFields:B,usedLinkFields:T,usedFields:g,fields:Q}=pe(y,m);if(g.forEach(M=>{if(!Q.includes(M))throw new Error(`[Schema] Field ${M} not found in the schema`)}),B.length>0)throw new Error(`Unknown fields: [${B.join(",")}] in ${JSON.stringify(p)}`);if(T.length>1){let M=y.linkFields?.filter(L=>T.includes(L.path));M?.some((L,A)=>M.some((R,D)=>{if(A!==D&&L.target!==R.target&&L.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.")}));}}),tr(s,a,e,r),Gt(s,a,e,r);}});}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var Qe=async(t,e)=>{let r=e.dbConnectors[0].id,n=t.typeDB?.get(r)?.session,o=t.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!o)throw new Error("Client not found");n=await o.session(e.dbConnectors[0].dbName,SessionType.DATA),t.typeDB?.set(r,{client:o,session:n});}return {client:o,session:n}};var nr=async(t,e,r)=>{if(!t)throw new Error("TQL request not built");if(!(t.deletions&&t.deletionMatches||t.insertions))throw new Error("TQL request error, no things");let{session:n}=await Qe(e,r),o=await n.transaction(TransactionType.WRITE);if(!o)throw new Error("Can't create transaction");let i=t.deletionMatches&&t.deletions&&`match ${t.deletionMatches} delete ${t.deletions}`,p=t.insertions&&`${t.insertionMatches?`match ${t.insertionMatches}`:""} insert ${t.insertions}`;i&&await o.query.delete(i);let d=p&&o.query.insert(p);try{let h=d?await d.collect():void 0;return await o.commit(),await o.close(),{insertions:h}}catch(h){throw await o.close(),new Error(`Transaction failed: ${h.message}`)}};var ir=async(t,e,r,n,o)=>{let i=[...e,...r],p=i.map(d=>{let h=t.insertions?.find(a=>a.get(`${d.$bzId}`))?.get(`${d.$bzId}`),$=d.$thing||d.$relation||d.$entity,s=$?G(n,$):void 0;if(d.$op==="create"||d.$op==="update"||d.$op==="link"){if(d.$op!=="update"&&!h&&d.$id)return {$id:d.$id,$error:"Does not exist or it's not linked to the parent"};let a=h?.asThing().iid,u=Object.entries(d).filter(([l,c])=>!l.startsWith("$")).reduce((l,[c,m])=>{if(s?.dataFields?.find(B=>B.path===c)?.contentType==="JSON")return l[c]=JSON.parse(m),l;if(d.$thingType==="relation"){let B=i.filter(T=>T.$id&&T.$bzId===m);if(B.length>1)throw new Error(`Multiple things with the same bzId ${m}`);return B.length===1?(l[c]=B[0].$id,l):(l[c]=m,l)}return l[c]=m,l},{});if(o.mutation?.noMetadata)return u;let f=d.$tempId&&!d.$tempId.startsWith("_:")?{$tempId:`_:${d.$tempId}`}:{};return {$dbId:a,...d,...u,[d.path]:d.$id,...f}}if(d.$op==="delete"||d.$op==="unlink")return d;if(d.$op!=="match")throw new Error(`Unsupported op ${d.$op}`)}).filter(d=>d);return clone(p)};var sr=t=>{let e=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(t,r=>traverse(r,e))};var cr=async(t,e)=>{let r=s=>{let a=[],u=[],f=y=>{if(y.$id)return y.$id;let B=C(e,y),{idFields:T}=B;if(!T)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[g]=T;if(!g)throw new Error(`no idField: ${JSON.stringify(y)}`);let Q=B.dataFields?.find(A=>A.path===g),M=Be({currentThing:y,fieldSchema:Q,mandatoryDependencies:!0}),L=y[g]||y.$id||M;if(!L)throw new Error(`no idValue: ${JSON.stringify(y)}`);return L},l=y=>{if(y.$op==="create"){let B=f(y);if(a.find(T=>T.$id===B&&T.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(y)}`);if(u.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate $bzId ${y.$bzId} for node ${JSON.stringify(y)}`);a.push({...y,$id:B});return}y.$tempId&&y.$op==="match"||a.push(y);},c=y=>{if(y.$op==="create"){let B=f(y);if(a.find(T=>T.$id===B),u.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate %bzId ${y.$bzIdd} for edge ${JSON.stringify(y)}`);u.push({...y,$id:B});return}u.push(y);};return traverse(s,({value:y,parent:B,meta:T})=>{if(!isObject(y))return;let g=y;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let Q=C(e,g),{dataFields:M,roleFields:L,linkFields:A,usedFields:R}=pe(Q,g),D=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let w=R.filter(E=>M?.includes(E)),F=R.filter(E=>L?.includes(E)),k=R.filter(E=>A?.includes(E));if(w.length>0)return "update";if(F.length>0||k.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},N={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,M||[""])),$op:D(),$bzId:g.$bzId};l(N);let x=g[ge];if(x?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");a.push({...g,$op:"match"});}let w=x.relation===g.$thing,F=w?g.$bzId:`LT_${v4()}`,E=_t(s,B,T).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return w?"match":"delete";if(g.$op==="unlink")return w?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return w?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},S=C(e,{$thing:x.relation,$thingType:"relation"});if(!Object.keys(S.roles).includes(x.plays))throw new Error(`[Wrong format] Field ${x.plays} is not a role of relation ${x.relation}`);let I={$bzId:F,$thing:x.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...w?{}:{[x.path]:g.$bzId},[x.plays]:E,[ge]:x,[Te]:"linkField"};c(I),(g.$op==="unlink"||b()==="unlink")&&w&&c({$thing:x.relation,$thingType:"relation",$bzId:F,$op:"match",[x.plays]:E,[ge]:x,[Te]:"linkField"});}if(g.$thingType==="relation"){let w=Se(g,(E,b)=>L.includes(E)),F=mapEntries(w,(E,b)=>isArray(b)?[E,b]:isObject(b)?[E,b.$bzId]:[E,b]),k=Se(y,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(w).filter(E=>!E.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let E=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},b=C(e,g).roles,S=mapEntries(F,(I,O)=>{let H=b[I]?.cardinality;if(!H)throw new Error(`Role ${I} not found in schema`);if(Array.isArray(O)){if(H==="ONE"){if(O.length>1)throw new Error(`[Error] Role ${I} is not a MANY relation`);return [I,O[0].$bzId||O[0]]}return [I,O.map(oe=>oe.$bzId||oe)]}return [I,O.$bzId||O]}),_={...k,$thing:g.$thing,$thingType:"relation",$op:E(),...S,$bzId:g.$bzId,[Te]:"roleField"};c(_);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(w).length>0){let E=0;Object.entries(w).forEach(([b,S])=>{let _=isArray(S)?S:[S],I=O=>O==="create"||O==="replace"?"link":O;_.forEach(O=>{if(!O)return;let H=I(O.$op);if(H==="replace")throw new Error("Not supported yet: replace on roleFields");if(H==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let oe={...k,$thing:g.$thing,$thingType:"relation",$op:H==="delete"?"unlink":H,[b]:O.$bzId,$bzId:g.$bzId,[Te]:"roleField"};c(oe);});});}}}}}),[a,u]},[n,o]=r(t),i=n.reduce((s,a)=>{if(!a.$bzId)return [...s,a];let u=s.findIndex(f=>f.$bzId===a.$bzId);if(u===-1)return [...s,a];if(s[u].$op==="create"&&a.$op==="match")return s;if(s[u].$op==="match"&&(a.$op==="create"||a.$op==="match"))return [...s.slice(0,u),a,...s.slice(u+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${a.$tempId}". Existing: ${s[u].$op}. Current: ${a.$op}`)},[]),p=o.reduce((s,a)=>{let u=s.find(f=>(f.$id&&f.$id===a.$id||f.$bzId&&f.$bzId===a.$bzId)&&f.$thing===a.$thing&&f.$op===a.$op);if(u){let f={...u};return Object.keys(a).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let m=u[c],y=a[c];Array.isArray(m)&&Array.isArray(y)?f[c]=Array.from(new Set([...m,...y])):!Array.isArray(m)&&Array.isArray(y)?m!==void 0?f[c]=Array.from(new Set([m,...y])):f[c]=y:Array.isArray(m)&&!Array.isArray(y)?y!==void 0&&(f[c]=Array.from(new Set([...m,y]))):m!==null&&y!==null&&m!==void 0&&y!==void 0?f[c]=Array.from(new Set([m,y])):m==null&&(f[c]=y);}),[...s.filter(c=>!((c.$id&&c.$id===a.$id||c.$bzId&&c.$bzId===a.$bzId)&&c.$thing===a.$thing&&c.$op===a.$op)),f]}return [...s,a]},[]);i.forEach(s=>{if((s.$thingType==="relation"||"relation"in s)&&p.filter(a=>a.$bzId===s.$bzId||a.$tempId&&a.$tempId===s.$tempId).length===0){if(s.$op==="delete"||s.$op==="match"||s.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(sr(s))}`)}});let d=[...i,...p],h=new Set(d.filter(s=>s.$tempId).map(s=>s.$tempId)),$=Array.from(h).filter(s=>!d.some(a=>a.$tempId===s&&a.$op==="create"));if($.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${$.join(", ")}`);return {mergedThings:i,mergedEdges:p}};var dr=async(t,e,r)=>{let n=u=>{let f=u.$op,l=`$${u.$bzId}`,c=C(r,u),{idFields:m,defaultDBConnector:y}=c,B=y?.path||u.$thing,T=u.$id,g=m?.[0],Q=listify(u,(w,F)=>{if(w.startsWith("$")||w.startsWith("%")||w===g||F===void 0||F===null)return "";let k=c.dataFields?.find(S=>S.path===w);if(!k?.path)return "";let b=k.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(k.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(k.contentType))return `has ${b} ${F}`;if(k.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${b} ${F.toISOString().replace("Z","")}`:`has ${b} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${k.contentType}`)}).filter(w=>w),M=`${l}-atts`,L=listify(u,w=>{if(w.startsWith("$")||w.startsWith("%")||w===g)return "";let F=c.dataFields?.find(b=>b.path===w);if(!F?.path)return "";let E=F.dbPath;return `{${M} isa ${E};}`}).filter(w=>w),A=isArray(T)?`like '${T.join("|")}'`:`'${T}'`,R=T?[`has ${g} ${A}`]:[],D=[...R,...Q].filter(w=>w).join(","),N=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${l} isa ${[B,...R].filter(w=>w).join(",")};`;if(f==="update"){if(!L.length)throw new Error("update without attributes");return `${l} isa ${[B,...R].filter(w=>w).join(",")}, has ${M};
37
- ${L.join(" or ")};`}return ""},x=()=>f==="update"||f==="link"||f==="match"?`${l} isa ${[B,...R].filter(w=>w).join(",")};`:"";if(De(u))return {op:f,deletionMatch:N(),insertionMatch:x(),insertion:f==="create"?`${l} isa ${[B,D].filter(w=>w).join(",")};`:f==="update"&&Q.length?`${l} ${Q.join(",")};`:"",deletion:f==="delete"?`${l} isa ${B};`:f==="update"&&L.length?`${l} has ${M};`:""};throw new Error("in attributes")},o=u=>{let f=u.$op,l=C(r,u),c=`$${u.$bzId}`,m=u.$id,y=l.defaultDBConnector?.path||u.$thing,B="roles"in l?listify(l.roles,F=>F):[],T="roles"in l?mapEntries(l.roles,(F,k)=>[F,k.dbConnector?.path||F]):{},g=listify(u,(F,k)=>{if(!B.includes(F))return null;if(!("roles"in l))throw new Error("This should have roles! ");let E=T[F];return Array.isArray(k)?k.map(b=>({path:E,id:b})):{path:E,id:k}}).filter(F=>F).flat(),Q=g.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),M=g.length>0?`( ${Q.join(" , ")} )`:"",L=u[Te];if(!L)throw new Error("[internal error] Symbol edgeType not defined");let A=M?`${c} ${M} ${L==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",R=`${c} ${L==="linkField"||f==="delete"?`isa ${y}`:""}`,D=()=>A?f==="link"?`${A};`:f==="create"?`${A}, has id '${m}';`:"":"",N=()=>A&&f==="match"?`${A};`:"",x=()=>A?f==="delete"?`${A};`:f==="match"?`${A};`:"":"",w=()=>A?f==="delete"?`${R};`:f==="unlink"?`${c} ${M};`:"":"";return {deletionMatch:x(),insertionMatch:N(),deletion:w(),insertion:D(),op:""}},i=(u,f)=>{let l=f==="edges"?o:n;if(Array.isArray(u))return u.map(g=>{let{preDeletionBatch:Q,insertionMatch:M,deletionMatch:L,insertion:A,deletion:R}=l(g);return shake({preDeletionBatch:Q,insertionMatch:M,deletionMatch:L,insertion:A,deletion:R},D=>!D)}).filter(g=>g);let{preDeletionBatch:c,insertionMatch:m,deletionMatch:y,insertion:B,deletion:T}=l(u);return shake({preDeletionBatch:c,insertionMatch:m,deletionMatch:y,insertion:B,deletion:T},g=>!g)},p=i(t),d=Array.isArray(p)?p:[p],h=i(e,"edges"),$=Array.isArray(h)?h:[h],s=[...d,...$];return shake({insertionMatches:s.map(u=>u.insertionMatch).join(" ").trim(),deletionMatches:s.map(u=>u.deletionMatch).join(" ").trim(),insertions:s.map(u=>u.insertion).join(" ").trim(),deletions:s.map(u=>u.deletion).join(" ").trim()},u=>!u)};var ot="___",pr=async t=>{let{enrichedBqlQuery:e,schema:r}=t;if(!e)throw new Error("BQL query not enriched");let n="",o=(s,a,u)=>{let f=[],l=[],c="";for(let B=0;B<s.length;B++)s[B].$isVirtual||f.push(s[B].$dbPath),l.push(`{${s[B].$dbPath}:${s[B].$as}}`);let m=f.join(", ");c=l.join(",");let y=`$metadata:{as:[${c}]}`;n+=P(`$${a} as "${a}.${y}.$dataFields": ${m};`,u);},i=(s,a,u,f)=>{let l=f+1;for(let c of s){let{$fields:m,$as:y,$justId:B,$idNotIncluded:T,$filterByUnique:g,$thing:Q,$sort:M,$offset:L,$limit:A}=c,R=c[v],D=`$metadata:{as:${y},justId:${B?"T":"F"},idNotIncluded:${T},filterByUnique:${g}}`;n+=P(`"${u}.${D}.${c.$var}": {`,f),n+=P("match",l);let N=`${a}${ot}${c.$var}`;n+=P(`$${N} isa ${c.$thing};`,l),n+=P(`$${a} (${c.$var}: $${a}${ot}${c.$var}) isa ${c.$intermediary};`,l),c.$filter&&(n+=je({$filter:c.$filter,$var:N,$thing:c.$thing,schema:r,depth:l}));let x=_e({schema:r,$thing:Q,$var:N,$sort:M,depth:l});if(x&&(n+=x.match),m){let w=`M_${v4()}`;n+=P(`
38
- ?queryPath${w} = "${R}";`,l),n+=P("fetch",l),n+=P(`?queryPath${w} as "queryPath";`,l);let F=m?.filter(b=>b.$fieldType==="data");F&&F.length>0&&o(F,N,`${a}.${c.$var}`);let k=m?.filter(b=>b.$fieldType==="link");k&&k.length>0&&p(k,N,`${a}.${c.$var}`,l);let E=m?.filter(b=>b.$fieldType==="role");E&&E.length>0&&i(E,N,`${a}.${c.$var}`,l);}x&&(n+=x.sort),typeof L=="number"&&(n+=P(`offset ${L};`,l)),typeof A=="number"&&(n+=P(`limit ${A};`,l)),n+=P("};",f);}},p=(s,a,u,f)=>{let l=f+1;for(let c of s){let{$fields:m,$as:y,$justId:B,$idNotIncluded:T,$filterByUnique:g,$playedBy:Q,$thing:M,$sort:L,$offset:A,$limit:R}=c,D=c[v],N=`$metadata:{as:${y},justId:${B?"T":"F"},idNotIncluded:${T},filterByUnique:${g}}`;n+=P(`"${u}.${N}.${c.$var}": {`,f),n+=P("match",l);let x=`${a}${ot}${c.$var}`;n+=P(`$${x} isa ${c.$thing};`,l),c.$filter&&(n+=je({$filter:c.$filter,$var:x,$thing:c.$thing,schema:r,depth:l}));let w=_e({schema:r,$thing:M,$var:x,$sort:L,depth:l});if(w&&(n+=w.match),c.$target==="role"?n+=P(`$${a}_intermediary (${c.$plays}: $${a}, ${Q.plays}: $${x}) isa ${c.$intermediary};`,l):n+=`
39
- $${x} (${c.$plays}: $${a}) isa ${c.$thing};`,m){let F=`M_${v4()}`;n+=P(`?queryPath${F} = "${D}";`,l),n+=P("fetch",l),n+=P(`?queryPath${F} as "queryPath";`,l);let k=m?.filter(S=>S.$fieldType==="data");k&&k.length>0&&o(k,x,l);let E=m?.filter(S=>S.$fieldType==="link");E&&E.length>0&&p(E,x,`${a}.${c.$var}`,l);let b=m?.filter(S=>S.$fieldType==="role");b&&b.length>0&&i(b,x,`${a}.${c.$var}`,l);}w&&(n+=w.sort),typeof A=="number"&&(n+=P(`offset ${A};`,l)),typeof R=="number"&&(n+=P(`limit ${R};`,l)),n+=P("};",f);}},d=e.length>1,h=[];(s=>{if(d)for(let a of s){let{$path:u,$thing:f,$filter:l,$fields:c,$sort:m,$offset:y,$limit:B}=a;if(!u)throw new Error("Path is not defined");let T=a[v];if(n+=`
40
- match
41
- $${u} isa ${f};`,l){let M=je({$filter:l,$var:u,$thing:f,schema:r,depth:0});n+=`
42
- ${M}`;}let g=_e({schema:r,$thing:f,$var:u,$sort:m,depth:0});g&&(n+=g.match);let Q=`M_${v4()}`;if(n+=`
43
- ?queryPath${Q} = "${T}";`,n+=`
44
- fetch`,n+=`
45
- ?queryPath${Q} as "queryPath";`,c){let M=c.filter(R=>R.$fieldType==="data");M&&M.length>0&&o(M,u,0);let L=c.filter(R=>R.$fieldType==="link");L&&L.length>0&&p(L,u,u,0);let A=c.filter(R=>R.$fieldType==="role");A&&A.length>0&&i(A,u,u,0);}g&&(n+=g.sort),typeof y=="number"&&(n+=`
46
- offset ${y};`),typeof B=="number"&&(n+=`
47
- limit ${B};`),h.push(n),n="";}else for(let a of s){let{$path:u,$thing:f,$filter:l,$fields:c,$sort:m,$offset:y,$limit:B}=a;if(!u||u==="undefined")throw new Error("Path is not defined");let T=a[v];n+=`
48
- match
49
- $${u} isa ${f};`,l&&(n+=je({$filter:l,$var:u,$thing:f,schema:r,depth:0}));let g=_e({schema:r,$thing:f,$var:u,$sort:m,depth:0});if(g&&(n+=g.match),n+=`
50
- ?queryPath = "${T}";`,n+=`
51
- fetch`,n+=`
52
- ?queryPath as "queryPath";`,c){let Q=c.filter(A=>A.$fieldType==="data");Q&&Q.length>0&&o(Q,u,0);let M=c.filter(A=>A.$fieldType==="link");M&&M.length>0&&p(M,u,u,0);let L=c.filter(A=>A.$fieldType==="role");L&&L.length>0&&i(L,u,u,0);}g&&(n+=g.sort),typeof y=="number"&&(n+=`
53
- offset ${y};`),typeof B=="number"&&(n+=`
54
- limit ${B};`);}})(e),t.tqlRequest=d?h:n;},je=t=>{let{$filter:e,$var:r,$thing:n,schema:o,depth:i}=t,{$not:p,...d}=e,h=G(o,n),$=[];return Object.entries(p||{}).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){a===null?$.push(P(`$${r} has ${s} $${s}_${v4()};`,i)):Array.isArray(a)?a.forEach(l=>{$.push(P(`not { $${r} has ${s} ${ie(l)}; };`,i));}):$.push(P(`not { $${r} has ${s} ${ie(a)}; };`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")a===null?$.push(P(`(${f.plays}: $${r}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(y=>{$.push(P(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(y)}; };`,i));}):$.push(P(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(a)}; };`,i));else {let y=`${l.thing}_${v4()}`;a===null?$.push(P(`$${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(B=>{$.push(P(`not { $${y} isa ${l.thing}, has ${m} ${ie(B)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}):$.push(P(`not { $${y} isa ${l.thing}, has ${m} ${ie(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${v4()}`;a===null?$.push(P(`$${r} (${c.plays}: ${B});`,i)):Array.isArray(a)?a.forEach(T=>{$.push(P(`not { $${B} isa ${c.thing}, has ${y} ${ie(T)}; $${r} (${c.plays}: $${B}); };`,i));}):$.push(P(`not { $${B} isa ${c.thing}, has ${y} ${ie(a)}; $${r} (${c.plays}: $${B}); };`,i));return}}}),Object.entries(d).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){if(a===null)$.push(P(`not { $${r} has ${s} $${s}_${v4()}; };`,i));else if(Array.isArray(a)){let l=a.map(m=>`$${r} has ${s} ${ie(m)};`),c=Ne(l);c&&$.push(P(c,i));}else $.push(P(`$${r} has ${s} ${ie(a)};`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")if(a===null)$.push(P(`not { (${f.plays}: $${r}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let y=a.map(T=>`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(T)};`),B=Ne(y);B&&$.push(P(B,i));}else $.push(P(`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(a)};`,i));else {let y=`${l.thing}_${v4()}`;if(a===null)$.push(P(`not { $${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let B=a.map(g=>`$${y} isa ${l.thing}, has ${m} ${ie(g)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`),T=Ne(B);T&&$.push(P(T,i));}else $.push(P(`$${y} isa ${l.thing}, has ${m} ${ie(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${v4()}`;if(a===null)$.push(P(`not { $${r} (${c.plays}: ${B}); };`,i));else if(Array.isArray(a)){let T=a.map(Q=>`$${B} isa ${c.thing}, has ${y} ${ie(Q)}; $${r} (${c.plays}: $${B});`),g=Ne(T);g&&$.push(P(g,i));}else $.push(P(`$${B} isa ${c.thing}, has ${y} ${ie(a)}; $${r} (${c.plays}: $${B});`,i));return}}throw new Error(`"${n}" does not have property "${s}"`)}),$.join(`
55
- `)},Ne=t=>{if(t.length>1)return `{ ${t.join(" } or { ")} };`;let[e]=t;return e},ie=t=>typeof t=="string"?`'${t}'`:t instanceof Date?`'${t.toISOString().replace("Z","")}'`:`${t}`,ii=t=>typeof t=="string"?{field:t,desc:!1}:{...t,desc:t.desc??!1},_e=t=>{let{$var:e,$thing:r,schema:n,$sort:o,depth:i}=t,p=G(n,r),d=[],h=[];if(o?.forEach($=>{let s=ii($),a=p.dataFields?.find(l=>l.path===s.field);if(!a)throw new Error(`"${r}" does not have data field "${s.field}"`);let u=`${s.field}_${v4()}`;d.push(P("{",i)),d.push(P(`$${e} has ${a.dbPath} $${u}_1;`,i+1)),d.push(P("not {",i+1)),d.push(P(`$${e} has ${a.dbPath} $${u}_2;`,i+2)),d.push(P(`$${u}_2 < $${u}_1;`,i+2)),d.push(P("};",i+1)),d.push(P(`?${u}_ = $${u}_1;`,i+1)),d.push(P("} or {",i)),d.push(P(`not { $${e} has ${a.dbPath} $${u}_1; };`,i+1)),d.push(P(`?${u}_ = "~";`,i+1)),d.push(P("};",i)),d.push(P(`?${u} = ?${u}_;`,i));let f=s.desc?"desc":"asc";h.push(`?${u} ${f}`);}),d.length!==0)return {match:d.join(""),sort:P(`sort ${h.join(", ")};`,i)}},P=(t,e)=>{let r="";for(let n=0;n<e;n++)r+=" ";return `
56
- ${r}${t}`};var at=t=>{let e=t.dataFields?.map(i=>i.path)||[],r=t.linkFields?.map(i=>i.path)||[],n=Object.keys(t.roles||{})||[];return [...e,...r,...n]},lt=(t,e)=>Object.keys(t||{}).some(n=>{if(!Array.isArray(t[n])){let o=e.idFields?.includes(n),i=e.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique);return o||i}return !1}),ct=(t,e)=>{let r=e.dataFields?.map(p=>({path:p.path,dbPath:p.dbPath}))||[],n=e.linkFields?.map(p=>({path:p.path,dbPath:p.dbPath}))||[],o=Object.keys(e.roles||{}).map(p=>({path:p,dbPath:p}))||[],i=[...r,...n,...o];return Object.entries(t||{}).reduce((p,[d,h])=>{let $=i.find(s=>s.path===d);return p[$?.dbPath||d]=h,p},{})},ze=async t=>{let{rawBqlRequest:e,schema:r}=t;if(Array.isArray(e)){for(let s of e)if(!("$entity"in s)&&!("$relation"in s)&&(!("$thing"in s)||!("$thingType"in s)))throw new Error("No entity specified in query")}else if(!("$entity"in e)&&!("$relation"in e)&&(!("$thing"in e)||!("$thingType"in e)))throw new Error("No entity specified in query");let n=(s,a)=>typeof a=="string"?s.idFields?.includes(a):s.idFields?.includes(a.$path),o=(s,a,u,f,l)=>({$path:a,$dbPath:f,$thingType:"attribute",$as:s.$as||a,$var:a,$fieldType:"data",$excludedFields:s.$excludedFields,$justId:u,$id:s.$id,$filter:s.$filter,$isVirtual:l,$filterProcessed:!0}),i=(s,a,u,f,l)=>{let{target:c,oppositeLinkFieldsPlayedBy:m}=u;return m.map(y=>{let B=c==="role"?y.thingType:"relation",T=c==="role"?y.thing:u.relation,g={[`$${B}`]:T},Q=C(r,g),M=s?.$fields?.filter(A=>n(Q,A)).length===0,L=[];return typeof s!="string"?s.$fields?M?L=[...s.$fields,...Q.idFields]:L=s.$fields:L=at(Q):L=["id"],s.$excludedFields&&(L=L.filter(A=>n(Q,A)?!0:!s.$excludedFields.includes(A.$path))),{$thingType:B,$plays:u.plays,$playedBy:y,$path:y.path,$dbPath:l,$as:s.$as||a,$var:a,$thing:T,$fields:L,$excludedFields:s.$excludedFields,$fieldType:"link",$target:c,$intermediary:y.relation,$justId:f,$id:s.$id,$filter:ct(s.$filter,Q),$idNotIncluded:M,$filterByUnique:lt(s.$filter,Q),$filterProcessed:!0,$sort:s.$sort,$offset:s.$offset,$limit:s.$limit}})},p=(s,a,u,f,l)=>u.playedBy.map(c=>{let{thing:m,thingType:y,relation:B}=c,T={[`$${y}`]:m},g=C(r,T),Q=s?.$fields?.filter(L=>g?.idFields?.includes(L)||g?.idFields?.includes(L.$path)).length===0,M=[];if(typeof s!="string")if(s.$fields)if(Q){let L=g.idFields||[];M=[...s.$fields,...L];}else M=s.$fields;else M=at(g);else M=["id"];return s.$excludedFields&&(M=M.filter(L=>n(g,L)?!0:!s.$excludedFields.includes(L.$path))),{$thingType:y,$path:a,$dbPath:l,$as:s.$as||a,$var:a,$thing:m,$fields:M,$excludedFields:s.$excludedFields,$fieldType:"role",$intermediary:B,$justId:f,$id:s.$id,$filter:ct(s.$filter,g),$idNotIncluded:Q,$filterByUnique:lt(s.$filter,g),$playedBy:c,$filterProcessed:!0,$sort:s.$sort,$offset:s.$offset,$limit:s.$limit}}),d=(s,a)=>{let u=typeof s=="string"?s:s.$path,f=typeof s=="string",l=a.dataFields?.find(y=>y.path===u),c=a.linkFields?.find(y=>y.path===u),m=a.roles?.[u];if(l){let y=l.isVirtual&&l.default;return o(s,u,f,l.dbPath,y)}else {if(c)return i(s,u,c,f,c.dbPath);if(m)return p(s,u,m,f,m.dbPath)}return null},$=(s=>produce(s,a=>traverse(a,u=>{let{value:f,meta:l}=u,c=f;if(isObject(c)){if(c.$id){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},y=C(r,m);if(!y?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=y.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),y?.idFields?.length===1){let[B]=y.idFields;c.$filter={...c.$filter,[B]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let m=C(r,c);if(!m?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=m.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[v]=l.nodePath;let y=C(r,m);if(c.$filter&&(c.$filterByUnique=lt(c.$filter,y),c.$filterProcessed||(c.$filter=ct(c.$filter,y))),c.$fields){c.$fields.filter(g=>y?.idFields?.includes(g)||y?.idFields?.includes(g.$path)).length>0||(c.$fields=[...c.$fields,...Array.isArray(y.idFields)?y.idFields:[]],c.$idNotIncluded=!0);let T=c.$fields?.flatMap(g=>{let Q=d(g,y);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=T;}else {let T=at(y)?.flatMap(g=>{let Q=d(g,y);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=T;}c.$excludedFields&&(c.$fields=c.$fields.filter(B=>n(y,B)?!0:!c.$excludedFields.includes(B.$path)));}}})))(Array.isArray(e)?e:[e]);t.enrichedBqlQuery=$;};var $r=async(t,e)=>{let{dbHandles:r,enrichedBqlQuery:n,tqlRequest:o,config:i}=t;if(!n)throw new Error("BQL request not parsed");if(!o)throw new Error("TQL request not built");let p=new TypeDBOptions;if(p.infer=!0,Array.isArray(o)){let h=await parallel(o.length,o,async $=>{let{session:s}=await Qe(r,i),a=await s.transaction(TransactionType.READ,p);if(!a)throw new Error("Can't create transaction");let f=await a.query.fetch($).collect();return await a.close(),f});e.rawTqlRes=h,e.isBatched=!0;}else {let{session:h}=await Qe(r,i),$=await h.transaction(TransactionType.READ,p);if(!$)throw new Error("Can't create transaction");let a=await $.query.fetch(o).collect();await $.close(),e.rawTqlRes=a;}};var fr=t=>{let e=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=t.match(e),p=t.match(r),d=t.match(n),h=t.match(o);return {as:i?i[1]:null,justId:p?p[1]:null,idNotIncluded:d?d[1]:null,filterByUnique:h?h[1]:null}},di=t=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(p,d,h)=>/^{.*}$/.test(h)?`:${h}`:`:${d}"${h}"`),i=i.replace(/\[([^\]]+)\]/g,(p,d)=>`[${d.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),i})(t);return JSON.parse(r)}catch(e){return console.error(e),{as:[]}}},yr=async(t,e)=>{let{enrichedBqlQuery:r,rawBqlRequest:n,schema:o,config:i}=t,{rawTqlRes:p,isBatched:d}=e;if(r){if(!p)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let h=(c,m)=>{let{$metaData:y}=c,{as:B}=di(y),T=Object.entries(c).filter(([g])=>g!=="type"&&!g.startsWith("$")).map(([g,Q])=>{let M=m.dataFields?.find(D=>D.path===g||D.dbPath===g),L=g==="id",A=Array.isArray(B)?B.find(D=>D[g])?.[g]:g,R;if(M?.cardinality==="ONE"){if(R=Q[0]?Q[0].value:i.query?.returnNulls?null:void 0,M.contentType==="DATE"?R=R&&`${R}Z`:M.contentType==="JSON"&&(R=R&&JSON.parse(R)),L)return [[A,R],["$id",R]].filter(([D,N])=>N!==void 0)}else if(M?.cardinality==="MANY"){if(!isArray(Q))throw new Error("Typedb fetch has changed its format");if(Q.length===0)return i.query?.returnNulls?[[A,null]]:[];M.contentType==="DATE"?R=Q.map(D=>`${D.value}Z`):M.contentType==="JSON"?R=Q.map(D=>D.value&&JSON.parse(D.value)):R=Q.map(D=>D.value);}return [[A,R]].filter(([D,N])=>N!==void 0)}).flat();return Object.fromEntries([...T])},$=c=>c.reduce((m,y)=>{let{$roleFields:B,$metaData:T,$cardinality:g}=y,{as:Q,justId:M,idNotIncluded:L,filterByUnique:A}=fr(T),R=B.map(D=>{let{dataFields:N,currentSchema:x,linkFields:w,roleFields:F,schemaValue:k}=a(D),E=h(N,x);if(M==="T")return E.id;{let b=s(w),S=$(F),_={...E};return L==="true"&&x?.idFields?.forEach(I=>delete _[I]),{..._,...b,...S,...k}}});return R.length>0?m[Q]=g==="MANY"&&A==="false"?R:R[0]:i.query?.returnNulls&&(m[Q]=null),m},{}),s=c=>c.reduce((m,y)=>{let{$linkFields:B,$metaData:T,$cardinality:g}=y,{as:Q,justId:M,idNotIncluded:L,filterByUnique:A}=fr(T),R=B.map(D=>{let{dataFields:N,currentSchema:x,linkFields:w,roleFields:F,schemaValue:k}=a(D),E=h(N,x);if(M==="T")return E.id;{let b=s(w),S=$(F),_={...E};return L==="true"&&x.idFields?.forEach(I=>delete _[I]),{..._,...b,...S,...k}}});return m[Q]=R.length>0?g==="MANY"&&A==="false"?R:R[0]:i.query?.returnNulls?null:void 0,m},{}),a=c=>{let m=Object.keys(c),y=m.find(D=>D.endsWith(".$dataFields"));if(!y)throw new Error("No datafields");let B=c[y],T=y.split(".")[y.split(".").length-2];if(B.$metaData=T,B.length===0)throw new Error("No datafields");let g=B.type,Q={$thing:g.label,$thingType:g.root,[v]:c.queryPath.value},M={[`$${Q.$thingType}`]:Q.$thing},L=C(o,M),A=m.filter(D=>!D.endsWith(".$dataFields")&&L.linkFields?.some(N=>N.path===D.split(".").pop())).map(D=>({$linkFields:c[D],$key:D.split(".").pop(),$metaData:D.split(".")[D.split(".").length-2],$cardinality:L?.linkFields?.find(N=>N.path===D.split(".").pop())?.cardinality})),R=m.filter(D=>!D.endsWith(".$dataFields")&&L.roles?.[D.split(".").pop()]).map(D=>({$roleFields:c[D],$key:D.split(".").pop(),$metaData:D.split(".")[D.split(".").length-2],$cardinality:L.roles[D.split(".").pop()].cardinality}));return {dataFields:B,schemaValue:Q,currentSchema:L,linkFields:A,roleFields:R}},u=c=>c.map(m=>{let{dataFields:y,currentSchema:B,linkFields:T,roleFields:g,schemaValue:Q}=a(m),M=h(y,B),L=s(T),A=$(g),R=n?.$fields?.every(N=>!B?.idFields?.includes(N)&&!B?.idFields?.includes(N.$path));return {...L,...A,...Q,...!i.query?.noMetadata&&n.$id?{$id:Array.isArray(n.$id)?M.id:n.$id}:{},...R?Object.fromEntries(Object.entries(M).filter(([N])=>!B?.idFields?.includes(N))):M}}),l=(c=>{let m=y=>{let B=u(y);return n.$id&&!Array.isArray(n.$id)||r[0].$filterByUnique?B[0]??null:B.length===0?null:B};return d?c.map(m):m(c)})(p);e.bqlRes=l;};var mr=async(t,e)=>{let{schema:r,enrichedBqlQuery:n}=t,{bqlRes:o}=e;if(!o)return;let p=(d=>produce(d,h=>traverse(h,({value:$})=>{if(isObject($)){let s=$;if(!s.$thing)return;if(s.$thing){let a=C(r,s),{virtualFields:u}=a,f=s[v];if(!f)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(n,f),c=l.$fields.map(y=>y.$path),m=l.$excludedFields;u.forEach(y=>{if(m?.includes(y)||c.length>0&&!c.includes(y))return;let B=a.dataFields?.find(T=>T.path===y);if(B?.default){let T=Be({currentThing:s,fieldSchema:B,mandatoryDependencies:!0});s[y]=T;}else if(s[y]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${y}`)}),m&&m.forEach(y=>{if(typeof y!="string")throw new Error("[Internal] ExcludedField is not a string");delete s[y];});}}})))(o);e.bqlRes=p;};var Fr=async(t,e)=>{let{config:r}=t,{bqlRes:n}=e;if(!n)return;let i=(h=>produce(h,$=>traverse($,({value:s})=>{isObject(s);})))(n),d=(h=>produce(h,$=>traverse($,({value:s})=>{if(isObject(s)){let a=s;Object.keys(a).forEach(u=>{a[u]===void 0&&delete a[u];}),Object.getOwnPropertySymbols(a).forEach(u=>{delete a[u];}),r.query?.noMetadata===!0&&Object.keys(a).forEach(u=>{u.startsWith("$")&&delete a[u];});}})))(i);e.bqlRes=d;};var yi=(t,e)=>{for(let r in e){let n=e[r];if(t.query?.returnNulls){if(Array.isArray(n)&&n.length===0){e[r]=null;continue}}else {if(n===null){delete e[r];continue}if(Array.isArray(n)&&n.length===0){delete e[r];continue}}}},br=({config:t,item:e,query:r,schema:n})=>{let o=n[r.$thingType==="entity"?"entities":"relations"][r.$thing];if(yi(t,e),Object.getOwnPropertySymbols(e).forEach(i=>{delete e[i];}),t.query?.noMetadata===!0&&Object.keys(e).forEach(i=>{i.startsWith("$")&&delete e[i];}),r.$idNotIncluded){let i=o.idFields?.[0];delete e[i??"id"];}},wr=async(t,e)=>{let{config:r,enrichedBqlQuery:n,schema:o}=t,{bqlRes:i}=e;if(!i)return;if(n.length>1)throw new Error("batch query unimplemented");let[d]=n,h=produce(i,$=>{if(Array.isArray($))for(let s of $)br({config:r,item:s,query:d,schema:o});else br({config:r,item:$,query:d,schema:o});});e.bqlRes=h;};var Lr=(t,e,r,n=[])=>{let o=Object.values(t[e]).filter(i=>i.extends===r).map(i=>i.name);return o.length===0?[...n]:o.reduce((i,p)=>[...i,p,...Lr(t,e,p,i)],n)},gi=t=>t.$path==="id"?`meta::id(${t.$path}) as id`:`${t.$path}`,Bi=(t,e)=>r=>{if(e.$thingType==="entity")return r;let o=t.relations[e.$thing];return Object.entries(o.roles).reduce((i,[p,d])=>{let h=i[p];return d.cardinality==="ONE"&&Array.isArray(h)?{...i,[p]:h[0]}:i},r)},Qr=(t,e)=>{let r=e.$fields.filter($=>$.$thingType==="attribute"),n=e.$fields.filter($=>$.$thingType==="entity"),i=e.$fields.filter($=>$.$thingType==="relation").map($=>`(SELECT VALUE meta::id(id) as id FROM <-${$.$thing}_${$.$plays}<-${$.$thing}) as \`${$.$as}\``),p=n.map($=>{let s=pascal($.$playedBy.relation);return e.$thingType==="relation"?`(SELECT VALUE meta::id(id) as id FROM ->${s}_${$.$playedBy.plays}.out) as ${$.$as}`:`(SELECT VALUE meta::id(id) as id FROM <-${s}_${$.$playedBy.path}<-${s}->${s}_${$.$playedBy.plays}.out) as ${$.$as}`}),d=e.$filter?`WHERE ${Object.entries(e.$filter).map(([$,s])=>`${$} = ${e.$thing}:\`${s}\``).join(",")}`:"";return `SELECT
57
- ${[...r.map(gi),...p,...i].join(",")}
58
- FROM ${t}
59
- ${d}
60
- FETCH ${n.map($=>$.$path).join(",")}
61
- PARALLEL`},Ei=async(t,e)=>{console.log(`
62
-
63
- buildSurrealDbQuery
64
- `,JSON.stringify(t));let{dbHandles:r,enrichedBqlQuery:n,schema:o}=t;if(!n)throw new Error("BQL request not parsed");if(!r.surrealDB)throw new Error("missing SurrealDB in dbHandles");let i=t.config.dbConnectors.find($=>$.provider==="surrealDB");if(!i)throw new Error("missing SurrealDB config");let p=r.surrealDB.get(i.id);if(!p)throw new Error(`missing SurrealDB client with id of ${i.id}`);let{client:d}=p,h=await Promise.all(t.enrichedBqlQuery.map(async $=>{let s;if($.$thingType==="relation"){let a=pascal($.$thing),u=Qr(a,$);s=(await d.query(u)).map(l=>({$id:l.id,$thing:trainCase(a),$thingType:"relation",...l,id:l.id,[v]:n[0][v]}));}else {let a=[$.$thing,...Lr(t.schema,"entities",$.$thing)];s=(await Promise.all(a.map(async f=>(await d.query(Qr(f,$))).map(c=>({$id:dash(c.id),$thing:f,$thingType:"entity",...c,id:dash(c.id),[v]:n[0][v]}))))).flat();}if(!s)throw new Error("empty query result");return s.map(Bi(o,$))}));if(t.enrichedBqlQuery.length>1)throw new Error("batch query unimplemented");e.bqlRes=t.enrichedBqlQuery[0]?.$filter?.id?h[0][0]:h[0];},kr={query:[ze,Ei,wr],mutation:[]};var Fi={query:[ze,pr,$r,yr,mr,Fr]},dt=async(t,e,r,n=!0)=>{for(let o of t){let i=await o(e,r);if(i&&Array.isArray(i))for(let p of i)await dt(p.pipeline,p.req,p.res,!1);}return n&&e.config.query?.debugger===!0&&typeof r.bqlRes=="object"?{...r.bqlRes,$debugger:{tqlRequest:e.tqlRequest}}:r.bqlRes},Sr=(t,e,r,n)=>{if(n.typeDB&&n.typeDB.size>0)return dt(Fi.query,{config:e,schema:r,rawBqlRequest:t,dbHandles:n},{});if(n.surrealDB&&n.surrealDB.size>0)return dt(kr.query,{config:e,schema:r,rawBqlRequest:t,dbHandles:n},{});throw new Error("no pipeline defined")};var qr="___",bi=Symbol.for("grandChildOfCreate"),Rr=async(t,e,r,n)=>{let o=(w,F)=>Object.keys(w).filter(k=>!k.startsWith("$")&&w[k]!==void 0?F?!C(e,w).dataFields?.find(b=>b.path===k):!0:!1);if(!t)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let i=[];if(traverse(t,({parent:w,key:F,value:k})=>{w&&F&&!F.includes("$")&&isObject(w)?(Array.isArray(w[F])?w[F]:[w[F]]).forEach(b=>{if(isObject(b)){if(w.$op!=="create")i.includes(b.$op)||i.push(b.$op);else if(b.$op==="delete"||b.$op==="unlink")throw new Error(`Cannot ${b.$op} under a create`)}}):!w&&isObject(k)&&(i.includes(k.$op)||i.push(k.$op));}),!i.includes("delete")&&!i.includes("unlink")&&!i.includes("replace")&&!i.includes("update")&&!i.includes("link"))return;let d=(w=>{let F=(k,E)=>{let b=[],S={},_=["$op","$bzId","$parentKey"],I=["$relation","$entity","$id",..._];for(let O in k)if(!_.includes(O)&&!(I.includes(O)&&!E))if(!O.includes("$")&&(isObject(k[O])||Array.isArray(k[O]))){let H=k[O];Array.isArray(H)&&H.length>0?H.forEach(oe=>{b.push({$path:O,...F(oe)});}):b.push({$path:O,...F(H)});}else S[O]=k[O];return {...S,$fields:b}};return w.map(k=>F(k,!0))})(Array.isArray(t)?t:[t]),h=await Sr(d,r,e,n),$=(w,F)=>{let k=w.$id||w.id||w.$bzId;if(w.$objectPath){let{$objectPath:E}=w,b=E?.beforePath||"root",S=Array.isArray(E.ids)?`[${E.ids}]`:E.ids;return {beforePath:`${b}.${S}___${E.key}`,ids:k,key:F}}else return {beforePath:"root",ids:k,key:F}},s=(w,F)=>{let k=w?.beforePath||"root",E=F||(Array.isArray(w?.ids)?`[${w?.ids}]`:w?.ids);return `${k}.${E}___${w?.key}`},a=w=>{if(w.includes("[")&&w.includes("]")){let[F,k,E]=w.split(/[[\]]/);return k.split(",").map(S=>`${F}${S}${E}`)}else return [w]},u={};(w=>produce(w,F=>traverse(F,k=>{let{key:E,parent:b}=k;if(b&&E&&b.$id&&!E.includes("$")){let S=$(b,E),_=s(S);if(Array.isArray(b[E])){let I=[];b[E].forEach(O=>{isObject(O)?(O.$objectPath=S,I.push(O.$id.toString())):O&&I.push(O.toString());}),u[_]={$objectPath:S,$ids:I};}else {let I=b[E];isObject(I)?(u[_]={$objectPath:S,$ids:[I.$id.toString()]},I.$objectPath=S):I&&(u[_]={$objectPath:S,$ids:[I.toString()]});}}})))(h||{});let l=w=>produce(w,F=>traverse(F,k=>{let{key:E,value:b,parent:S}=k;S&&E&&!E.includes("$")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(S)&&(Array.isArray(S[E])?S[E].forEach(_=>{typeof _!="string"&&(_.$objectPath=$(S,E),_.$parentIsCreate=S.$op==="create",_[bi]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")]);}):isObject(S[E])&&(S[E].$parentIsCreate=S.$op==="create",S[E][Symbol.for("grandChildOfCreate")]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")],S[E].$objectPath=$(S,E)));})),c=l(t),m=w=>{let F=[];return w.forEach(E=>{if(!E.$id&&!E.id&&!E.$tempId){let b=s(E.$objectPath),S=u[b];S?S?.$ids.forEach(_=>{let I={...E,$id:_,$bzId:`T4_${v4()}`};F.push(I);}):F.push(E);}else F.push(E);}),F.map(E=>{let b={...E};return o(b,!0).forEach(S=>{let _=Array.isArray(b[S])?b[S]:[b[S]],I=m(_);b[S]=I;}),b})},y=m(Array.isArray(c)?c:[c]),B=l(y),g=(w=>{let F=k=>{let E=Y=>{let ee=[],V=[],z=[];return Y.forEach(J=>{let ae=o(J,!0);if(ae.length>0){let j=!1;ae.forEach(W=>{(Array.isArray(J[W])?J[W]:[J[W]]).filter(re=>!re.$id&&!re.id&&typeof J=="object").length&&(j=!0);}),j?ee.push(J):V.push(J);}else z.push({...J,$bzId:J.$tempId||`T_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:V,otherOps:z}},{operationWithMultiples:b,operationWithoutMultiples:S,otherOps:_}=E(k),I=Y=>{let V=(()=>{let W={};for(let ne in Y){let te=C(e,Y);!ne.startsWith("$")&&te.dataFields?.find(re=>re.path===ne)&&(W[ne]=Y[ne]);}return W})(),z=Object.keys(Y),J=o(Y,!0),ae=[],j=(W,ne)=>{if(W===J.length){let re={...ne};z.forEach(ce=>{ce.startsWith("$")&&(re[ce]=Y[ce]);}),ae.push({...re,...V});return}let te={...ne,[J[W]]:Y[J[W]],...ye(ne),...V};j(W+1,te),j(W+1,ne);};return j(0,{...ye(Y)}),ae},O=[];return b.forEach(Y=>{let ee=I(Y),V=[];ee.forEach(z=>{let J=o(z,!0);if(z.$op==="create")V.push(z);else if(z.$id){let ae=s(z.$objectPath),j=[];if(J.forEach(W=>{let ne=`${ae.includes("undefined")?"root":ae}.${z.$id}${qr}${W}`,te=u[ne];z[W].filter(ce=>ce.$op==="unlink"||ce.$op==="delete"||ce.$op==="update").length>0?te&&j.push({key:W,ids:te.$ids}):j.push({key:W,ids:[""]});}),j.length===J.length&&!V.find(W=>W.$id===z.$id))V.push(z);else {let W={...z,$bzId:z.$tempId||`T4_${v4()}`};J.forEach(te=>{let re=z[te].filter(ce=>ce.$id);re.length>0?W[te]=re:W[te]=void 0;}),o(W,!0).length>0&&V.push(W);}}else if(z.$objectPath){let ae=s(z.$objectPath),j=u[ae]?.$ids||[];j.forEach(W=>{let ne=[];J.forEach(te=>{let re=`${ae}.${W}${qr}${te}`,ce=u[re];ce&&ne.push({key:te,ids:ce.$ids});}),J.length===0?j.filter(re=>!V.find(ce=>ce.$id===re)).forEach(re=>{V.push({...z,$id:re,$bzId:z.$tempId||`T_${v4()}`});}):ne.length===J.length&&!V.find(te=>te.$id===W)&&V.push({...z,$id:W,$bzId:z.$tempId||`T_${v4()}`});});}else V.push(z);}),V.forEach(z=>{O.push(z);});}),[...O,...S,..._].filter(Y=>o(Y).length>0?!0:Y.$op!=="update").map(Y=>{let ee={...Y};return o(ee,!0).forEach(V=>{let z=Array.isArray(ee[V])?ee[V]:[ee[V]],J=F(z);ee[V]=J;}),ee})};return F(w)})(Array.isArray(B)?B:[B]),Q=w=>w.map(F=>{let k=o(F,!0),E={...F};return k.forEach(b=>{let S=Array.isArray(F[b])?F[b]:[F[b]],_=[],I=[],O=[],H={},oe=tt(e,F,b);S.filter(j=>j).forEach(j=>{j.$op==="replace"&&j.$id?(H=j,Array.isArray(j.$id)?I=[...I,...j.$id]:I.push(j.$id)):j.$op==="create"&&oe==="ONE"&&j.id?(H=j,Array.isArray(j.id)?O=[...I,...j.id]:O.push(j.id)):_.push(j);});let Re=s(H.$objectPath),ee=a(Re).map(j=>u[j]),V=[];ee.filter(j=>j!=null).forEach(j=>{V=[...V,...j.$ids];});let z=V.filter(j=>!I.includes(j)),J=I.filter(j=>!V.includes(j)),ae=ye(H);z.length>0&&_.push({...H,$op:"unlink",$id:z,$bzId:H.$tempId||`T4_${v4()}`,id:void 0,...ae}),J.length>0&&J.forEach(j=>{_.push({...H,$op:"link",$id:j,$bzId:H.$tempId||`T5_${v4()}`,...ae});}),O.length>0&&O.forEach(j=>{_.push({...H,$op:"create",id:j,$bzId:H.$tempId||`T6_${v4()}`,...ae});}),E[b]=Q(_);}),E}),M=l(Q(l(g)));(w=>produce(w,F=>traverse(F,k=>{let{key:E,value:b,parent:S}=k;E&&S&&!E?.includes("$")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(S)&&(Array.isArray(b)?b:[b]).forEach(I=>{let O=u[s(I.$objectPath)],H=(Y,ee)=>Y.every(V=>ee.includes(V)),oe=I.$id?Array.isArray(I.$id)?H(I.$id,O?O.$ids:[]):O?.$ids.includes(I.$id):O,Re=tt(e,S,I.$objectPath.key);if(I.$op==="link"&&oe&&Re==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${s(I.$objectPath)}" because it is already occupied.`);if(I.$op)switch(I.$op){case"delete":if(!oe&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${I.$id}" because it is not linked to $id:"${S.$id}"`);break;case"update":if(!oe&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${I.$id}" because it is not linked to $id:"${S.$id}"`);break;case"unlink":if(!oe&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${I.$id}" because it is not linked to $id:"${S.$id}"`);break;case"link":if(oe)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${I.$id}" because it is already linked to $id:"${S.$id}"`);break;}});})))(M);let R=(w=>produce(w,F=>traverse(F,k=>{let{value:E,meta:b}=k;isObject(E)&&(E[Symbol.for("path")]=b.nodePath,delete E.$objectPath,delete E.$parentIsCreate);})))(M);return [...Array.isArray(R)?R:[R]].sort((w,F)=>w.$op==="create"&&F.$op!=="create"?-1:w.$op!=="create"&&F.$op==="create"?1:0)};function X(t){return {enumerable:!0,value:t}}function Ar(t){return {enumerable:!0,writable:!0,value:t}}var ke={},wi=()=>!0,Dr=()=>({}),Ir=t=>t,Ti=(t,e,r,n)=>t.apply(r,n)&&e.apply(r,n),Qi=(t,e,r,[n,o])=>e.call(r,t.call(r,n,o),o),Fe=(t,e)=>Object.freeze(Object.create(t,e));function Pr(t,e,r){return t.reduce((n,o)=>function(...i){return r(n,o,this,i)},e)}function Cr(t){return Fe(this,{fn:X(t)})}var Or={},U=Cr.bind(Or);var xr={},jr=Cr.bind(xr);function We(t,e){return e.filter(r=>t.isPrototypeOf(r))}function Nr(t,e,...r){let n=Pr(We(xr,r).map(i=>i.fn),wi,Ti),o=Pr(We(Or,r).map(i=>i.fn),Ir,Qi);return Fe(this,{from:X(t),to:X(e),guards:X(n),reducers:X(o)})}var _r={},zr={},K=Nr.bind(_r);Nr.bind(zr,null);function Mi(t,e,r){return ut(e,t,r,this.immediates)||t}function Vr(t){let e=new Map;for(let r of t)e.has(r.from)||e.set(r.from,[]),e.get(r.from).push(r);return e}var Li={enter:Ir};function de(...t){let e=We(_r,t),r=We(zr,t),n={final:X(t.length===0),transitions:X(Vr(e))};return r.length&&(n.immediates=X(r),n.enter=X(Mi)),Fe(Li,n)}var ki={enter(t,e,r){let n=this.fn.call(e,e.context,r);return pt.isPrototypeOf(n)?Fe(Wr,{machine:X(n),transitions:X(this.transitions)}).enter(t,e,r):(n.then(o=>e.send({type:"done",data:o})).catch(o=>e.send({type:"error",error:o})),t)}},Wr={enter(t,e,r){if(e.child=fe(this.machine,n=>{e.onChange(n),e.child==n&&n.machine.state.value.final&&(delete e.child,e.send({type:"done",data:n.context}));},e.context,r),e.child.machine.state.value.final){let n=e.child.context;return delete e.child,ut(e,t,{type:"done",data:n},this.transitions.get("done"))}return t}};function Z(t,...e){let r=X(Vr(e));return pt.isPrototypeOf(t)?Fe(Wr,{machine:X(t),transitions:r}):Fe(ki,{fn:X(t),transitions:r})}var pt={get state(){return {name:this.current,value:this.states[this.current]}}};function be(t,e,r=Dr){return typeof t!="string"&&(r=e||Dr,e=t,t=Object.keys(e)[0]),ke._create&&ke._create(t,e),Fe(pt,{context:X(r),current:X(t),states:X(e)})}function ut(t,e,r,n){let{context:o}=t;for(let{to:i,guards:p,reducers:d}of n)if(p(o,r)){t.context=d.call(t,o,r);let h=e.original||e,$=Fe(h,{current:X(i),original:{value:h}});ke._onEnter&&ke._onEnter(e,i,t.context,o,r);let s=$.state.value;return t.machine=$,t.onChange(t),s.enter($,t,r)}}function Si(t,e){let r=e.type||e,{machine:n}=t,{value:o,name:i}=n.state;return o.transitions.has(r)?ut(t,n,e,o.transitions.get(r))||n:(ke._send&&ke._send(r,i),n)}var qi={send(t){Si(this,t);}};function fe(t,e,r,n){let o=Object.create(qi,{machine:Ar(t),context:Ar(t.context(r,n)),onChange:X(e)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,n),o}var Hr=(t,e)=>produce(t,n=>He(e,n)),He=(t,e,r)=>{if(typeof e=="string")return;if(Array.isArray(e)){e.forEach(o=>He(t,o,r));return}let n=G(t,r||e.$entity||e.$relation||e.$thing);Object.entries(e).forEach(([o])=>{o.startsWith("$")||Ai(t,e,o,n);});},Ai=(t,e,r,n)=>{let o=e[r];if(!o)return;let i=n.dataFields?.find(d=>d.path===r);if(i){i.contentType==="JSON"&&o!=null&&(e[r]=JSON.stringify(o));return}let p=n.linkFields?.find(d=>d.path===r);if(p){let d=p.oppositeLinkFieldsPlayedBy[0]?.thing;He(t,o,d);return}if(n.thingType==="relation"){let d=n.roles[r],[h]=d.playedBy||[];if(!h)throw new Error(`Role ${d.name} in ${n} is not played by anything`);He(t,o,h.thing);}};var vr=de,ve=(t,e)=>e.data?{...t,bql:{...t.bql,current:e.data}}:t,Di=(t,e)=>({...t,bql:{...t.bql,res:e.data}}),Pi=(t,e)=>({...t,bql:{...t.bql,things:e.data.mergedThings,edges:e.data.mergedEdges}}),Ii=(t,e)=>({...t,typeDB:{...t.typeDB,tqlMutation:e.data}}),Ci=(t,e)=>({...t,typeDB:{...t.typeDB,tqlRes:e.data}}),Oi=async t=>Object.keys(t.bql.current).length?it(t.bql.current,t.schema,t.config):it(t.bql.raw,t.schema,t.config),xi=async t=>Rr(t.bql.current,t.schema,t.config,t.handles),ji=async t=>cr(t.bql.current,t.schema),Ni=async t=>dr(t.bql.things,t.bql.edges,t.schema),_i=async t=>nr(t.typeDB.tqlMutation,t.handles,t.config),zi=async t=>ir(t.typeDB.tqlRes,t.bql.things,t.bql.edges,t.schema,t.config),Vi=()=>!0,Me=K("error","error",U((t,e)=>({...t,error:e.error}))),Wi=be("stringify",{stringify:Z(async t=>Hr(t.bql.raw,t.schema),K("done","enrich",U(ve)),Me),enrich:Z(Oi,K("done","preQuery",jr(Vi),U(ve)),K("done","parseBQL",U(ve)),Me),preQuery:Z(xi,K("done","parseBQL",U(ve)),Me),parseBQL:Z(ji,K("done","buildMutation",U(Pi)),Me),buildMutation:Z(Ni,K("done","runMutation",U(Ii)),Me),runMutation:Z(_i,K("done","parseMutation",U(Ci)),Me),parseMutation:Z(zi,K("done","success",U(Di)),Me),success:vr(),error:vr()},t=>t),Hi=async t=>new Promise((e,r)=>{fe(Wi,n=>{n.machine.state.name==="success"&&e(n.context),n.machine.state.name==="error"&&r(n.context);},t);}),Ur=async(t,e,r,n)=>Hi({bql:{raw:t,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:e,config:r,handles:n,depthLevel:0,error:null});var Yr=(t,e)=>{if(!e)return;let r=vi(e);return Ui(r,t.query?.noMetadata??!1)},vi=t=>produce(t,e=>traverse(e,({value:r})=>{isObject(r);})),Ui=(t,e)=>produce(t,r=>traverse(r,({value:n})=>{if(isObject(n)){let o=n;Object.keys(o).forEach(i=>{o[i]===void 0&&delete o[i];}),Object.getOwnPropertySymbols(o).forEach(i=>{delete o[i];}),e===!0&&Object.keys(o).forEach(i=>{i.startsWith("$")&&delete o[i];});}}));var tn=(t,e)=>{for(let o of t)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(t)?t:[t];return produce(r,o=>traverse(o,i=>{let{value:p,meta:d}=i,h=p;if(isObject(h)){if(h.$id){let $=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},s=C(e,$);if(!s?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=s.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),s?.idFields?.length===1){let[a]=s.idFields;h.$filter={...h.$filter,[a]:h.$id},delete h.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let $=C(e,h);if(!$?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=$.name;}if(h.$entity?(h.$thing=h.$entity,h.$thingType="entity",delete h.$entity):h.$relation&&(h.$thing=h.$relation,h.$thingType="relation",delete h.$relation),isObject(h)&&"$thing"in h){let $=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[v]=d.nodePath;let s=C(e,$);if(h.$filter&&(h.$filterByUnique=$t(h.$filter,s),h.$filterProcessed||(h.$filter=h.$filter&&ft(h.$filter,s))),h.$fields){h.$fields.some(f=>s?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(s.idFields)?s.idFields:[]],h.$idNotIncluded=!0);let u=h.$fields?.flatMap(f=>{let l=en(f,s,e);return Array.isArray(l)?l:[l]}).filter(Boolean);h.$fields=u;}else {let u=ht(s)?.flatMap(f=>{let l=en(f,s,e);return Array.isArray(l)?l:[l]}).filter(Boolean);h.$fields=u;}h.$excludedFields&&(h.$fields=h.$fields.filter(a=>Ue(s,a)?!0:!h.$excludedFields.includes(a.$path)));}}}))},ht=t=>{let e=t.dataFields?.map(i=>i.path)||[],r=t.linkFields?.map(i=>i.path)||[],n=Object.keys(t.roles||{})||[];return [...e,...r,...n]},$t=(t,e)=>Object.keys(t||{}).some(n=>{if(!Array.isArray(t[n])){let o=e.idFields?.includes(n),i=e.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique);return o||i}return !1}),ft=(t,e)=>{let r={};if(e.dataFields?.forEach(p=>{p.path!==p.dbPath&&(r[p.path]=p.dbPath);}),Object.keys(r).length===0)return t;let{$not:n,...o}=t,i=Xr(o,r);return n&&(i.$not=Xr(n,r)),i},Xr=(t,e)=>{let r={};return Object.entries(t).forEach(([n,o])=>{let i=e[n]||n;r[i]=o;}),r},Ue=(t,e)=>typeof e=="string"?t.idFields?.includes(e):t.idFields?.includes(e.$path),Zi=t=>{let{field:e,fieldStr:r,$justId:n,dbPath:o,isVirtual:i}=t;return {$path:r,$dbPath:o,$thingType:"attribute",$as:e.$as||r,$var:r,$fieldType:"data",$justId:n,$id:e.$id,$isVirtual:i}},Yi=t=>{let{field:e,fieldStr:r,linkField:n,$justId:o,dbPath:i,schema:p}=t,{target:d,oppositeLinkFieldsPlayedBy:h}=n;return h.map($=>{let s=d==="role"?$.thingType:"relation",a=d==="role"?$.thing:n.relation,u={[`$${s}`]:a},f=C(p,u),l=e?.$fields?.filter(m=>Ue(f,m)).length===0,c=[];if(typeof e!="string")if(e.$fields)if(l){let m=f.idFields||[];c=[...e.$fields,...m];}else c=e.$fields;else c=ht(f);else c=["id"];return e.$excludedFields&&(c=c.filter(m=>Ue(f,m)?!0:!e.$excludedFields.includes(m.$path))),{$thingType:s,$plays:n.plays,$playedBy:$,$path:$.path,$dbPath:i,$as:e.$as||r,$var:r,$thing:a,$fields:c,$excludedFields:e.$excludedFields,$fieldType:"link",$target:d,$intermediary:$.relation,$justId:o,$id:e.$id,$filter:e.$filter&&ft(e.$filter,f),$idNotIncluded:l,$filterByUnique:$t(e.$filter,f),$filterProcessed:!0,$sort:e.$sort,$offset:e.$offset,$limit:e.$limit}})},Gi=t=>{let{field:e,fieldStr:r,roleField:n,$justId:o,dbPath:i,schema:p}=t;return n.playedBy.map(d=>{let{thing:h,thingType:$,relation:s}=d,a={[`$${$}`]:h},u=C(p,a),f=e?.$fields?.filter(c=>u?.idFields?.includes(c)||u?.idFields?.includes(c.$path)).length===0,l=[];if(typeof e!="string")if(e.$fields)if(f){let c=u.idFields||[];l=[...e.$fields,...c];}else l=e.$fields;else l=ht(u);else l=["id"];return e.$excludedFields&&(l=l.filter(c=>Ue(u,c)?!0:!e.$excludedFields.includes(c.$path))),{$thingType:$,$path:r,$dbPath:i,$as:e.$as||r,$var:r,$thing:h,$fields:l,$excludedFields:e.$excludedFields,$fieldType:"role",$intermediary:s,$justId:o,$id:e.$id,$filter:e.$filter&&ft(e.$filter,u),$idNotIncluded:f,$filterByUnique:$t(e.$filter,u),$playedBy:d,$filterProcessed:!0,$sort:e.$sort,$offset:e.$offset,$limit:e.$limit}})},en=(t,e,r)=>{let n=typeof t=="string"?t:t.$path,o=typeof t=="string",i=e.dataFields?.find(h=>h.path===n),p=e.linkFields?.find(h=>h.path===n),d=e.roles?.[n];if(i){let h=!!i.isVirtual&&!!i.default;return Zi({field:t,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:h})}else {if(p)return Yi({field:t,fieldStr:n,linkField:p,$justId:o,dbPath:p.path,schema:r});if(d)return Gi({field:t,fieldStr:n,roleField:d,$justId:o,dbPath:n,schema:r})}return null};var rn=async(t,e,r)=>r?(i=>produce(i,p=>traverse(p,({value:d})=>{if(isObject(d)){let h=d;if(!h.$thing)return;if(h.$thing){let $=C(t,h),{virtualFields:s}=$,a=h[v];if(!a)throw new Error("[Internal] QueryPath is missing");let u=getNodeByPath(e,a),f=u.$fields.map(c=>c.$path),l=u.$excludedFields;s.forEach(c=>{if(l?.includes(c)||f.length>0&&!f.includes(c))return;let m=$.dataFields?.find(y=>y.path===c);if(m?.default){let y=Be({currentThing:h,fieldSchema:m,mandatoryDependencies:!0});h[c]=y;}else if(h[c]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${c}`)}),l&&l.forEach(c=>{if(typeof c!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[c];});}}})))(r):void 0;var sn=t=>{let{queries:e,schema:r}=t;return e.map(n=>ns({query:n,schema:r}))},ns=t=>{let{query:e,schema:r}=t;if(e.$fields.length===0)return null;let n=[];n.push("SELECT");let o=yt({queries:e.$fields,level:1,schema:r});o&&n.push(o);let i=e.$filter&&on(e.$filter,0)||[];return n.push(...i),n.push(`FROM ${e.$thing}`),n.join(`
65
- `)},yt=t=>{let{queries:e,schema:r,level:n}=t,o=[];return e.forEach(i=>{let p=is({query:i,level:n,schema:r});p&&o.push(p);}),o.length===0?null:o.join(`,
66
- `)},is=t=>{let{query:e,schema:r,level:n}=t;return e.$fieldType==="data"?ss({query:e,level:n}):e.$fieldType==="link"?os({query:e,level:n,schema:r}):e.$fieldType==="role"?as({query:e,level:n,schema:r}):null},ss=t=>{let{query:e,level:r}=t;return e.$isVirtual?null:e.$path==="id"?q(`meta::id(\`${e.$path}\`) AS ${e.$as}`,r):e.$path===e.$as?q(`\`${e.$path}\``,r):q(`\`${e.$path}\` AS \`${e.$as}\``,r)},os=t=>{let{query:e,schema:r,level:n}=t;if(e.$fields.length===0)return null;let o=[];o.push(q("(",n));let i=n+1;o.push(q("SELECT",i));let p=i+1,d=yt({queries:e.$fields,level:p,schema:r});d&&o.push(d);let h=[e.$playedBy.thing,...an(r,e.$playedBy.thingType,e.$playedBy.thing)],$;return e.$target==="relation"?$=h.map(s=>`<-\`${e.$playedBy.thing}_${e.$plays}\`<-\`${s}\``).join(", "):$=h.map(s=>`<-\`${e.$playedBy.relation}_${e.$plays}\`<-\`${e.$playedBy.relation}\`->\`${e.$playedBy.relation}_${e.$playedBy.plays}\`->\`${s}\``).join(", "),o.push(q(`FROM ${$}`,i)),o.push(q(`) AS \`${e.$as}\``,n)),o.join(`
67
- `)},as=t=>{let{query:e,schema:r,level:n}=t;if(e.$fields.length===0)return null;let o=[];o.push(q("(",n));let i=n+1;o.push(q("SELECT",i));let p=i+1,d=yt({queries:e.$fields,level:p,schema:r});d&&o.push(d);let $=[e.$playedBy.thing,...an(r,e.$thingType,e.$thing)].map(s=>`->\`${e.$playedBy.relation}_${e.$playedBy.plays}\`->\`${s}\``).join(", ");return o.push(q(`FROM ${$}`,i)),e.$filter&&o.push(...on(e.$filter,i)),o.push(q(`) AS \`${e.$as}\``,n)),o.join(`
68
- `)},on=(t,e)=>{let r=[],{$not:n,...o}=t,i=e+1;Object.entries(o).forEach(([h,$])=>{r.push(q(`${h}=${JSON.stringify($)}`,i));}),n&&Object.entries(n).forEach(([h,$])=>{r.push(`${h}!=${JSON.stringify($)}`);});let[p,...d]=r;return p?[q("WHERE (",e),q(p,i),...d.map(h=>q(`AND ${h}`,i)),q(")",e)]:r},an=(t,e,r)=>{let n=nn(t,e,r),o=0;for(;n[o];)n.push(...nn(t,e,n[o])),o++;return n},nn=(t,e,r)=>Object.values(e==="entity"?t.entities:t.relations).filter(o=>o.extends===r).map(o=>o.name);var ln=async t=>{let{client:e,queries:r}=t;return await Promise.all(r.map(n=>e.query(n)))};var cn=t=>{let{res:e,queries:r}=t;return e.map((n,o)=>dn(r[o],n))},dn=(t,e)=>e.map(r=>pn(t,r)),pn=(t,e)=>{let r={};return t.$fields.forEach(n=>{let o=n.$as,i=e[o];n.$path==="id"&&t.$idNotIncluded||(r[o]=ls(n,i));}),r},ls=(t,e)=>t.$fieldType==="data"?e??null:t.$justId?t.$filterByUnique?e[0]?.id??null:e?.map(r=>r.id)??[]:t.$filterByUnique?pn(t,e[0]):dn(t,e);var mt=K("error","error",U((t,e)=>({...t,error:e.error}))),cs=be("build",{build:Z(async t=>sn({queries:t.bql.queries,schema:t.schema}),K("done","run",U((t,e)=>({...t,surql:{...t.surql,queries:e.data}}))),mt),run:Z(async t=>ln({client:t.client,queries:le(t.surql.queries)}),K("done","parse",U((t,e)=>({...t,surql:{...t.surql,res:e.data}}))),mt),parse:Z(async t=>cn({res:le(t.surql.res),queries:t.bql.queries,schema:t.schema,config:t.config}),K("done","success",U((t,e)=>({...t,bql:{...t.bql,res:e.data}}))),mt),success:de(),error:de()},t=>t),ds=async t=>new Promise((e,r)=>{fe(cs,n=>{n.machine.state.name==="success"&&e(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},t);}),un=async(t,e,r,n)=>ds({bql:{queries:t},surql:{},schema:e,config:r,client:n,error:null});var gt="___",hn=async t=>{let{queries:e,schema:r}=t;return e.map(n=>ps({query:n,schema:r}))},ps=t=>{let{query:e,schema:r}=t,{$path:n,$thing:o,$filter:i,$fields:p,$sort:d,$offset:h,$limit:$}=e;if(!n)throw new Error("Path is not defined");let s=[],a=e[v];if(s.push("match"),s.push(`$${n} isa ${o};`),i){let l=bt({$filter:i,$var:n,$thing:o,schema:r,depth:0});s.push(`
69
- ${l}`);}let u=wt({schema:r,$thing:o,$var:n,$sort:d,depth:0});u&&s.push(u.match);let f=`M_${v4()}`;if(s.push(`?queryPath${f} = "${a}";`),s.push("fetch"),s.push(`?queryPath${f} as "queryPath";`),p){let l=p.filter(y=>y.$fieldType==="data");l&&l.length>0&&s.push(...Bt(l,n,0));let c=p.filter(y=>y.$fieldType==="link");c&&c.length>0&&s.push(...Ft(c,n,n,0,r));let m=p.filter(y=>y.$fieldType==="role");m&&m.length>0&&s.push(...Et(m,n,n,0,r));}return u&&s.push(u.sort),typeof h=="number"&&s.push(`
70
- offset ${h};`),typeof $=="number"&&s.push(`
71
- limit ${$};`),s.join(`
72
- `)},Bt=(t,e,r)=>{let n=[],o=[];for(let $=0;$<t.length;$++)t[$].$isVirtual||n.push(t[$].$dbPath),o.push(`{${t[$].$dbPath}:${t[$].$as}}`);let i=n.join(", "),d=`$metadata:{as:[${o.join(",")}]}`;return [q(`$${e} as "${e}.${d}.$dataFields": ${i};`,r)]},Et=(t,e,r,n,o)=>{let i=n+1,p=[];for(let d of t){let{$fields:h,$as:$,$justId:s,$idNotIncluded:a,$filterByUnique:u,$thing:f,$sort:l,$offset:c,$limit:m}=d,y=d[v],B=`$metadata:{as:${$},justId:${s?"T":"F"},idNotIncluded:${a},filterByUnique:${u}}`;p.push(q(`"${r}.${B}.${d.$var}": {`,n)),p.push(q("match",i));let T=`${e}${gt}${d.$var}`;p.push(q(`$${T} isa ${d.$thing};`,i)),p.push(q(`$${e} (${d.$var}: $${e}${gt}${d.$var}) isa ${d.$intermediary};`,i)),d.$filter&&p.push(bt({$filter:d.$filter,$var:T,$thing:d.$thing,schema:o,depth:i}));let g=wt({schema:o,$thing:f,$var:T,$sort:l,depth:i});if(g&&p.push(g.match),h){let Q=`M_${v4()}`;p.push(q(`
73
- ?queryPath${Q} = "${y}";`,i)),p.push(q("fetch",i)),p.push(q(`?queryPath${Q} as "queryPath";`,i));let M=h?.filter(R=>R.$fieldType==="data");M&&M.length>0&&p.push(...Bt(M,T,i));let L=h?.filter(R=>R.$fieldType==="link");L&&L.length>0&&p.push(...Ft(L,T,`${e}.${d.$var}`,i,o));let A=h?.filter(R=>R.$fieldType==="role");A&&A.length>0&&p.push(...Et(A,T,`${e}.${d.$var}`,i,o));}g&&p.push(g.sort),typeof c=="number"&&p.push(q(`offset ${c};`,i)),typeof m=="number"&&p.push(q(`limit ${m};`,i)),p.push(q("};",n));}return p},Ft=(t,e,r,n,o)=>{let i=n+1,p=[];for(let d of t){let{$fields:h,$as:$,$justId:s,$idNotIncluded:a,$filterByUnique:u,$playedBy:f,$thing:l,$sort:c,$offset:m,$limit:y}=d,B=d[v],T=`$metadata:{as:${$},justId:${s?"T":"F"},idNotIncluded:${a},filterByUnique:${u}}`;p.push(q(`"${r}.${T}.${d.$var}": {`,n)),p.push(q("match",i));let g=`${e}${gt}${d.$var}`;p.push(q(`$${g} isa ${d.$thing};`,i)),d.$filter&&p.push(bt({$filter:d.$filter,$var:g,$thing:d.$thing,schema:o,depth:i}));let Q=wt({schema:o,$thing:l,$var:g,$sort:c,depth:i});if(Q&&p.push(Q.match),d.$target==="role"?p.push(q(`$${e}_intermediary (${d.$plays}: $${e}, ${f.plays}: $${g}) isa ${d.$intermediary};`,i)):p.push(`
74
- $${g} (${d.$plays}: $${e}) isa ${d.$thing};`),h){let M=`M_${v4()}`;p.push(q(`?queryPath${M} = "${B}";`,i)),p.push(q("fetch",i)),p.push(q(`?queryPath${M} as "queryPath";`,i));let L=h?.filter(D=>D.$fieldType==="data");L&&L.length>0&&p.push(...Bt(L,g,i));let A=h?.filter(D=>D.$fieldType==="link");A&&A.length>0&&p.push(...Ft(A,g,`${e}.${d.$var}`,i,o));let R=h?.filter(D=>D.$fieldType==="role");R&&R.length>0&&p.push(...Et(R,g,`${e}.${d.$var}`,i,o));}Q&&p.push(Q.sort),typeof m=="number"&&p.push(q(`offset ${m};`,i)),typeof y=="number"&&p.push(q(`limit ${y};`,i)),p.push(q("};",n));}return p},bt=t=>{let{$filter:e,$var:r,$thing:n,schema:o,depth:i}=t,{$not:p,...d}=e,h=G(o,n),$=[];return Object.entries(p||{}).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){a===null?$.push(q(`$${r} has ${s} $${s}_${v4()};`,i)):Array.isArray(a)?a.forEach(l=>{$.push(q(`not { $${r} has ${s} ${se(l)}; };`,i));}):$.push(q(`not { $${r} has ${s} ${se(a)}; };`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")a===null?$.push(q(`(${f.plays}: $${r}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(y=>{$.push(q(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(y)}; };`,i));}):$.push(q(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(a)}; };`,i));else {let y=`${l.thing}_${v4()}`;a===null?$.push(q(`$${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(B=>{$.push(q(`not { $${y} isa ${l.thing}, has ${m} ${se(B)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}):$.push(q(`not { $${y} isa ${l.thing}, has ${m} ${se(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${v4()}`;a===null?$.push(q(`$${r} (${c.plays}: ${B});`,i)):Array.isArray(a)?a.forEach(T=>{$.push(q(`not { $${B} isa ${c.thing}, has ${y} ${se(T)}; $${r} (${c.plays}: $${B}); };`,i));}):$.push(q(`not { $${B} isa ${c.thing}, has ${y} ${se(a)}; $${r} (${c.plays}: $${B}); };`,i));return}}}),Object.entries(d).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){if(a===null)$.push(q(`not { $${r} has ${s} $${s}_${v4()}; };`,i));else if(Array.isArray(a)){let l=a.map(m=>`$${r} has ${s} ${se(m)};`),c=Ke(l);c&&$.push(q(c,i));}else $.push(q(`$${r} has ${s} ${se(a)};`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")if(a===null)$.push(q(`not { (${f.plays}: $${r}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let y=a.map(T=>`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(T)};`),B=Ke(y);B&&$.push(q(B,i));}else $.push(q(`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(a)};`,i));else {let y=`${l.thing}_${v4()}`;if(a===null)$.push(q(`not { $${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let B=a.map(g=>`$${y} isa ${l.thing}, has ${m} ${se(g)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`),T=Ke(B);T&&$.push(q(T,i));}else $.push(q(`$${y} isa ${l.thing}, has ${m} ${se(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${v4()}`;if(a===null)$.push(q(`not { $${r} (${c.plays}: ${B}); };`,i));else if(Array.isArray(a)){let T=a.map(Q=>`$${B} isa ${c.thing}, has ${y} ${se(Q)}; $${r} (${c.plays}: $${B});`),g=Ke(T);g&&$.push(q(g,i));}else $.push(q(`$${B} isa ${c.thing}, has ${y} ${se(a)}; $${r} (${c.plays}: $${B});`,i));return}}throw new Error(`"${n}" does not have property "${s}"`)}),$.join(`
75
- `)},Ke=t=>{if(t.length>1)return `{ ${t.join(" } or { ")} };`;let[e]=t;return e},se=t=>typeof t=="string"?`'${t}'`:t instanceof Date?`'${t.toISOString().replace("Z","")}'`:`${t}`,us=t=>typeof t=="string"?{field:t,desc:!1}:{...t,desc:t.desc??!1},wt=t=>{let{$var:e,$thing:r,schema:n,$sort:o,depth:i}=t,p=G(n,r),d=[],h=[];if(o?.forEach($=>{let s=us($),a=p.dataFields?.find(l=>l.path===s.field);if(!a)throw new Error(`"${r}" does not have data field "${s.field}"`);let u=`${s.field}_${v4()}`;d.push(q("{",i)),d.push(q(`$${e} has ${a.dbPath} $${u}_1;`,i+1)),d.push(q("not {",i+1)),d.push(q(`$${e} has ${a.dbPath} $${u}_2;`,i+2)),d.push(q(`$${u}_2 < $${u}_1;`,i+2)),d.push(q("};",i+1)),d.push(q(`?${u}_ = $${u}_1;`,i+1)),d.push(q("} or {",i)),d.push(q(`not { $${e} has ${a.dbPath} $${u}_1; };`,i+1)),d.push(q(`?${u}_ = "~";`,i+1)),d.push(q("};",i)),d.push(q(`?${u} = ?${u}_;`,i));let f=s.desc?"desc":"asc";h.push(`?${u} ${f}`);}),d.length!==0)return {match:d.join(""),sort:q(`sort ${h.join(", ")};`,i)}};var fn=async t=>{let{enrichedBqlQuery:e,rawBqlRequest:r,schema:n,config:o,rawTqlRes:i}=t;if(e){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((p,d)=>{let h=r[d],$=e[d];return $s(p,h,$,n,o)})},$s=(t,e,r,n,o)=>t.length===0?null:r.$filterByUnique?$n(t[0],e,n,o):t.map(i=>$n(i,e,n,o)),$n=(t,e,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:p,roleFields:d,schemaValue:h}=Tt(t,r),$=Qt(o,i,n),s=Lt(p,r,n),a=Mt(d,r,n);console.log("parseObj/parsedLinkFields",JSON.stringify(s)),console.log("parseObj/parsedRoleFields",JSON.stringify(a));let u=e?.$fields?.every(l=>!i?.idFields?.includes(typeof l=="string"?l:l.$path));return {...s,...a,...h,...!n.query?.noMetadata&&e.$id?{$id:Array.isArray(e.$id)?$.id:e.$id}:{},...u?Object.fromEntries(Object.entries($).filter(([l])=>!i?.idFields?.includes(l))):$}},Tt=(t,e)=>{let r=Object.keys(t),n=r.find(u=>u.endsWith(".$dataFields"));if(!n)throw new Error("No datafields");let o=t[n],i=n.split(".")[n.split(".").length-2];if(o.$metaData=i,o.length===0)throw new Error("No datafields");let p=o.type,d={$thing:p.label,$thingType:p.root,[v]:t.queryPath.value},h={[`$${d.$thingType}`]:d.$thing},$=C(e,h),s=r.filter(u=>{let f=le(u.split(".").pop());return !u.endsWith(".$dataFields")&&$.linkFields?.some(l=>l.path===f)}).map(u=>{let f=le(u.split(".").pop()),l=le($.linkFields?.find(c=>c.path===f));return {$linkFields:t[u],$key:f,$metaData:u.split(".")[u.split(".").length-2],$cardinality:l.cardinality}}),a=r.filter(u=>{let f=u.split(".").pop();return f&&!u.endsWith(".$dataFields")&&$.thingType==="relation"&&$.roles?.[f]}).map(u=>{let f=le(u.split(".").pop());return {$roleFields:t[u],$key:f,$metaData:u.split(".")[u.split(".").length-2],$cardinality:$.roles[f].cardinality}});return {dataFields:o,schemaValue:d,currentSchema:$,linkFields:s,roleFields:a}},Qt=(t,e,r)=>{let{$metaData:n}=t,{as:o}=fs(n),i=Object.entries(t).filter(([p])=>p!=="type"&&!p.startsWith("$")).map(([p,d])=>{let h=e.dataFields?.find(u=>u.path===p||u.dbPath===p),$=p==="id",s=Array.isArray(o)?o.find(u=>u[p])?.[p]:p,a;if(h?.cardinality==="ONE"){if(a=d[0]?d[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"?a=a&&`${a}Z`:h.contentType==="JSON"&&(a=a&&JSON.parse(a)),$)return [[s,a],["$id",a]].filter(([u,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!isArray(d))throw new Error("Typedb fetch has changed its format");if(d.length===0)return r.query?.returnNulls?[[s,null]]:[];h.contentType==="DATE"?a=d.map(u=>`${u.value}Z`):h.contentType==="JSON"?a=d.map(u=>u.value&&JSON.parse(u.value)):a=d.map(u=>u.value);}return [[s,a]].filter(([u,f])=>f!==void 0)}).flat();return Object.fromEntries([...i])},Mt=(t,e,r)=>{let n={};return t.forEach(o=>{let{$roleFields:i,$metaData:p,$cardinality:d}=o,{as:h,justId:$,idNotIncluded:s,filterByUnique:a}=yn(p);if(h===null){console.log("parseRoleFields/as is null");return}let u=i.map(f=>{let{dataFields:l,currentSchema:c,linkFields:m,roleFields:y,schemaValue:B}=Tt(f,e),T=Qt(l,c,r);if($==="T")return T.id;{let g=Lt(m,e,r),Q=Mt(y,e,r),M={...T};return s==="true"&&c?.idFields?.forEach(L=>delete M[L]),{...M,...g,...Q,...B}}});u.length>0?n[h]=d==="MANY"&&a==="false"?u:u[0]:r.query?.returnNulls&&(n[h]=null);}),n},Lt=(t,e,r)=>{let n={};return t.forEach(o=>{let{$linkFields:i,$metaData:p,$cardinality:d}=o,{as:h,justId:$,idNotIncluded:s,filterByUnique:a}=yn(p);if(h===null){console.log("parseLinkFields/as is null");return}let u=i.map(f=>{let{dataFields:l,currentSchema:c,linkFields:m,roleFields:y,schemaValue:B}=Tt(f,e),T=Qt(l,c,r);if($==="T")return T.id;{let g=Lt(m,e,r),Q=Mt(y,e,r),M={...T};return s==="true"&&c.idFields?.forEach(L=>delete M[L]),{...M,...g,...Q,...B}}});n[h]=u.length>0?d==="MANY"&&a==="false"?u:u[0]:r.query?.returnNulls?null:void 0;}),n},yn=t=>{let e=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=t.match(e),p=t.match(r),d=t.match(n),h=t.match(o);return {as:i?i[1]:null,justId:p?p[1]:null,idNotIncluded:d?d[1]:null,filterByUnique:h?h[1]:null}},fs=t=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(p,d,h)=>/^{.*}$/.test(h)?`:${h}`:`:${d}"${h}"`),i=i.replace(/\[([^\]]+)\]/g,(p,d)=>`[${d.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),i})(t);return JSON.parse(r)}catch(e){return console.error(e),{as:[]}}};var mn=async t=>{let{tqlRequest:e,dbHandles:r,config:n}=t,o=new TypeDBOptions;o.infer=!0;let{session:i}=await Qe(r,n),p=await i.transaction(TransactionType.READ,o);if(!p)throw new Error("Can't create transaction");return await parallel(e.length,e,async h=>await p.query.fetch(h).collect())};var Bs=(t,e)=>e.data?{...t,bql:{...t.bql,res:e.data}}:t,Es=(t,e)=>e.data?{...t,tql:{...t.tql,queries:e.data}}:t,Fs=(t,e)=>e.data?{...t,tql:{...t.tql,res:e.data}}:t,kt=K("error","error",U((t,e)=>({...t,error:e.error}))),bs=be("build",{build:Z(async t=>hn({queries:t.bql.queries,schema:t.schema}),K("done","run",U(Es)),kt),run:Z(async t=>mn({dbHandles:t.handles,tqlRequest:le(t.tql.queries),config:t.config}),K("done","parse",U(Fs)),kt),parse:Z(async t=>fn({rawBqlRequest:t.bql.raw,enrichedBqlQuery:t.bql.queries,schema:t.schema,config:t.config,rawTqlRes:le(t.tql.res)}),K("done","success",U(Bs)),kt),success:de(),error:de()},t=>t),ws=async t=>new Promise((e,r)=>{fe(bs,n=>{n.machine.state.name==="success"&&e(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},t);}),gn=async(t,e,r,n,o)=>ws({bql:{raw:t,queries:e},tql:{},schema:r,config:n,handles:o,error:null});var Ts=(t,e)=>e.data?{...t,bql:{...t.bql,queries:e.data}}:t,St=(t,e)=>e.data?{...t,bql:{...t.bql,res:e.data}}:t,Je=K("error","error",U((t,e)=>({...t,error:e.error}))),Qs=be("enrich",{enrich:Z(async t=>tn(t.bql.raw,t.schema),K("done","adapter",U(Ts)),Je),adapter:Z(async t=>{let e={};t.bql.queries?.forEach((d,h)=>{let $=t.bql.raw[h],s=G(t.schema,d.$thing),{id:a}=s.defaultDBConnector;if(s.db==="typeDB"){if(!e[a]){let f=t.handles.typeDB?.get(a)?.client;if(!f)throw new Error(`TypeDB client with id "${s.defaultDBConnector.id}" does not exist`);e[a]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(s.db==="surrealDB"){if(!e[a]){let f=t.handles.surrealDB?.get(a)?.client;if(!f)throw new Error(`SurrealDB client with id "${s.defaultDBConnector.id}" does not exist`);e[a]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${s.db}"`);let u=e[a];u.rawBql.push($),u.bqlQueries.push(d),u.indices.push(h);});let r=Object.values(e),n=r.map(d=>d.db==="typeDB"?gn(d.rawBql,d.bqlQueries,t.schema,t.config,t.handles):un(d.bqlQueries,t.schema,t.config,d.client)),o=await Promise.all(n),i=r.flatMap((d,h)=>{let $=o[h];return d.indices.map((s,a)=>({index:s,result:$[a]}))});return i.sort((d,h)=>d.index<h.index?-1:d.index>h.index?1:0),i.map(({result:d})=>d)},K("done","postHooks",U(St)),Je),postHooks:Z(async t=>rn(t.schema,le(t.bql.queries),le(t.bql.res)),K("done","clean",U(St)),Je),clean:Z(async t=>Yr(t.config,le(t.bql.res)),K("done","success",U(St)),Je),success:de(),error:de()},t=>t),Ms=async t=>new Promise((e,r)=>{fe(Qs,n=>{n.machine.state.name==="success"&&e(n.context),n.machine.state.name==="error"&&r(n.context);},t);}),Bn=async(t,e,r,n)=>Ms({bql:{raw:t},schema:e,config:r,handles:n,error:null});enableMapSet();var qt=class{schema;config;dbHandles;constructor({schema:e,config:r}){this.schema=e,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let e={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let o=new Surreal;await o.connect(n.url),await o.signin({namespace:n.namespace,database:n.dbName,username:n.username,password:n.password}),e.surrealDB.set(n.id,{client:o});}if(n.provider==="typeDB"&&n.dbName){let[o,i]=await tryit(TypeDB.coreDriver)(n.url);if(o){let p=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(p)}try{let p=await i.session(n.dbName,SessionType.DATA);e.typeDB.set(n.id,{client:i,session:p});}catch(p){let d=`[BORM:${n.provider}:${n.dbName}:session] ${(p.messageTemplate?._messageBody()||p.message)??"Can't create TypeDB Session"}`;throw new Error(d)}}if(n.provider==="typeDBCluster"&&n.dbName){let[o,i]=await tryit(TypeDB.cloudDriver)(n.addresses,n.credentials);if(o){let p=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(p)}try{let p=await i.session(n.dbName,SessionType.DATA);e.typeDB.set(n.id,{client:i,session:p});}catch(p){let d=`[BORM:${n.provider}:${n.dbName}:session] ${(p.messageTemplate?._messageBody()||p.message)??"Can't create TypeDB Session"}`;throw new Error(d)}}}));let r=xt(this.schema,e);this.schema=r,this.dbHandles=e;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),At(this.config,this.schema,this.dbHandles));query=async(e,r)=>{await this.#e();let n={...this.config,query:{...Ye.query,...this.config.query,...r}},o=Array.isArray(e),i=o?e:[e],[p,d]=await tryit(Bn)(i,this.schema,n,this.dbHandles);if(p){let $=new Error(p.error);throw $.stack=p.error.stack,$}let h=d.bql.res;return o?h:h[0]};mutate=async(e,r)=>{await this.#e();let n={...this.config,mutation:{...Ye.mutation,...this.config.mutation,...r}},[o,i]=await tryit(Ur)(e,this.schema,n,this.dbHandles);if(o){let d=new Error(o.error.message);throw d.stack=o.error.stack,d}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:e,session:r})=>{r.isOpen()&&await r.close(),await e.close();});}},Zc=qt;//! Todo: delete when this works with the new $thing and $thingType fields
35
+ ${g}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:c}]=e.dbConnectors;await(await s.databases.get(c)).delete(),await s.databases.create(c);let u=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),h=await u.transaction(TransactionType.WRITE);await h.query.define(o),await h.commit(),await h.close();let a=await u.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async g=>{g.get("a");}),await a.close();};var Ct={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Pt=(e,t,r)=>r?t:`${e}\xB7${t}`;var qt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],Ce=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),Ot=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:c})=>{if(c.depth===2&&(l&&(s.dataFields=s.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:Pt(l,p.path,p.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector`);let p=n.entities[s.extends]||n.relations[s.extends];if(s.allExtends=[s.extends,...p.allExtends||[]],s.idFields=p.idFields?(s.idFields||[]).concat(p.idFields):s.idFields,s.dataFields=p.dataFields?(s.dataFields||[]).concat(p.dataFields.map(u=>{let h=s.extends,a=e.entities[h]||e.relations[h];for(;!a.dataFields?.find(f=>f.path===u.path);)h="extends"in a?a.extends:void 0,a=e.entities[h]||e.relations[h];return {...u,dbPath:Pt(h,u.path,u.shared)}})):s.dataFields,s.linkFields=p.linkFields?(s.linkFields||[]).concat(p.linkFields):s.linkFields,"roles"in p){let u=s,h=p;u.roles=u.roles||{},u.roles={...u.roles,...h.roles},Object.keys(u.roles).length===0&&(u.roles={});}p?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...p?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let p=(()=>{if(!s.nodePath)throw new Error("No path");let[h,a]=s.nodePath.split(".");return {thing:a,thingType:h==="entities"?"entity":h==="relations"?"relation":""}})(),u=Array.isArray(l)?l.map(h=>({...h,...p})):[{...l,...p}];r.push(...u);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:c})=>{if(c.depth===2&&l.idFields&&!l.id){l.name=s;let p=()=>{if(c.nodePath?.split(".")[0]==="entities")return "entity";if(c.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=p();let u=Object.keys(t).find(h=>t[h]?.get(l.defaultDBConnector.id));l.db=u,l.dbContext=Ct[u],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField",f.playedBy=r.filter(d=>d.relation===s&&d.plays===a)||[],f.name=a;}),"linkFields"in l&&l.linkFields&&l.linkFields?.forEach(a=>{if(a.fieldType="linkField",a.target==="relation"){a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];return}let f=r.filter($=>$.relation===a.relation&&$.plays!==a.plays)||[];a.oppositeLinkFieldsPlayedBy=f;let{filter:d}=a;a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),d&&Array.isArray(d)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>d.some(g=>$.thing===g.$role)),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>d.some(g=>$.thing===g.$thing))),d&&!Array.isArray(d)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.$role===d.$role),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.thing===d.$thing));});}if(typeof l=="object"&&"playedBy"in l){let p=[...new Set(l.playedBy.map(u=>u.thing))];if(p.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${c.nodePath}, played by: ${p.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${c.nodePath}`)}if(c.depth===4){let[p,u]=c.nodePath?.split(".")||[],h=n[p][u];l.validations&&(l.validations.required&&h.requiredFields.push(l.path),l.validations.enum&&h.enumFields.push(l.path),l.validations.fn&&h.fnValidatedFields.push(l.path)),l.default?l.isVirtual?h.virtualFields.push(l.path):h.computedFields.push(l.path):l.isVirtual&&h.virtualFields.push(l.path);}}))},ee=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},O=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},xt=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},Ge=(e,t,r)=>{let i=O(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l},Xe=(e,t,r)=>Ge(e,t,r)?.cardinality,de=(e,t)=>{let r=e.dataFields?.map(d=>d.path)||[],i=e.linkFields?.map(d=>d.path)||[],o="roles"in e?listify(e.roles,d=>d):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let c=t.$fields?t.$fields.map(d=>{if(typeof d=="string"){if(d.startsWith("$")||d.startsWith("%"))return;if(!n.includes(d))throw new Error(`Field ${d} not found in the schema`);return d}if("$path"in d&&typeof d.$path=="string")return d.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,d=>{if(!(d.startsWith("$")||d.startsWith("%"))){if(!n.includes(d))throw new Error(`[Schema] Field ${d} not found in the schema`);return d}}).filter(d=>d!==void 0),p=t.$filter?listify(t.$filter,d=>d.toString().startsWith("$")?void 0:d.toString()).filter(d=>d&&r?.includes(d)):[],u=t.$filter?listify(t.$filter,d=>d.toString().startsWith("$")?void 0:d.toString()).filter(d=>d&&[...o||[],...i||[]].includes(d)):[],h=[...c,...p].filter(d=>!d?.startsWith("%")).filter(d=>!s.includes(d)).filter(d=>d),a=t.$filter?Ce(t.$filter,(d,$)=>p.includes(d)):{},f=t.$filter?Ce(t.$filter,(d,$)=>u.includes(d)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:c,usedLinkFields:i.filter(d=>c.includes(d)),usedRoleFields:o.filter(d=>c.includes(d)),usedDataFields:r.filter(d=>c.includes(d)),unidentifiedFields:h,...p.length?{localFilters:a}:{},...u.length?{nestedFilters:f}:{}}};var jt=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Nt=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},me=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Pe=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),he=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},oe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},b=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Me=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.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 _t=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Me(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,c=n.thingType;if(i.some(p=>p.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:c,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var be=(e,t,r)=>{let i=O(r,t),{usedDataFields:o}=de(i,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"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var qe=(e,t,r)=>{let i=O(r,t),{usedFields:o}=de(i,t);return t.$op?(be(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(be(e,{...t,$op:"update"},r),"update"):(be(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(be(e,{...t,$op:"create"},r),"create"):(be(e,{...t,$op:"create"},r),"link"):(be(e,{...t,$op:"create"},r),"create")};var Wt=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=qe(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:xt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ue=Symbol.for("queryPath"),Oe=Symbol.for("stepPrint"),we=Symbol.for("edgeType"),ye=Symbol.for("edgeSchema"),Te=Symbol.for("dbNode"),et=Symbol.for("isTransformed");var xe=(e,t)=>{let r=t[Oe];return isSet(r)?r.has("clean")?(Reflect.set(t,Oe,r.add("clean")),!0):!1:(Reflect.set(t,Oe,new Set(["clean"])),!0)};var Vt=(e,t,r)=>{if(xe("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(O(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...he(n),$id:l,$bzId:`${n.$bzId}_${s}`,...me(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var Kt=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Me(t,r),[s]=l,c=qe(e,{...n,$thing:s.thing,$thingType:s.thingType},i),p=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[ye]:r,$thing:s.thing,$thingType:s.thingType,$op:c,$bzId:p}});e[t]=isArray(e[t])?o:o[0];};var Bn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,En=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Ut=e=>{let r=e.toString().replace(Bn,"").trim().split("=>")[0].split("{")[0].replace(En,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Le=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!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(r){let{fn:o}=t.default,l=Ut(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var vt=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=O(r,o),{unidentifiedFields:l}=de(n,o),{computedFields:s,virtualFields:c}=n,p=listify(o,(a,f)=>f!==void 0?a:void 0),u=p.filter(a=>c?.includes(a));if(u.length>0)throw new Error(`Virtual fields can't be sent to DB: "${u.join(",")}"`);if(s.filter(a=>!p.includes(a)).forEach(a=>{let f=n.dataFields?.find(w=>w.path===a),$=n.linkFields?.find(w=>w.path===a)?.oppositeLinkFieldsPlayedBy[0],g="roles"in n?qt(n.roles,(w,T)=>w===a):void 0,y=f||$||g;if(!y)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let w=Le({currentThing:o,fieldSchema:y,mandatoryDependencies:!0});o[a]=w;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var je=(e,t)=>{let r=O(t,e).hooks;if(r?.pre){let i=`on${jt(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var Zt=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:c,dataFields:p}=O(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(u=>{if(!(u in n))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(u=>{if(u in n){let h=p?.find(a=>a.path===u)?.validations?.enum;if(!h)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(n[u]))n[u].some(a=>{if(!h.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${u}".`)});else if(h&&!h.includes(n[u]))throw new Error(`[Validations] Option "${n[u]}" is not a valid option for field "${u}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&c.forEach(u=>{if(u in n)try{let h=p?.find(a=>a.path===u)?.validations?.fn;if(!h)throw new Error("Missing validation function.");if(!h(n[u]))throw new Error("Failed validation function.")}catch(h){throw new Error(`[Validations:attribute:${u}] ${h.message}`)}}),isObject(n)&&"$thing"in n){let u=n.$thing,h=n,a=clone(he(e)),f=clone(he(h)),d=i.mutation?.context||{},$=clone(he(n[Te]||{}));je(h,r).forEach(y=>{if(y.type==="validate"){if(y.severity!=="error")return;try{let w=y.fn(f,a,d,$);if(w===!1)throw new Error(`${y.message}.`);if(w!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(w){throw new Error(`[Validations:thing:${u}] ${w.message}`)}}});}}});};var Gt=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Pe(n)){if(n.$fields||n[et])return n;let l=je(n,r).filter(h=>h.type==="transform"),s=clone(he(e)),c=clone(he(n)),p=i.mutation?.context||{},u=clone(he(n[Te]||n.$dbNode));return l.forEach(h=>{let a=h.fn(c,s,p,u||{});Object.keys(a).length!==0&&(n={...c,...a,...me(n),[et]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Xt=(e,t,r)=>{let i=Me(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[ye]:r};};var ke=e=>{if(Array.isArray(e)){for(let t of e)if(ke(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&ke(e[t]))return !0}return !1};var Dn=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(xe("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Rn=(e,t)=>{},ot=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=ke(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:c,key:p,meta:u})=>{if(!(!c||!p)&&isObject(s)){let h=u.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let d=["$fields","$dbNode","$filter"],$=h[h.length-1],g=h[h.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!d.includes($)&&!d.includes(g))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,f=h.includes("$filter");Object.keys(a).forEach(d=>{if(Dn(a,d),d!=="$root"&&f||d!=="$root"&&(d.startsWith("$")||d.startsWith("%")))return;let $=d!=="$root"?Ge(t,a,d):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${d} not found in schema`);if("contentType"in $)return Rn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[d]===null?Xt(a,d,$):_t(a,d,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${d} is a rootField but the object is not a root`);Wt(a,t);}let g=isArray(a[d])?a[d]:[a[d]],y=h.slice(1).join(".");g.forEach(T=>{if(T){if($?.cardinality==="ONE"&&!T.$op&&!T.$id&&!T.$filter&&!T.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${y}.${d}`);if(T.$tempId&&!(T.$op===void 0||T.$op==="link"||T.$op==="create"||T.$op==="update"))throw new Error(`Invalid op ${T.$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($.fieldType)&&Kt(a,d,$,t),Vt(a,d,t),["rootField","linkField","roleField"].includes($.fieldType)&&vt(a,d,t),(isArray(a[d])?a[d]:[a[d]]).forEach(T=>{let m=O(t,T),{unidentifiedFields:D,usedLinkFields:R,usedFields:A,fields:x}=de(m,T);if(A.forEach(j=>{if(!x.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),D.length>0)throw new Error(`Unknown fields: [${D.join(",")}] in ${JSON.stringify(s)}`);if(R.length>1){let j=m.linkFields?.filter(N=>R.includes(N.path));j?.some((N,se)=>j.some((K,S)=>{if(se!==S&&N.target!==K.target&&N.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(Gt(a,d,t,r),Zt(a,d,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ne=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var er=async(e,t,r)=>{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:i}=await Ne(t,r),o=await i.transaction(TransactionType.WRITE);if(!o)throw new Error("Can't create transaction");let n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;n&&await o.query.delete(n);let s=l&&o.query.insert(l);try{let c=s?await s.collect():void 0;return await o.commit(),await o.close(),{insertions:c}}catch(c){throw await o.close(),new Error(`Transaction failed: ${c.message}`)}};var tr=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let c=e.insertions?.find(h=>h.get(`${s.$bzId}`))?.get(`${s.$bzId}`),p=s.$thing||s.$relation||s.$entity,u=p?ee(i,p):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!c&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let h=c?.asThing().iid,a=Object.entries(s).filter(([d,$])=>!d.startsWith("$")).reduce((d,[$,g])=>{if(u?.dataFields?.find(w=>w.path===$)?.contentType==="JSON")return d[$]=JSON.parse(g),d;if(s.$thingType==="relation"){let w=n.filter(T=>T.$id&&T.$bzId===g);return w.length===1?(d[$]=w[0].$id,d):(d[$]=g,d)}return d[$]=g,d},{});if(o.mutation?.noMetadata)return a;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:h,...s,...a,[s.path]:s.$id,...f}}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(l)};var rr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var sr=async(e,t)=>{let r=u=>{let h=[],a=[],f=y=>{if(y.$id)return y.$id;let w=O(t,y),{idFields:T}=w;if(!T)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[m]=T;if(!m)throw new Error(`no idField: ${JSON.stringify(y)}`);let D=w.dataFields?.find(x=>x.path===m),R=Le({currentThing:y,fieldSchema:D,mandatoryDependencies:!0}),A=y[m]||y.$id||R;if(!A)throw new Error(`no idValue: ${JSON.stringify(y)}`);return A},d=y=>{if(y.$op==="create"){let w=f(y);if(h.find(T=>T.$id===w&&T.$op==="create"))throw new Error(`Duplicate id ${w} for node ${JSON.stringify(y)}`);if(a.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate $bzId ${y.$bzId} for node ${JSON.stringify(y)}`);h.push({...y,$id:w});return}y.$tempId&&y.$op==="match"||h.push(y);},$=y=>{if(y.$op==="create"){let w=f(y);if(h.find(T=>T.$id===w),a.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate %bzId ${y.$bzIdd} for edge ${JSON.stringify(y)}`);a.push({...y,$id:w});return}a.push(y);};return traverse(u,({value:y,parent:w,meta:T})=>{if(!isObject(y))return;let m=y;if(m.$thing){if(!m.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(m)}`);if(!m.$bzId)throw new Error("[internal error] BzId not found");let D=O(t,m),{dataFields:R,roleFields:A,linkFields:x,usedFields:j}=de(D,m),N=()=>{if(m.$op==="create"||m.$op==="delete")return m.$op;if(m.$op==="update"){let S=j.filter(F=>R?.includes(F)),B=j.filter(F=>A?.includes(F)),Q=j.filter(F=>x?.includes(F));if(S.length>0)return "update";if(B.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(m)}`)}return "match"},se={...m.$id&&{$id:m.$id},...m.$tempId&&{$tempId:m.$tempId},...m.$filter&&{$filter:m.$filter},$thing:m.$thing,...m.$thingType&&{$thingType:m.$thingType},...shake(pick(m,R||[""])),$op:N(),$bzId:m.$bzId};d(se);let K=m[ye];if(K?.fieldType==="linkField"){if((m.$op==="link"||m.$op==="unlink")&&(m.$id||m.$filter)){if(m.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");h.push({...m,$op:"match"});}let S=K.relation===m.$thing,B=S?m.$bzId:`LT_${v4()}`,F=Nt(u,w,T).$bzId;if(!F)throw new Error("No parent id found");let E=()=>{if(m.$op==="delete")return S?"match":"delete";if(m.$op==="unlink")return S?"unlink":"delete";if(m.$op==="link"||m.$op==="create")return S?"link":"create";if(m.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},M=O(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(M.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let P={$bzId:B,$thing:K.relation,$thingType:"relation",...m.$tempId?{$tempId:m.$tempId}:{},$op:E(),...S?{}:{[K.path]:m.$bzId},[K.plays]:F,[ye]:K,[we]:"linkField"};$(P),(m.$op==="unlink"||E()==="unlink")&&S&&$({$thing:K.relation,$thingType:"relation",$bzId:B,$op:"match",[K.plays]:F,[ye]:K,[we]:"linkField"});}if(m.$thingType==="relation"){let S=Ce(m,(F,E)=>A.includes(F)),B=mapEntries(S,(F,E)=>isArray(E)?[F,E]:isObject(E)?[F,E.$bzId]:[F,E]),Q=Ce(y,(F,E)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(S).filter(F=>!F.startsWith("$")).length>0){if(m.$op==="create"||m.$op==="delete"){let F=()=>{if(m.$op==="create")return "link";if(m.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},E=O(t,m).roles,M=mapEntries(B,(P,k)=>{let q=E[P]?.cardinality;if(!q)throw new Error(`Role ${P} not found in schema`);if(Array.isArray(k)){if(q==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${P} is not a MANY relation`);return [P,k[0].$bzId||k[0]]}return [P,k.map(v=>v.$bzId||v)]}return [P,k.$bzId||k]}),L={...Q,$thing:m.$thing,$thingType:"relation",$op:F(),...M,$bzId:m.$bzId,[we]:"roleField"};$(L);return}if(m.$op==="match"||m.$op==="update"&&Object.keys(S).length>0){let F=0;Object.entries(S).forEach(([E,M])=>{let L=isArray(M)?M:[M],P=k=>k==="create"||k==="replace"?"link":k;L.forEach(k=>{if(!k)return;let q=P(k.$op);if(q==="replace")throw new Error("Not supported yet: replace on roleFields");if(q==="unlink"&&F>0)throw F+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let v={...Q,$thing:m.$thing,$thingType:"relation",$op:q==="delete"?"unlink":q,[E]:k.$bzId,$bzId:m.$bzId,[we]:"roleField"};$(v);});});}}}}}),[h,a]},[i,o]=r(e),n=i.reduce((u,h)=>{if(!h.$bzId)return [...u,h];let a=u.findIndex(f=>f.$bzId===h.$bzId);if(a===-1)return [...u,h];if(u[a].$op==="create"&&h.$op==="match")return u;if(u[a].$op==="match"&&(h.$op==="create"||h.$op==="match"))return [...u.slice(0,a),h,...u.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${h.$tempId}". Existing: ${u[a].$op}. Current: ${h.$op}`)},[]),l=o.reduce((u,h)=>{let a=u.find(f=>(f.$id&&f.$id===h.$id||f.$bzId&&f.$bzId===h.$bzId)&&f.$thing===h.$thing&&f.$op===h.$op);if(a){let f={...a};return Object.keys(h).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=a[$],y=h[$];Array.isArray(g)&&Array.isArray(y)?f[$]=Array.from(new Set([...g,...y])):!Array.isArray(g)&&Array.isArray(y)?g!==void 0?f[$]=Array.from(new Set([g,...y])):f[$]=y:Array.isArray(g)&&!Array.isArray(y)?y!==void 0&&(f[$]=Array.from(new Set([...g,y]))):g!==null&&y!==null&&g!==void 0&&y!==void 0?f[$]=Array.from(new Set([g,y])):g==null&&(f[$]=y);}),[...u.filter($=>!(($.$id&&$.$id===h.$id||$.$bzId&&$.$bzId===h.$bzId)&&$.$thing===h.$thing&&$.$op===h.$op)),f]}return [...u,h]},[]);n.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&l.filter(h=>h.$bzId===u.$bzId||h.$tempId&&h.$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(rr(u))}`)}});let s=[...n,...l],c=new Set(s.filter(u=>u.$tempId).map(u=>u.$tempId)),p=Array.from(c).filter(u=>!s.some(h=>h.$tempId===u&&h.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var ar=async(e,t,r)=>{let i=a=>{let f=a.$op,d=`$${a.$bzId}`,$=O(r,a),{idFields:g,defaultDBConnector:y}=$,w=y?.path||a.$thing,T=a.$id,m=g?.[0],D=listify(a,(S,B)=>{if(S.startsWith("$")||S.startsWith("%")||S===m||B===void 0||B===null)return "";let Q=$.dataFields?.find(M=>M.path===S);if(!Q?.path)return "";let E=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${E} '${B}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${E} ${B}`;if(Q.contentType==="DATE"){if(Number.isNaN(B.valueOf()))throw new Error("Invalid format, Nan Date");return B instanceof Date?`has ${E} ${B.toISOString().replace("Z","")}`:`has ${E} ${new Date(B).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(S=>S),R=`${d}-atts`,A=listify(a,S=>{if(S.startsWith("$")||S.startsWith("%")||S===m)return "";let B=$.dataFields?.find(E=>E.path===S);if(!B?.path)return "";let F=B.dbPath;return `{${R} isa ${F};}`}).filter(S=>S),x=isArray(T)?`like '${T.join("|")}'`:`'${T}'`,j=T?[`has ${m} ${x}`]:[],N=[...j,...D].filter(S=>S).join(","),se=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${d} isa ${[w,...j].filter(S=>S).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${d} isa ${[w,...j].filter(S=>S).join(",")}, has ${R};
36
+ ${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${d} isa ${[w,...j].filter(S=>S).join(",")};`:"";if(Pe(a))return {op:f,deletionMatch:se(),insertionMatch:K(),insertion:f==="create"?`${d} isa ${[w,N].filter(S=>S).join(",")};`:f==="update"&&D.length?`${d} ${D.join(",")};`:"",deletion:f==="delete"?`${d} isa ${w};`:f==="update"&&A.length?`${d} has ${R};`:""};throw new Error("in attributes")},o=a=>{let f=a.$op,d=O(r,a),$=`$${a.$bzId}`,g=a.$id,y=d.defaultDBConnector?.path||a.$thing,w="roles"in d?listify(d.roles,B=>B):[],T="roles"in d?mapEntries(d.roles,(B,Q)=>[B,Q.dbConnector?.path||B]):{},m=listify(a,(B,Q)=>{if(!w.includes(B))return null;if(!("roles"in d))throw new Error("This should have roles! ");let F=T[B];return Array.isArray(Q)?Q.map(E=>({path:F,id:E})):{path:F,id:Q}}).filter(B=>B).flat(),D=m.map(B=>{if(!B?.path)throw new Error("Object without path");return `${B.path}: $${B.id}`}),R=m.length>0?`( ${D.join(" , ")} )`:"",A=a[we];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let x=R?`${$} ${R} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",j=`${$} ${A==="linkField"||f==="delete"?`isa ${y}`:""}`,N=()=>x?f==="link"?`${x};`:f==="create"?`${x}, has id '${g}';`:"":"",se=()=>x&&f==="match"?`${x};`:"",K=()=>x?f==="delete"?`${x};`:f==="match"?`${x};`:"":"",S=()=>x?f==="delete"?`${j};`:f==="unlink"?`${$} ${R};`:"":"";return {deletionMatch:K(),insertionMatch:se(),deletion:S(),insertion:N(),op:""}},n=(a,f)=>{let d=f==="edges"?o:i;if(Array.isArray(a))return a.map(m=>{let{preDeletionBatch:D,insertionMatch:R,deletionMatch:A,insertion:x,deletion:j}=d(m);return shake({preDeletionBatch:D,insertionMatch:R,deletionMatch:A,insertion:x,deletion:j},N=>!N)}).filter(m=>m);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:w,deletion:T}=d(a);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:w,deletion:T},m=>!m)},l=n(e),s=Array.isArray(l)?l:[l],c=n(t,"edges"),p=Array.isArray(c)?c:[c],u=[...s,...p];return shake({insertionMatches:u.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:u.map(a=>a.deletionMatch).join(" ").trim(),insertions:u.map(a=>a.insertion).join(" ").trim(),deletions:u.map(a=>a.deletion).join(" ").trim()},a=>!a)};function G(e){return {enumerable:!0,value:e}}function lr(e){return {enumerable:!0,writable:!0,value:e}}var Se={},Wn=()=>!0,cr=()=>({}),hr=e=>e,Vn=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),Hn=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),ge=(e,t)=>Object.freeze(Object.create(e,t));function dr(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function ur(e){return ge(this,{fn:G(e)})}var pr={},V=ur.bind(pr);var fr={},at=ur.bind(fr);function ze(e,t){return t.filter(r=>e.isPrototypeOf(r))}function $r(e,t,...r){let i=dr(ze(fr,r).map(n=>n.fn),Wn,Vn),o=dr(ze(pr,r).map(n=>n.fn),hr,Hn);return ge(this,{from:G(e),to:G(t),guards:G(i),reducers:G(o)})}var mr={},yr={},H=$r.bind(mr);$r.bind(yr,null);function Kn(e,t,r){return ct(t,e,r,this.immediates)||e}function gr(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var Un={enter:hr};function ce(...e){let t=ze(mr,e),r=ze(yr,e),i={final:G(e.length===0),transitions:G(gr(t))};return r.length&&(i.immediates=G(r),i.enter=G(Kn)),ge(Un,i)}var vn={enter(e,t,r){let i=this.fn.call(t,t.context,r);return lt.isPrototypeOf(i)?ge(Br,{machine:G(i),transitions:G(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Br={enter(e,t,r){if(t.child=fe(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,ct(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=G(gr(t));return lt.isPrototypeOf(e)?ge(Br,{machine:G(e),transitions:r}):ge(vn,{fn:G(e),transitions:r})}var lt={get state(){return {name:this.current,value:this.states[this.current]}}};function Be(e,t,r=cr){return typeof e!="string"&&(r=t||cr,t=e,e=Object.keys(t)[0]),Se._create&&Se._create(e,t),ge(lt,{context:G(r),current:G(e),states:G(t)})}function ct(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let c=t.original||t,p=ge(c,{current:G(n),original:{value:c}});Se._onEnter&&Se._onEnter(t,n,e.context,o,r);let u=p.state.value;return e.machine=p,e.onChange(e),u.enter(p,e,r)}}function Jn(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?ct(e,i,t,o.transitions.get(r))||i:(Se._send&&Se._send(r,n),i)}var Zn={send(e){Jn(this,e);}};function fe(e,t,r,i){let o=Object.create(Zn,{machine:lr(e),context:lr(e.context(r,i)),onChange:G(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var wr=(e,t)=>{if(!t)return;let r=Yn(t);return Gn(r,e.query?.noMetadata??!1)},Yn=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Gn=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Lr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:l,meta:s}=n,c=l;if(isObject(c)){if(c.$id){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},u=O(t,p);if(!u?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=u.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),u?.idFields?.length===1){let[h]=u.idFields;c.$filter={...c.$filter,[h]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let p=O(t,c);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=p.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[ue]=s.nodePath;let u=O(t,p);if(c.$filter&&(c.$filterByUnique=ht(c.$filter,u),c.$filterProcessed||(c.$filter=c.$filter&&ut(c.$filter,u))),c.$fields){c.$fields.some(f=>u?.idFields?.includes(f?.$path||f))||(c.$fields=[...c.$fields,...Array.isArray(u.idFields)?u.idFields:[]],c.$idNotIncluded=!0);let a=c.$fields?.flatMap(f=>{let d=Tr(f,u,t);return Array.isArray(d)?d:[d]}).filter(Boolean);c.$fields=a;}else {let a=dt(u)?.flatMap(f=>{let d=Tr(f,u,t);return Array.isArray(d)?d:[d]}).filter(Boolean);c.$fields=a;}c.$excludedFields&&(c.$fields=c.$fields.filter(h=>We(u,h)?!0:!c.$excludedFields.includes(h.$path)));}}}))},dt=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},ht=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(l=>(l.dbPath===i||l.path===i)&&l?.validations?.unique);return o||n}return !1}),ut=(e,t)=>{let r={};if(t.dataFields?.forEach(l=>{l.path!==l.dbPath&&(r[l.path]=l.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=Mr(o,r);return i&&(n.$not=Mr(i,r)),n},Mr=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},We=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),ti=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n}},ri=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l}=e,{target:s,oppositeLinkFieldsPlayedBy:c}=i;return c.map(p=>{let u=s==="role"?p.thingType:"relation",h=s==="role"?p.thing:i.relation,a={[`$${u}`]:h},f=O(l,a),d=t?.$fields?.filter(g=>We(f,g)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(d){let g=f.idFields||[];$=[...t.$fields,...g];}else $=t.$fields;else $=dt(f);else $=["id"];return t.$excludedFields&&($=$.filter(g=>We(f,g)?!0:!t.$excludedFields.includes(g.$path))),{$thingType:u,$plays:i.plays,$playedBy:p,$path:p.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:h,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"link",$target:s,$intermediary:p.relation,$justId:o,$id:t.$id,$filter:t.$filter&&ut(t.$filter,f),$idNotIncluded:d,$filterByUnique:ht(t.$filter,f),$filterProcessed:!0,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit}})},ni=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l}=e;return i.playedBy.map(s=>{let{thing:c,thingType:p,relation:u}=s,h={[`$${p}`]:c},a=O(l,h),f=t?.$fields?.filter($=>a?.idFields?.includes($)||a?.idFields?.includes($.$path)).length===0,d=[];if(typeof t!="string")if(t.$fields)if(f){let $=a.idFields||[];d=[...t.$fields,...$];}else d=t.$fields;else d=dt(a);else d=["id"];return t.$excludedFields&&(d=d.filter($=>We(a,$)?!0:!t.$excludedFields.includes($.$path))),{$thingType:p,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:c,$fields:d,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:o,$id:t.$id,$filter:t.$filter&&ut(t.$filter,a),$idNotIncluded:f,$filterByUnique:ht(t.$filter,a),$playedBy:s,$filterProcessed:!0,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit}})},Tr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(c=>c.path===i),l=t.linkFields?.find(c=>c.path===i),s=t.roles?.[i];if(n){let c=!!n.isVirtual&&!!n.default;return ti({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:c})}else {if(l)return ri({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r});if(s)return ni({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r})}return null};var kr=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let c=s;if(!c.$thing)return;if(c.$thing){let p=O(e,c),{virtualFields:u}=p,h=c[ue];if(!h)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,h),f=a.$fields.map($=>$.$path),d=a.$excludedFields;u.forEach($=>{if(d?.includes($)||f.length>0&&!f.includes($))return;let g=p.dataFields?.find(y=>y.path===$);if(g?.default){let y=Le({currentThing:c,fieldSchema:g,mandatoryDependencies:!0});c[$]=y;}else if(c[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),d&&d.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete c[$];});}}})))(r):void 0;var Dr=e=>{let{queries:t,schema:r}=e;return t.map(i=>li({query:i,schema:r}))},li=e=>{let{query:t,schema:r}=e;if(t.$fields.length===0)return null;let i=[];i.push("SELECT");let o=pt({queries:t.$fields,level:1,schema:r});o&&i.push(o);let n=t.$filter&&Rr(t.$filter,0)||[];return i.push(...n),i.push(`FROM ${t.$thing}`),i.join(`
37
+ `)},pt=e=>{let{queries:t,schema:r,level:i}=e,o=[];return t.forEach(n=>{let l=ci({query:n,level:i,schema:r});l&&o.push(l);}),o.length===0?null:o.join(`,
38
+ `)},ci=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?di({query:t,level:i}):t.$fieldType==="link"?hi({query:t,level:i,schema:r}):t.$fieldType==="role"?ui({query:t,level:i,schema:r}):null},di=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?b(`meta::id(\`${t.$path}\`) AS ${t.$as}`,r):t.$path===t.$as?b(`\`${t.$path}\``,r):b(`\`${t.$path}\` AS \`${t.$as}\``,r)},hi=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(b("(",i));let n=i+1;o.push(b("SELECT",n));let l=n+1,s=pt({queries:t.$fields,level:l,schema:r});s&&o.push(s);let c=[t.$playedBy.thing,...Cr(r,t.$playedBy.thingType,t.$playedBy.thing)],p;return t.$target==="relation"?p=c.map(u=>`<-\`${t.$playedBy.thing}_${t.$plays}\`<-\`${u}\``).join(", "):p=c.map(u=>`<-\`${t.$playedBy.relation}_${t.$plays}\`<-\`${t.$playedBy.relation}\`->\`${t.$playedBy.relation}_${t.$playedBy.plays}\`->\`${u}\``).join(", "),o.push(b(`FROM ${p}`,n)),o.push(b(`) AS \`${t.$as}\``,i)),o.join(`
39
+ `)},ui=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(b("(",i));let n=i+1;o.push(b("SELECT",n));let l=n+1,s=pt({queries:t.$fields,level:l,schema:r});s&&o.push(s);let p=[t.$playedBy.thing,...Cr(r,t.$thingType,t.$thing)].map(u=>`->\`${t.$playedBy.relation}_${t.$playedBy.plays}\`->\`${u}\``).join(", ");return o.push(b(`FROM ${p}`,n)),t.$filter&&o.push(...Rr(t.$filter,n)),o.push(b(`) AS \`${t.$as}\``,i)),o.join(`
40
+ `)},Rr=(e,t)=>{let r=[],{$not:i,...o}=e,n=t+1;Object.entries(o).forEach(([c,p])=>{r.push(b(`${c}=${JSON.stringify(p)}`,n));}),i&&Object.entries(i).forEach(([c,p])=>{r.push(`${c}!=${JSON.stringify(p)}`);});let[l,...s]=r;return l?[b("WHERE (",t),b(l,n),...s.map(c=>b(`AND ${c}`,n)),b(")",t)]:r},Cr=(e,t,r)=>{let i=Sr(e,t,r),o=0;for(;i[o];)i.push(...Sr(e,t,i[o])),o++;return i},Sr=(e,t,r)=>Object.values(t==="entity"?e.entities:e.relations).filter(o=>o.extends===r).map(o=>o.name);var Ar=async e=>{let{client:t,queries:r}=e;return await Promise.all(r.map(i=>t.query(i)))};var Ir=e=>{let{res:t,queries:r}=e;return t.map((i,o)=>Pr(r[o],i))},Pr=(e,t)=>t.map(r=>qr(e,r)),qr=(e,t)=>{let r={};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=pi(i,n));}),r},pi=(e,t)=>e.$fieldType==="data"?t??null:e.$justId?e.$filterByUnique?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique?qr(e,t[0]):Pr(e,t);var ft=H("error","error",V((e,t)=>({...e,error:t.error}))),fi=Be("build",{build:Z(async e=>Dr({queries:e.bql.queries,schema:e.schema}),H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),ft),run:Z(async e=>Ar({client:e.client,queries:oe(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),ft),parse:Z(async e=>Ir({res:oe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),H("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),ft),success:ce(),error:ce()},e=>e),$i=async e=>new Promise((t,r)=>{fe(fi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Or=async(e,t,r,i)=>$i({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var $t="___",xr=async e=>{let{queries:t,schema:r}=e;return t.map(i=>mi({query:i,schema:r}))},mi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:c,$limit:p}=t;if(!i)throw new Error("Path is not defined");let u=[],h=t[ue];if(u.push("match"),u.push(`$${i} isa ${o};`),n){let d=Bt({$filter:n,$var:i,$thing:o,schema:r,depth:0});u.push(`
41
+ ${d}`);}let a=Et({schema:r,$thing:o,$var:i,$sort:s,depth:0});a&&u.push(a.match);let f=`M_${v4()}`;if(u.push(`?queryPath${f} = "${h}";`),u.push("fetch"),u.push(`?queryPath${f} as "queryPath";`),l){let d=l.filter(y=>y.$fieldType==="data");d&&d.length>0&&u.push(...mt(d,i,0));let $=l.filter(y=>y.$fieldType==="link");$&&$.length>0&&u.push(...gt($,i,i,0,r));let g=l.filter(y=>y.$fieldType==="role");g&&g.length>0&&u.push(...yt(g,i,i,0,r));}return a&&u.push(a.sort),typeof c=="number"&&u.push(`
42
+ offset ${c};`),typeof p=="number"&&u.push(`
43
+ limit ${p};`),u.join(`
44
+ `)},mt=(e,t,r)=>{let i=[],o=[];for(let p=0;p<e.length;p++)e[p].$isVirtual||i.push(e[p].$dbPath),o.push(`{${e[p].$dbPath}:${e[p].$as}}`);let n=i.join(", "),s=`$metadata:{as:[${o.join(",")}]}`;return [b(`$${t} as "${t}.${s}.$dataFields": ${n};`,r)]},yt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:h,$filterByUnique:a,$thing:f,$sort:d,$offset:$,$limit:g}=s,y=s[ue],w=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${h},filterByUnique:${a}}`;l.push(b(`"${r}.${w}.${s.$var}": {`,i)),l.push(b("match",n));let T=`${t}${$t}${s.$var}`;l.push(b(`$${T} isa ${s.$thing};`,n)),l.push(b(`$${t} (${s.$var}: $${t}${$t}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter&&l.push(Bt({$filter:s.$filter,$var:T,$thing:s.$thing,schema:o,depth:n}));let m=Et({schema:o,$thing:f,$var:T,$sort:d,depth:n});if(m&&l.push(m.match),c){let D=`M_${v4()}`;l.push(b(`
45
+ ?queryPath${D} = "${y}";`,n)),l.push(b("fetch",n)),l.push(b(`?queryPath${D} as "queryPath";`,n));let R=c?.filter(j=>j.$fieldType==="data");R&&R.length>0&&l.push(...mt(R,T,n));let A=c?.filter(j=>j.$fieldType==="link");A&&A.length>0&&l.push(...gt(A,T,`${t}.${s.$var}`,n,o));let x=c?.filter(j=>j.$fieldType==="role");x&&x.length>0&&l.push(...yt(x,T,`${t}.${s.$var}`,n,o));}m&&l.push(m.sort),typeof $=="number"&&l.push(b(`offset ${$};`,n)),typeof g=="number"&&l.push(b(`limit ${g};`,n)),l.push(b("};",i));}return l},gt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:h,$filterByUnique:a,$playedBy:f,$thing:d,$sort:$,$offset:g,$limit:y}=s,w=s[ue],T=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${h},filterByUnique:${a}}`;l.push(b(`"${r}.${T}.${s.$var}": {`,i)),l.push(b("match",n));let m=`${t}${$t}${s.$var}`;l.push(b(`$${m} isa ${s.$thing};`,n)),s.$filter&&l.push(Bt({$filter:s.$filter,$var:m,$thing:s.$thing,schema:o,depth:n}));let D=Et({schema:o,$thing:d,$var:m,$sort:$,depth:n});if(D&&l.push(D.match),s.$target==="role"?l.push(b(`$${t}_intermediary (${s.$plays}: $${t}, ${f.plays}: $${m}) isa ${s.$intermediary};`,n)):l.push(b(`$${m} (${s.$plays}: $${t});`,n)),c){let R=`M_${v4()}`;l.push(b(`?queryPath${R} = "${w}";`,n)),l.push(b("fetch",n)),l.push(b(`?queryPath${R} as "queryPath";`,n));let A=c?.filter(N=>N.$fieldType==="data");A&&A.length>0&&l.push(...mt(A,m,n));let x=c?.filter(N=>N.$fieldType==="link");x&&x.length>0&&l.push(...gt(x,m,`${t}.${s.$var}`,n,o));let j=c?.filter(N=>N.$fieldType==="role");j&&j.length>0&&l.push(...yt(j,m,`${t}.${s.$var}`,n,o));}D&&l.push(D.sort),typeof g=="number"&&l.push(b(`offset ${g};`,n)),typeof y=="number"&&l.push(b(`limit ${y};`,n)),l.push(b("};",i));}return l},Bt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,{$not:l,...s}=t,c=ee(o,i),p=[];return Object.entries(l||{}).forEach(([u,h])=>{if(c.dataFields?.find(d=>d.dbPath===u)){h===null?p.push(b(`$${r} has ${u} $${u}_${v4()};`,n)):Array.isArray(h)?h.forEach(d=>{p.push(b(`not { $${r} has ${u} ${ne(d)}; };`,n));}):p.push(b(`not { $${r} has ${u} ${ne(h)}; };`,n));return}let f=c.linkFields?.find(d=>d.path===u);if(f){let[d]=f.oppositeLinkFieldsPlayedBy,g=ee(o,d.thing).idFields?.[0];if(!g)throw new Error(`"${d.thing}" does not have an id field`);if(f.target==="relation")h===null?p.push(b(`(${f.plays}: $${r}) isa ${f.relation};`,n)):Array.isArray(h)?h.forEach(y=>{p.push(b(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(y)}; };`,n));}):p.push(b(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(h)}; };`,n));else {let y=`${d.thing}_${v4()}`;h===null?p.push(b(`$${y} isa ${d.thing}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation};`,n)):Array.isArray(h)?h.forEach(w=>{p.push(b(`not { $${y} isa ${d.thing}, has ${g} ${ne(w)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation}; };`,n));}):p.push(b(`not { $${y} isa ${d.thing}, has ${g} ${ne(h)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation}; };`,n));}return}if(c.thingType==="relation"){let d=c.roles[u];if(d){let[$]=d.playedBy||[],y=ee(o,$.thing).idFields?.[0];if(!y)throw new Error(`"${$.thing}" does not have an id field`);let w=`${$.thing}_${v4()}`,T=v4(),m=`${r}_${T}`;h===null?(p.push(b(`$${m} isa ${i};`,n)),p.push(b(`$${m} (${$.plays}: ${w});`,n)),p.push(b(`$${r} is $${m};`,n))):Array.isArray(h)?h.forEach(D=>{p.push(b(`$${m} isa ${i};`,n)),p.push(b(`not { $${w} isa ${$.thing}, has ${y} ${ne(D)}; $${m} (${$.plays}: $${w}); };`,n)),p.push(b(`$${r} is $${m};`,n));}):(p.push(b(`$${m} isa ${i};`,n)),p.push(b(`not { $${w} isa ${$.thing}, has ${y} ${ne(h)}; $${m} (${$.plays}: $${w}); };`,n)),p.push(b(`$${r} is $${m};`,n)));return}}}),Object.entries(s).forEach(([u,h])=>{if(c.dataFields?.find(d=>d.dbPath===u)){if(h===null)p.push(b(`not { $${r} has ${u} $${u}_${v4()}; };`,n));else if(Array.isArray(h)){let d=h.map(g=>`$${r} has ${u} ${ne(g)};`),$=Ve(d);$&&p.push(b($,n));}else p.push(b(`$${r} has ${u} ${ne(h)};`,n));return}let f=c.linkFields?.find(d=>d.path===u);if(f){let[d]=f.oppositeLinkFieldsPlayedBy,g=ee(o,d.thing).idFields?.[0];if(!g)throw new Error(`"${d.thing}" does not have an id field`);if(f.target==="relation")if(h===null)p.push(b(`not { (${f.plays}: $${r}) isa ${f.relation}; };`,n));else if(Array.isArray(h)){let y=h.map(T=>`(${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(T)};`),w=Ve(y);w&&p.push(b(w,n));}else p.push(b(`(${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(h)};`,n));else {let y=`${d.thing}_${v4()}`;if(h===null)p.push(b(`not { $${y} isa ${d.thing}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation}; };`,n));else if(Array.isArray(h)){let w=h.map(m=>`$${y} isa ${d.thing}, has ${g} ${ne(m)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation};`),T=Ve(w);T&&p.push(b(T,n));}else p.push(b(`$${y} isa ${d.thing}, has ${g} ${ne(h)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation};`,n));}return}if(c.thingType==="relation"){let d=c.roles[u];if(d){let[$]=d.playedBy||[],y=ee(o,$.thing).idFields?.[0];if(!y)throw new Error(`"${$.thing}" does not have an id field`);let w=`${$.thing}_${v4()}`,T=v4(),m=`${r}_${T}`;if(h===null)p.push(b(`$${m} isa ${i};`,n)),p.push(b(`not { $${m} (${$.plays}: ${w}); };`,n)),p.push(b(`$${r} is $${m};`,n));else if(Array.isArray(h)){let D=h.map(A=>`$${w} isa ${$.thing}, has ${y} ${ne(A)}; $${m} (${$.plays}: $${w});`),R=Ve(D);R&&(p.push(b(`$${m} isa ${i};`,n)),p.push(b(R,n)),p.push(b(`$${r} is $${m};`,n)));}else p.push(b(`$${m} isa ${i};`,n)),p.push(b(`$${w} isa ${$.thing}, has ${y} ${ne(h)}; $${m} (${$.plays}: $${w});`,n)),p.push(b(`$${r} is $${m};`,n));return}}throw new Error(`"${i}" does not have property "${u}"`)}),p.join(`
46
+ `)},Ve=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ne=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:`${e}`,yi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Et=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=ee(i,r),s=[],c=[];if(o?.forEach(p=>{let u=yi(p),h=l.dataFields?.find(d=>d.path===u.field);if(!h)throw new Error(`"${r}" does not have data field "${u.field}"`);let a=`${u.field}_${v4()}`;s.push(b("{",n)),s.push(b(`$${t} has ${h.dbPath} $${a}_1;`,n+1)),s.push(b("not {",n+1)),s.push(b(`$${t} has ${h.dbPath} $${a}_2;`,n+2)),s.push(b(`$${a}_2 < $${a}_1;`,n+2)),s.push(b("};",n+1)),s.push(b(`?${a}_ = $${a}_1;`,n+1)),s.push(b("} or {",n)),s.push(b(`not { $${t} has ${h.dbPath} $${a}_1; };`,n+1)),s.push(b(`?${a}_ = "~";`,n+1)),s.push(b("};",n)),s.push(b(`?${a} = ?${a}_;`,n));let f=u.desc?"desc":"asc";c.push(`?${a} ${f}`);}),s.length!==0)return {match:s.join(""),sort:b(`sort ${c.join(", ")};`,n)}};var Nr=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let c=r[s],p=t[s];return Bi(l,c,p,i,o)})},Bi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?jr(e[0],t,i,o):e.map(n=>jr(n,t,i,o)),jr=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:c}=Ft(e,r),p=bt(o,n,i),u=Qt(l,r,i),h=wt(s,r,i),a=t?.$fields?.every(d=>!n?.idFields?.includes(typeof d=="string"?d:d.$path));return {...u,...h,...c,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...a?Object.fromEntries(Object.entries(p).filter(([d])=>!n?.idFields?.includes(d))):p}},Ft=(e,t)=>{let r=Object.keys(e),i=r.find(a=>a.endsWith(".$dataFields"));if(!i)throw new Error("No datafields");let o=e[i],n=i.split(".")[i.split(".").length-2];if(o.$metaData=n,o.length===0)throw new Error("No datafields");let l=o.type,s={$thing:l.label,$thingType:l.root,[ue]:e.queryPath.value},c={[`$${s.$thingType}`]:s.$thing},p=O(t,c),u=r.filter(a=>{let f=oe(a.split(".").pop());return !a.endsWith(".$dataFields")&&p.linkFields?.some(d=>d.path===f)}).map(a=>{let f=oe(a.split(".").pop()),d=oe(p.linkFields?.find($=>$.path===f));return {$linkFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:d.cardinality}}),h=r.filter(a=>{let f=a.split(".").pop();return f&&!a.endsWith(".$dataFields")&&p.thingType==="relation"&&p.roles?.[f]}).map(a=>{let f=oe(a.split(".").pop());return {$roleFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:p.roles[f].cardinality}});return {dataFields:o,schemaValue:s,currentSchema:p,linkFields:u,roleFields:h}},bt=(e,t,r)=>{let{$metaData:i}=e,{as:o}=Ei(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let c=t.dataFields?.find(a=>a.path===l||a.dbPath===l),p=l==="id",u=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,h;if(c?.cardinality==="ONE"){if(h=s[0]?s[0].value:r.query?.returnNulls?null:void 0,c.contentType==="DATE"?h=h&&`${h}Z`:c.contentType==="JSON"&&(h=h&&JSON.parse(h)),p)return [[u,h],["$id",h]].filter(([a,f])=>f!==void 0)}else if(c?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[u,null]]:[];c.contentType==="DATE"?h=s.map(a=>`${a.value}Z`):c.contentType==="JSON"?h=s.map(a=>a.value&&JSON.parse(a.value)):h=s.map(a=>a.value);}return [[u,h]].filter(([a,f])=>f!==void 0)}).flat();return Object.fromEntries([...n])},wt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:c,justId:p,idNotIncluded:u,filterByUnique:h}=_r(l);if(c===null)return;let a=n.map(f=>{let{dataFields:d,currentSchema:$,linkFields:g,roleFields:y,schemaValue:w}=Ft(f,t),T=bt(d,$,r);if(p==="T")return T.id;{let m=Qt(g,t,r),D=wt(y,t,r),R={...T};return u==="true"&&$?.idFields?.forEach(A=>delete R[A]),{...R,...m,...D,...w}}});a.length>0?i[c]=s==="MANY"&&h==="false"?a:a[0]:r.query?.returnNulls&&(i[c]=null);}),i},Qt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:c,justId:p,idNotIncluded:u,filterByUnique:h}=_r(l);if(c===null)return;let a=n.map(f=>{let{dataFields:d,currentSchema:$,linkFields:g,roleFields:y,schemaValue:w}=Ft(f,t),T=bt(d,$,r);if(p==="T")return T.id;{let m=Qt(g,t,r),D=wt(y,t,r),R={...T};return u==="true"&&$.idFields?.forEach(A=>delete R[A]),{...R,...m,...D,...w}}});i[c]=a.length>0?s==="MANY"&&h==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},_r=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),c=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:c?c[1]:null}},Ei=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,c)=>/^{.*}$/.test(c)?`:${c}`:`:${s}"${c}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(c=>c.trim().startsWith("{")&&c.trim().endsWith("}")?c.trim():`"${c.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var zr=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ne(r,i),l=await n.transaction(TransactionType.READ,o);if(!l)throw new Error("Can't create transaction");return await parallel(t.length,t,async c=>await l.query.fetch(c).collect())};var Qi=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Mi=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ti=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Mt=H("error","error",V((e,t)=>({...e,error:t.error}))),Li=Be("build",{build:Z(async e=>xr({queries:e.bql.queries,schema:e.schema}),H("done","run",V(Mi)),Mt),run:Z(async e=>zr({dbHandles:e.handles,tqlRequest:oe(e.tql.queries),config:e.config}),H("done","parse",V(Ti)),Mt),parse:Z(async e=>Nr({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:oe(e.tql.res)}),H("done","success",V(Qi)),Mt),success:ce(),error:ce()},e=>e),ki=async e=>new Promise((t,r)=>{fe(Li,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Wr=async(e,t,r,i,o)=>ki({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var Si=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Tt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,He=H("error","error",V((e,t)=>({...e,error:t.error}))),Di=Be("enrich",{enrich:Z(async e=>Lr(e.bql.raw,e.schema),H("done","adapter",V(Si)),He),adapter:Z(async e=>{let t={};e.bql.queries?.forEach((s,c)=>{let p=e.bql.raw[c],u=ee(e.schema,s.$thing),{id:h}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[h]){let f=e.handles.typeDB?.get(h)?.client;if(!f)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[h]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[h]){let f=e.handles.surrealDB?.get(h)?.client;if(!f)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[h]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let a=t[h];a.rawBql.push(p),a.bqlQueries.push(s),a.indices.push(c);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?Wr(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):Or(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,c)=>{let p=o[c];return s.indices.map((u,h)=>({index:u,result:p[h]}))});return n.sort((s,c)=>s.index<c.index?-1:s.index>c.index?1:0),n.map(({result:s})=>s)},H("done","postHooks",V(Tt)),He),postHooks:Z(async e=>kr(e.schema,oe(e.bql.queries),oe(e.bql.res)),H("done","clean",V(Tt)),He),clean:Z(async e=>wr(e.config,oe(e.bql.res)),H("done","success",V(Tt)),He),success:ce(),error:ce()},e=>e),Ri=async e=>new Promise((t,r)=>{fe(Di,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),De=async(e,t,r,i)=>Ri({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Lt="___",Ci=Symbol.for("grandChildOfCreate"),Vr=async(e,t,r,i)=>{let o=(B,Q)=>Object.keys(B).filter(F=>!F.startsWith("$")&&B[F]!==void 0?Q?!O(t,B).dataFields?.find(M=>M.path===F):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(traverse(e,({parent:B,key:Q,value:F})=>{B&&Q&&!Q.includes("$")&&isObject(B)?(Array.isArray(B[Q])?B[Q]:[B[Q]]).forEach(M=>{if(isObject(M)){if(B.$op!=="create")n.includes(M.$op)||n.push(M.$op);else if(M.$op==="delete"||M.$op==="unlink")throw new Error(`Cannot ${M.$op} under a create`)}}):!B&&isObject(F)&&(n.includes(F.$op)||n.push(F.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(B=>{let Q=(F,E)=>{let M=[],L={},P=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...P];for(let q in F)if(!P.includes(q)&&!(k.includes(q)&&!E))if(!q.includes("$")&&(isObject(F[q])||Array.isArray(F[q]))){let v=F[q];if(Array.isArray(v)&&v.length>0)v.forEach(ae=>{let Fe={$path:q,...Q(ae),...ae.$filter&&{$as:ae.$bzId}};M.find(U=>U.$path===Fe.$path&&!U.$filter)||(M=[...M,Fe]);});else {let ae={$path:q,...Q(v),...!v.$filter&&{$as:v.$bzId}};M=[...M,ae];}}else L[q]=F[q];return {...L,$fields:M}};return B.map(F=>Q(F,!0))})(Array.isArray(e)?e:[e]),p=(await De(s,t,r,i)).bql.res,u=(B,Q)=>{let F=B.$id||B.id||B.$bzId;if(B.$objectPath){let{$objectPath:E}=B,M=E?.beforePath||"root",L=Array.isArray(E.ids)?`[${E.ids}]`:E.ids;return {beforePath:`${M}.${L}___${E.key}`,ids:F,key:Q}}else return {beforePath:"root",ids:F,key:Q}},h=(B,Q)=>{let F=B?.beforePath||"root",E=(Array.isArray(B?.ids)?`[${B?.ids}]`:B?.ids);return `${F}.${E}___${B?.key}`},a=B=>{if(B.includes("[")&&B.includes("]")){let[Q,F,E]=B.split(/[[\]]/);return F.split(",").map(L=>`${Q}${L}${E}`)}else return [B]},f={};(B=>produce(B,Q=>traverse(Q,F=>{let{key:E,parent:M}=F;if(M&&E&&M.$id&&!E.includes("$")){let L=u(M,E),P=h(L);if(Array.isArray(M[E])){let k=[];M[E].forEach(q=>{isObject(q)?(q.$objectPath=L,k.push(q.$id.toString())):q&&k.push(q.toString());}),f[P]={$objectPath:L,$ids:k};}else {let k=M[E];isObject(k)?(f[P]={$objectPath:L,$ids:[k.$id.toString()]},k.$objectPath=L):k&&(f[P]={$objectPath:L,$ids:[k.toString()]});}}})))(p||{});let $=B=>produce(B,Q=>traverse(Q,F=>{let{key:E,value:M,parent:L}=F;L&&E&&!E.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(L)&&(Array.isArray(L[E])?L[E].forEach(P=>{typeof P!="string"&&(P.$objectPath=u(L,E),P.$parentIsCreate=L.$op==="create",P[Ci]=L.$parentIsCreate||L[Symbol.for("grandChildOfCreate")]);}):isObject(L[E])&&(L[E].$parentIsCreate=L.$op==="create",L[E][Symbol.for("grandChildOfCreate")]=L.$parentIsCreate||L[Symbol.for("grandChildOfCreate")],L[E].$objectPath=u(L,E)));})),g=$(e),y=B=>{let Q=[];return B.forEach(E=>{if(!E.$id&&!E.id&&!E.$tempId)if(E.$filter){let M=h({...E.$objectPath,key:E.$bzId}),L=f[M];L&&(Array.isArray(L.$ids)?L.$ids:[L.$ids]).forEach(k=>{let q={...E,$id:k,$bzId:`T4_${v4()}`,$filterBzId:E.$bzId};Q.push(q);});}else {let M=h(E.$objectPath),L=f[M];L?L?.$ids.forEach(P=>{let k={...E,$id:P,$bzId:`T4_${v4()}`};Q.push(k);}):Q.push(E);}else Q.push(E);}),Q.map(E=>{let M={...E};return o(M,!0).forEach(L=>{let P=Array.isArray(M[L])?M[L]:[M[L]],k=y(P);M[L]=k;}),M})},w=y(Array.isArray(g)?g:[g]),T=$(w),D=(B=>{let Q=F=>{let E=U=>{let X=[],z=[],I=[];return U.forEach(W=>{let ie=o(W,!0);if(ie.length>0){let C=!1;ie.forEach(_=>{(Array.isArray(W[_])?W[_]:[W[_]]).filter(Y=>!Y.$id&&!Y.id&&typeof W=="object").length&&(C=!0);}),C?X.push(W):z.push(W);}else I.push({...W,$bzId:W.$tempId||`T_${v4()}`});}),{operationWithMultiples:X,operationWithoutMultiples:z,otherOps:I}},{operationWithMultiples:M,operationWithoutMultiples:L,otherOps:P}=E(F),k=U=>{let z=(()=>{let _={};for(let te in U){let J=O(t,U);!te.startsWith("$")&&J.dataFields?.find(Y=>Y.path===te)&&(_[te]=U[te]);}return _})(),I=Object.keys(U),W=o(U,!0),ie=[],C=(_,te)=>{if(_===W.length){let Y={...te};I.forEach(re=>{re.startsWith("$")&&(Y[re]=U[re]);}),ie.push({...Y,...z});return}let J={...te,[W[_]]:U[W[_]],...me(te),...z};C(_+1,J),C(_+1,te);};return C(0,{...me(U)}),ie},q=[];return M.forEach(U=>{let X=k(U),z=[];X.forEach(I=>{let W=o(I,!0);if(I.$op==="create")z.push(I);else if(I.$id){let ie=h(I.$objectPath),C=[];if(W.forEach(_=>{let te=`${ie.includes("undefined")?"root":ie}.${I.$id}${Lt}${_}`,J=f[te];I[_].filter(re=>re.$op==="unlink"||re.$op==="delete"||re.$op==="update").length>0?J&&C.push({key:_,ids:J.$ids}):C.push({key:_,ids:[""]});}),C.length===W.length&&!z.find(_=>_.$id===I.$id))z.push(I);else {let _={...I,$bzId:I.$tempId||`T4_${v4()}`};W.forEach(J=>{let Y=I[J].filter(re=>re.$id);Y.length>0?_[J]=Y:_[J]=void 0;}),o(_,!0).length>0&&z.push(_);}}else if(I.$objectPath){let ie=h(I.$objectPath),C=f[ie]?.$ids||[];C.forEach(_=>{let te=[];W.forEach(J=>{let Y=`${ie}.${_}${Lt}${J}`,re=f[Y];re&&te.push({key:J,ids:re.$ids});}),W.length===0?C.filter(Y=>!z.find(re=>re.$id===Y)).forEach(Y=>{z.push({...I,$id:Y,$bzId:I.$tempId||`T_${v4()}`});}):te.length===W.length&&!z.find(J=>J.$id===_)&&(W.forEach(J=>{let Y=`${h(I.$objectPath)}.${_}${Lt}${J}`,{$ids:re}=f[Y],on=I[J].find(Qe=>!Qe.$id),sn=[...re.map(Qe=>({...on,$id:Qe,$objectPath:{beforePath:I.$objectPath,ids:Qe,key:J}})),...I[J].filter(Qe=>Qe.$id)];I[J]=sn;}),z.push({...I,$id:_,$bzId:I.$tempId||`T_${v4()}`}));});}else z.push(I);}),z.forEach(I=>{q.push(I);});}),[...q,...L,...P].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let X={...U};return o(X,!0).forEach(z=>{let I=Array.isArray(X[z])?X[z]:[X[z]],W=Q(I);X[z]=W;}),X})};return Q(B)})(Array.isArray(T)?T:[T]),R=B=>B.map(Q=>{let F=o(Q,!0),E={...Q};return F.forEach(M=>{let L=Array.isArray(Q[M])?Q[M]:[Q[M]],P=[],k=[],q=[],v={},ae=Xe(t,Q,M);L.filter(C=>C).forEach(C=>{C.$op==="replace"&&C.$id?(v=C,Array.isArray(C.$id)?k=[...k,...C.$id]:k.push(C.$id)):C.$op==="create"&&ae==="ONE"&&C.id?(v=C,Array.isArray(C.id)?q=[...k,...C.id]:q.push(C.id)):P.push(C);});let Fe=h(v.$objectPath),X=a(Fe).map(C=>f[C]),z=[];X.filter(C=>C!=null).forEach(C=>{z=[...z,...C.$ids];});let I=z.filter(C=>!k.includes(C)),W=k.filter(C=>!z.includes(C)),ie=me(v);I.length>0&&P.push({...v,$op:"unlink",$id:I,$bzId:v.$tempId||`T4_${v4()}`,id:void 0,...ie}),W.length>0&&W.forEach(C=>{P.push({...v,$op:"link",$id:C,$bzId:v.$tempId||`T5_${v4()}`,...ie});}),q.length>0&&q.forEach(C=>{P.push({...v,$op:"create",id:C,$bzId:v.$tempId||`T6_${v4()}`,...ie});}),E[M]=R(P);}),E}),A=$(R($(D)));(B=>produce(B,Q=>traverse(Q,F=>{let{key:E,value:M,parent:L}=F;E&&L&&!E?.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(L)&&(Array.isArray(M)?M:[M]).forEach(k=>{let q=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,v=h(q),ae=f[v],Fe=(z,I)=>z.every(W=>I.includes(W)),U=k.$id?Array.isArray(k.$id)?Fe(k.$id,ae?ae.$ids:[]):ae?.$ids.includes(k.$id):ae,X=Xe(t,L,k.$objectPath.key);if(k.$op==="link"&&U&&X==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${h(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${L.$id}"`);break;}});})))(A);let N=(B=>produce(B,Q=>traverse(Q,F=>{let{value:E,meta:M}=F;isObject(E)&&(E[Symbol.for("path")]=M.nodePath,delete E.$objectPath,delete E.$parentIsCreate);})))(A);return [...Array.isArray(N)?N:[N]].sort((B,Q)=>B.$op==="create"&&Q.$op!=="create"?-1:B.$op!=="create"&&Q.$op==="create"?1:0)};var Hr=(e,t)=>produce(e,i=>Ue(t,i)),Ue=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>Ue(e,o,r));return}let i=ee(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||Ii(e,t,o,i);});},Ii=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;Ue(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[c]=s.playedBy||[];if(!c)throw new Error(`Role ${s.name} in ${i} is not played by anything`);Ue(e,o,c.thing);}};var Jr=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(c=>kt(c,!0)),s=(await De(n,t,r,i)).bql.res;return o.map((c,p)=>{let u=ee(t,c.$thing);return Yr({mut:c,node:s[p],schema:t,thing:u})})},Zr=new Set(["$op","$bzId","$parentKey"]),qi=new Set(["$relation","$entity","$id",...Zr]),kt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(Zr.has(o)||qi.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...kt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...kt(n,!1)});}return i.$fields=Object.values(r),i},Yr=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=Xr(o),l=xi(r);if(Array.isArray(t))return t.map(c=>{let p=l[c.$id];return p?Kr({mut:c,node:p,schema:i,thing:o,...n}):c});let s=l[t.$id];return Kr({mut:t,node:s,schema:i,thing:o,...n})},Kr=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:c,...p}=t;if(!r)return p;let u=Gr({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),h={...p,[Te]:u};for(let a in t){if(a.startsWith("$"))continue;let f=t[a];if(n[a]||!f||typeof f!="object"){h[a]=f;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let g=ee(i,$);h[a]=Yr({mut:f,schema:i,node:r[a],thing:g});}return h},Gr=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,c=t||Oi(o),p={$id:r.$id};return c.forEach(u=>{let h=typeof u!="string",a=h?u.$path:u,f=r[a];if(n[a]){p[a]=f;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!h){f&&(p[a]=Array.isArray(f)?f.map(Ur):Ur(f));return}let g=ee(i,$),y=Xr(g);p[a]=Array.isArray(f)?f.map(w=>vr({...y,$fields:u.$fields,value:w,schema:i,thing:g})):vr({...y,$fields:u.$fields,value:f,schema:i,thing:g});}),p},Oi=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},Ur=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},vr=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return Gr({...e,node:t})},Xr=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},xi=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var en=ce,Re=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,ji=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ni=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),_i=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),zi=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Wi=async e=>Object.keys(e.bql.current).length?ot(e.bql.current,e.schema,e.config):ot(e.bql.raw,e.schema,e.config),Vi=async e=>Vr(e.bql.current,e.schema,e.config,e.handles),Hi=async e=>Jr(e.bql.current,e.schema,e.config,e.handles),Ki=async e=>sr(e.bql.current,e.schema),Ui=async e=>ar(e.bql.things,e.bql.edges,e.schema),vi=async e=>er(e.typeDB.tqlMutation,e.handles,e.config),Ji=async e=>tr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Zi=()=>!0,Yi=e=>ke(e.bql.current),Ee=H("error","error",V((e,t)=>({...e,error:t.error}))),Gi=Be("stringify",{stringify:Z(async e=>Hr(e.bql.raw,e.schema),H("done","enrich",V(Re)),Ee),enrich:Z(Wi,H("done","preQuery",at(Zi),V(Re)),H("done","parseBQL",V(Re)),Ee),preHookDependencies:Z(Hi,H("done","enrich",V(Re)),Ee),preQuery:Z(Vi,H("done","preHookDependencies",at(Yi),V(Re)),H("done","parseBQL",V(Re)),Ee),parseBQL:Z(Ki,H("done","buildMutation",V(Ni)),Ee),buildMutation:Z(Ui,H("done","runMutation",V(_i)),Ee),runMutation:Z(vi,H("done","parseMutation",V(zi)),Ee),parseMutation:Z(Ji,H("done","success",V(ji)),Ee),success:en(),error:en()},e=>e),Xi=async e=>new Promise((t,r)=>{fe(Gi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),tn=async(e,t,r,i)=>Xi({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var St=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="surrealDB"){let o=new Surreal;await o.connect(i.url),await o.signin({namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let[o,n]=await tryit(TypeDB.cloudDriver)(i.addresses,i.credentials);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}}));let r=Ot(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),Rt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...Je.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await tryit(De)(n,this.schema,i,this.dbHandles);if(l){let p=new Error(l.error);throw p.stack=l.error.stack,p}let c=s.bql.res;return o?c:c[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...Je.mutation,...this.config.mutation,...r}},[o,n]=await tryit(tn)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Wl=St;//! Todo: delete when this works with the new $thing and $thingType fields
76
47
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
77
48
  //! Todo: Sandbox the function in computeFunction()
78
49
  //! reads all the insertions and gets the first match. This means each id must be unique
79
50
  //!old
80
51
 
81
- export { Zc as default };
52
+ export { Wl as default };