@blitznocode/blitz-orm 0.10.28 → 0.10.30

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
@@ -3,12 +3,12 @@ import { TypeDBOptions, TransactionType, SessionType, TypeDB, TypeDBCredential }
3
3
  import { Surreal } from 'surrealdb.js';
4
4
  import { enableMapSet, produce, isDraft, current } from 'immer';
5
5
  import { traverse, getNodeByPath } from 'object-traversal';
6
+ import { nanoid } from 'nanoid';
6
7
  import { v4 } from 'uuid';
7
8
  import { isSet } from 'util/types';
8
- import { nanoid } from 'nanoid';
9
9
  import 'acorn';
10
10
 
11
- var ct={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var In=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},Zt=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
11
+ var ct={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var kn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,c=`${o}-${n}`;r.has(c)||(r.set(c,!0),t.push(i));}),t},Zt=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
12
12
  `,Object.keys(t.entities).forEach(g=>{let S=t.entities[g],{idFields:C,dataFields:A,linkFields:O,name:x}=S,W=[],le=[],K=[];if("extends"in S){let F=t.entities[S.extends];F.dataFields&&F.dataFields.forEach(Q=>{W.push(Q.dbPath);}),F.linkFields&&F.linkFields.forEach(Q=>{le.push(Q.path);}),F.idFields&&F.idFields.forEach(Q=>{K.push(Q);});}y+=`${x} sub ${"extends"in S?S.extends:"entity"},
13
13
  `;let D=[];if(C&&C.length>0){let F=new Set(C),E=Array.from(F).map(b=>`${b}`).join(", ");K.includes(E)||(y+=` owns ${E} @key,
14
14
  `,D.push(E));}if(A&&A.length>0&&A.forEach(F=>{!W.includes(F.dbPath)&&!D.includes(F.dbPath)&&(y+=` owns ${F.dbPath},
@@ -24,7 +24,7 @@ var ct={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
24
24
  `),y+=`
25
25
  `;});let B=`define
26
26
 
27
- `;return In(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
27
+ `;return kn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
28
28
  `,g.contentType==="TEXT"||g.contentType==="ID"||g.contentType==="JSON")B+=` value string;
29
29
  `;else if(g.contentType==="EMAIL")B+=` value string,
30
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,})$';
@@ -33,24 +33,24 @@ var ct={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
33
33
  `;else if(g.contentType==="NUMBER")B+=` value long;
34
34
  `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${g.contentType}" is not implemented`)}),`${B}
35
35
 
36
- ${y}`})(),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:h}]=e.dbConnectors;await(await s.databases.get(h)).delete(),await s.databases.create(h);let c=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await c.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let a=await c.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var te=Symbol.for("queryPath"),Ve=Symbol.for("stepPrint"),Se=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),Ae=Symbol.for("dbNode"),dt=Symbol.for("isTransformed"),ie=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),me=Symbol.for("suqlMetadata");var Yt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Gt=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:i})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],n=[e.relation,...o],l=`<-\`${t}_${e.plays}\`<-(\`${n.join("`,`")}\`)`;if(e.target==="relation"){if(i==="edges")return l;if(i==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[s]=e.oppositeLinkFieldsPlayedBy,h=r.entities[s.thing]?.subTypes||r.relations[s.thing]?.subTypes||[],p=[s.thing,...h],c=`->\`${t}_${s.plays}\`->(\`${p.join("`,`")}\`)`;return i==="edges"?`${l}${c}`:i==="refs"?`$parent.\`${s.plays}\``:`${l}${c}`}else throw new Error("Unsupported linkField target")};var tr=(e,t,r)=>r?t:`${e}\xB7${t}`;var nr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],We=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),ir=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:h})=>{if(h.depth===2&&(l&&(s.dataFields=s.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:tr(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. Path:${h.nodePath}`);let p=n.entities[s.extends]||n.relations[s.extends],c=[s.extends,...p.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[l,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[l,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=p.idFields?Array.from(new Set((s.idFields||[]).concat(p.idFields))):s.idFields,s.dataFields=p.dataFields?(s.dataFields||[]).concat(p.dataFields.map(d=>{let a=s.extends,f=e.entities[a]||e.relations[a];for(;!f.dataFields?.find(u=>u.path===d.path);)a="extends"in f?f.extends:void 0,f=e.entities[a]||e.relations[a];return {...d,dbPath:tr(a,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in p){let d=s,a=p;if(a.roles){let f=mapEntries(a.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...f};}}s.linkFields=p.linkFields?(s.linkFields||[]).concat(p.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,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[d,a]=s.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(l)?l.map(d=>({...d,...p})):[{...l,...p}];r.push(...c);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:h})=>{if(h.depth===2&&l.idFields&&!l.id){l.name=s;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=p();let c=Object.keys(t).find(d=>t[d]?.get(l.defaultDBConnector.id));if(l.db=c,l.dbContext=Yt[c],l.dbProviderConfig=c==="surrealDB"?t[c]?.get(l.defaultDBConnector.id)?.providerConfig:void 0,l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===s&&w.plays===a)||[];f.playedBy=u,f.path=a;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||l.name;$.length>1&&console.warn(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let S=G(e,w)?.subTypes||[];return [w,...S]}),B=()=>{if(l.dbProviderConfig.linkMode==="edges")return `->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;if(l.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.\`${a}\``;if(f.cardinality==="ONE")return `$parent.[\`${a}\`]`}throw new Error("Unsupported linkMode")};if(l.db==="surrealDB"){let w=B();f[me]={queryPath:w};}}),"linkFields"in l&&l.linkFields){let d=l;d.linkFields?.forEach(a=>{a.fieldType="linkField";let f=i.relations[a.relation];if(!a.isVirtual){if(!f)throw new Error(`The relation ${a.relation} does not exist in the schema`);if(f.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`)}if(a.target==="relation"){if(a.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${a.path}. Path:${h.nodePath}."`);a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];}if(a.target==="role"){let u=r.filter($=>$.relation===a.relation&&$.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=u,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),a.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${a.path}. Path:${h.nodePath}."`);if(a.$things=a.oppositeLinkFieldsPlayedBy.map($=>$.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${d.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map($=>$.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}if(l.db==="surrealDB"){let u=f?.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Gt({linkField:a,originalRelation:u,withExtensionsSchema:i,linkMode:l.dbProviderConfig.linkMode});a[me]={queryPath:$};}});}}if(l&&typeof l=="object"&&"playedBy"in l){let p=[...new Set(l.playedBy.map(c=>c.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${h.nodePath}, played by: ${p.join(", ")}`),l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${h.nodePath}`)}if(h.depth===4){let[p,c]=h.nodePath?.split(".")||[],d=n[p][c];!isArray(l)&&typeof l=="object"&&(l.validations&&(l.validations.required&&d.requiredFields.push(l.path),l.validations.enum&&d.enumFields.push(l.path),l.validations.fn&&d.fnValidatedFields.push(l.path)),l.default?l.isVirtual?d.virtualFields.push(l.path):d.computedFields.push(l.path):l.isVirtual&&d.virtualFields.push(l.path));}}))},G=(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`)},q=(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)}`)},Ie=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ke=(e,t)=>{let r=q(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},or=(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")},pt=(e,t,r)=>{let i=q(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;throw new Error(`Field ${r} not found in schema`)},ft=(e,t,r)=>pt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?listify(e.roles,u=>u):[],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 h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],c=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],d=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!s.includes(u)).filter(u=>u),a=t.$filter?We(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?We(t.$filter,(u,$)=>c.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:d,...p.length?{localFilters:a}:{},...c.length?{nestedFilters:f}:{}}};var sr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ar=(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):{}},Fe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ue=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=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},ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},T=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var ke=(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 lr=(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=ke(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,h=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: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: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=q(r,t),{usedDataFields:o}=ue(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 Je=(e,t,r)=>{let i=q(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var dr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Je(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:or(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ve=(e,t)=>{let r=t[Ve];return isSet(r)?r.has("clean")?(Reflect.set(t,Ve,r.add("clean")),!0):!1:(Reflect.set(t,Ve,new Set(["clean"])),!0)};var hr=(e,t,r)=>{if(ve("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(q(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Fe(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var pr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=ke(t,r),[s]=l,h=Je(e,{...n,$thing:s.thing,$thingType:s.thingType},i),c=n.$bzId?n.$bzId:n.$tempId?n.$tempId:n.$id&&!isArray(n.$id)?`SN_ONE_${s.thing}_${n.$id}`:n.$id&&isArray(n.$id)?`SN_MANY_${s.thing}_${nanoid()}`:`SM_${nanoid()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:h,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var zn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Vn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,fr=e=>{let r=e.toString().replace(zn,"").trim().split("=>")[0].split("{")[0].replace(Vn,"").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 Oe=({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=fr(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 $r=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=q(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:h}=n,p=listify(o,(a,f)=>f!==void 0?a:void 0),c=p.filter(a=>h?.includes(a));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(a=>!p.includes(a)).forEach(a=>{let f=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?nr(n.roles,(B,w)=>B===a):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Oe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Ye=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let i=`on${sr(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var yr=(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:h,dataFields:p}=q(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(c=>{if(c in n){let d=p?.find(a=>a.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(n[c]))n[c].some(a=>{if(!d.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(n[c]))throw new Error(`[Validations] Option "${n[c]}" is not a valid option for field "${c}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(c=>{if(c in n)try{let d=p?.find(a=>a.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let c=n.$thing,d=n,a=clone(pe(e)),f=clone(pe(d)),u=i.mutation?.context||{},$=clone(pe(n[Ae]||{}));Ye(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,a,u,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${c}] ${B.message}`)}}});}}});};var Er=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Ue(n)){if(n.$fields||n[dt])return n;let l=Ye(n,r).filter(d=>d.type==="transform"),s=clone(pe(e)),h=clone(pe(n)),p=i.mutation?.context||{},c=clone(pe(n[Ae]||n.$dbNode));return l.forEach(d=>{let a=d.fn(h,s,p,c||{});Object.keys(a).length!==0&&(n={...h,...a,...Fe(n),[dt]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Br=(e,t,r)=>{let i=ke(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Pe=e=>{if(Array.isArray(e)){for(let t of e)if(Pe(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"&&Pe(e[t]))return !0}return !1};var ei=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ve("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")},ti=(e,t)=>{},Et=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Pe(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:h,key:p,meta:c})=>{if(!(!h||!p)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let u=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,f=d.includes("$filter");Object.keys(a).forEach(u=>{if(ei(a,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?pt(t,a,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return ti();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[u]===null?Br(a,u,$):lr(a,u,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);dr(a,t);}let y=isArray(a[u])?a[u]:[a[u]],m=d.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$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)&&pr(a,u,$,t),hr(a,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&$r(a,u,t),(isArray(a[u])?a[u]:[a[u]]).forEach(w=>{let g=q(t,w),{unidentifiedFields:S,usedLinkFields:C,usedFields:A,fields:O}=ue(g,w);if(A.forEach(x=>{if(!O.includes(x))throw new Error(`[Schema] Field ${x} not found in the schema`)}),S.length>0)throw new Error(`Unknown fields: [${S.join(",")}] in ${JSON.stringify(s)}`);if(C.length>1){let x=g.linkFields?.filter(W=>C.includes(W.path));x?.some((W,le)=>x.some((K,D)=>{if(le!==D&&W.target!==K.target&&W.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||(Er(a,u,t,r),yr(a,u,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ge=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 Fr=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 Ge(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),h=s?await s.collect():void 0;return await o.commit(),{insertions:h}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var br=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let h=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),p=s.$thing||s.$relation||s.$entity,c=p?G(i,p):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!h&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=h?.asThing().iid,a=Object.entries(s).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(s.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return a;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...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 wr=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=c=>{let d=[],a=[],f=m=>{if(m.$id)return m.$id;let B=q(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let S=B.dataFields?.find(O=>O.path===g),C=Oe({currentThing:m,fieldSchema:S,mandatoryDependencies:!0}),A=m[g]||m.$id||C;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B),a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return traverse(c,({value:m,parent:B,meta:w})=>{if(!isObject(m))return;let g=m;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 S=q(t,g),{dataFields:C,roleFields:A,linkFields:O,usedFields:x}=ue(S,g),W=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=x.filter(E=>C?.includes(E)),F=x.filter(E=>A?.includes(E)),Q=x.filter(E=>O?.includes(E));if(D.length>0)return "update";if(F.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},le={...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,C||[""])),$op:W(),$bzId:g.$bzId};u(le);let K=g[Be];if(K?.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");d.push({...g,$op:"match"});}let D=K.relation===g.$thing,F=D?g.$bzId:`LT_${v4()}`,E=ar(c,B,w).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return D?"match":"delete";if(g.$op==="unlink")return D?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return D?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},M=q(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 k={$bzId:F,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...D?{}:{[K.path]:g.$bzId},[K.plays]:E,[Be]:K,[Se]:"linkField"};$(k),(g.$op==="unlink"||b()==="unlink")&&D&&$({$thing:K.relation,$thingType:"relation",$bzId:F,$op:"match",[K.plays]:E,[Be]:K,[Se]:"linkField"});}if(g.$thingType==="relation"){let D=We(g,(E,b)=>A.includes(E)),F=mapEntries(D,(E,b)=>isArray(b)?[E,b]:isObject(b)?[E,b.$bzId]:[E,b]),Q=We(m,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(D).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=q(t,g).roles,M=mapEntries(F,(k,L)=>{let N=b[k]?.cardinality;if(!N)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(L)){if(N==="ONE"){if(L.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,L[0].$bzId||L[0]]}return [k,L.map(J=>J.$bzId||J)]}return [k,L.$bzId||L]}),R={...Q,$thing:g.$thing,$thingType:"relation",$op:E(),...M,$bzId:g.$bzId,[Se]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){let E=0;Object.entries(D).forEach(([b,M])=>{let R=isArray(M)?M:[M],k=L=>L==="create"||L==="replace"?"link":L;R.forEach(L=>{if(!L)return;let N=k(L.$op);if(N==="replace")throw new Error("Not supported yet: replace on roleFields");if(N==="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 J={...Q,$thing:g.$thing,$thingType:"relation",$op:N==="delete"?"unlink":N,[b]:L.$bzId,$bzId:g.$bzId,[Se]:"roleField"};$(J);});});}}}}}),[d,a]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let a=c.findIndex(f=>f.$bzId===d.$bzId);if(a===-1)return [...c,d];if(c[a].$op==="create"&&d.$op==="match")return c;if(c[a].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,a),d,...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d},...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="match"||c[a].$op==="match"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d,$op:"update"},...c.slice(a+1)];if(c[a].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(c[a].$filter)===JSON.stringify(d.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[a].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${c[a].$op}. Current: ${d.$op}`)},[]),l=o.reduce((c,d)=>{let a=c.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(a){let f={...a};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...c,d]},[]);n.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&l.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(wr(c))}`)}});let s=[...n,...l],h=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),p=Array.from(h).filter(c=>!s.some(d=>d.$tempId===c&&d.$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 Bt=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var Rr=async(e,t,r)=>{let i=a=>{let f=a.$op,u=`$${a.$bzId}`,$=q(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,w=a.$id,g=y?.[0],S=listify(a,(D,F)=>{if(D.startsWith("$")||D.startsWith("%")||D===g||F===void 0||F===null)return "";let Q=$.dataFields?.find(M=>M.path===D);if(!Q?.path)return "";let b=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${b} ${F}`;if(Q.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","")}`}if(Q.contentType==="FLEX"){let M=`bza${nanoid()}`,R=isArray(F)?F.map(k=>Bt(k)):Bt(F);if(Array.isArray(R))throw new Error("Array in FLEX fields not supported yet");return `has ${b} $${M}; $${M} '${M}' isa ${b}, has ${R.type}Attribute ${R.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(D=>D),C=`${u}-atts`,A=listify(a,D=>{if(D.startsWith("$")||D.startsWith("%")||D===g)return "";let F=$.dataFields?.find(b=>b.path===D);if(!F?.path)return "";let E=F.dbPath;return `{${C} isa ${E};}`}).filter(D=>D),O=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,x=w?[`has ${g} ${O}`]:[],W=[...x,...S].filter(D=>D).join(","),le=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...x].filter(D=>D).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...x].filter(D=>D).join(",")}, has ${C};
37
- ${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...x].filter(D=>D).join(",")};`:"";if(Ue(a))return {op:f,deletionMatch:le(),insertionMatch:K(),insertion:f==="create"?`${u} isa ${[B,W].filter(D=>D).join(",")};`:f==="update"&&S.length?`${u} ${S.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&A.length?`${u} has ${C};`:""};throw new Error("in attributes")},o=a=>{let f=a.$op,u=q(r,a),$=`$${a.$bzId}`,y=a.$id,m=u.defaultDBConnector?.path||a.$thing,B="roles"in u?listify(u.roles,F=>F):[],w="roles"in u?mapEntries(u.roles,(F,Q)=>[F,Q.dbConnector?.path||F]):{},g=listify(a,(F,Q)=>{if(!B.includes(F))return null;if(!("roles"in u))throw new Error("This should have roles! ");let E=w[F];return Array.isArray(Q)?Q.map(b=>({path:E,id:b})):{path:E,id:Q}}).filter(F=>F).flat(),S=g.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),C=g.length>0?`( ${S.join(" , ")} )`:"",A=a[Se];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let O=C?`${$} ${C} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",x=`${$} ${A==="linkField"||f==="delete"?`isa ${m}`:""}`,W=()=>O?f==="link"?`${O};`:f==="create"?`${O}, has id '${y}';`:"":"",le=()=>O&&f==="match"?`${O};`:"",K=()=>O?f==="delete"?`${O};`:f==="match"?`${O};`:"":"",D=()=>O?f==="delete"?`${x};`:f==="unlink"?`${$} ${C};`:"":"";return {deletionMatch:K(),insertionMatch:le(),deletion:D(),insertion:W(),op:""}},n=(a,f)=>{let u=f==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x}=u(g);return shake({preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x},W=>!W)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w}=u(a);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],h=n(t,"edges"),p=Array.isArray(h)?h:[h],c=[...s,...p];return shake({insertionMatches:c.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:c.map(a=>a.deletionMatch).join(" ").trim(),insertions:c.map(a=>a.insertion).join(" ").trim(),deletions:c.map(a=>a.deletion).join(" ").trim()},a=>!a)};var qe={};function X(e){return {enumerable:!0,value:e}}function Cr(e){return {enumerable:!0,writable:!0,value:e}}var fi=()=>!0,Dr=()=>({}),Ir=e=>e,$i=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),mi=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),be=(e,t)=>Object.freeze(Object.create(e,t));function Ar(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function kr(e){return be(this,{fn:X(e)})}var Or={},V=kr.bind(Or);var Pr={},bt=kr.bind(Pr);function et(e,t){return t.filter(r=>e.isPrototypeOf(r))}function qr(e,t,...r){let i=Ar(et(Pr,r).map(n=>n.fn),fi,$i),o=Ar(et(Or,r).map(n=>n.fn),Ir,mi);return be(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var xr={},jr={},H=qr.bind(xr);qr.bind(jr,null);function yi(e,t,r){return Mt(t,e,r,this.immediates)||e}function Nr(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 gi={enter:Ir};function he(...e){let t=et(xr,e),r=et(jr,e),i={final:X(e.length===0),transitions:X(Nr(t))};return r.length&&(i.immediates=X(r),i.enter=X(yi)),be(gi,i)}var Ei={enter(e,t,r){let i=this.fn.call(t,t.context,r);return wt.isPrototypeOf(i)?be(Wr,{machine:X(i),transitions:X(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Wr={enter(e,t,r){if(t.child=ye(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,Mt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=X(Nr(t));return wt.isPrototypeOf(e)?be(Wr,{machine:X(e),transitions:r}):be(Ei,{fn:X(e),transitions:r})}var wt={get state(){return {name:this.current,value:this.states[this.current]}}};function we(e,t,r=Dr){return typeof e!="string"&&(r=t||Dr,t=e,e=Object.keys(t)[0]),qe._create&&qe._create(e,t),be(wt,{context:X(r),current:X(e),states:X(t)})}function Mt(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 h=t.original||t,p=be(h,{current:X(n),original:{value:h}});qe._onEnter&&qe._onEnter(t,n,e.context,o,r);let c=p.state.value;return e.machine=p,e.onChange(e),c.enter(p,e,r)}}function Bi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Mt(e,i,t,o.transitions.get(r))||i:(qe._send&&qe._send(r,n),i)}var Fi={send(e){Bi(this,e);}};function ye(e,t,r,i){let o=Object.create(Fi,{machine:Cr(e),context:Cr(e.context(r,i)),onChange:X(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var Hr=(e,t)=>{if(!t)return;let r=wi(t);return Mi(r,e.query)},wi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Mi=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Ur=(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,h=l;if(isObject(h)){if(h.$id){if(s.nodePath?.includes(".$filter"))return;let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},c=q(t,p);if(!c?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=c.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let p=q(t,h);if(!p?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=p.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&&h.$thing){let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[te]=s.nodePath;let c=q(t,p);if(h.$filter&&(h.$filterByUnique=Lt(h.$filter,c),h.$filter=xe(h.$filter,h.$thing,t)),h.$fields){h.$fields.some(f=>c?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(c.idFields)?c.idFields:[]],h.$idNotIncluded=!0);let a=h.$fields?.flatMap(f=>{let u=Kr(f,c,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}else {let a=St(c)?.flatMap(f=>{let u=Kr(f,c,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}h.$excludedFields&&(h.$fields=h.$fields.filter(d=>tt(c,d)?!0:!h.$excludedFields.includes(d.$path)));}}}))},St=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]},Lt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),tt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Si=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[ie]:l}},Li=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:h,oppositeLinkFieldsPlayedBy:p}=i;return p.map(c=>{let d=h==="role"?c.thingType:"relation",a=h==="role"?c.thing:i.relation,f={[`$${d}`]:a},u=q(l,f),$=t?.$fields?.filter(B=>tt(u,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=u.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=St(u);else y=["id"];t.$excludedFields&&(y=y.filter(B=>tt(u,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,a,l)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:c,$path:c.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:h,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Lt(t.$filter,u),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Ri=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(h=>{let{thing:p,thingType:c,relation:d}=h,a={[`$${c}`]:p},f=q(l,a),u=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(u){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=St(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>tt(f,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,p,l)}:void 0;return {$thingType:c,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:u,$filterByUnique:Lt(t.$filter,f),$playedBy:h,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Kr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(h=>h.path===i),l=t.linkFields?.find(h=>h.path===i),s=t.roles?.[i];if(n){let h=!!n.isVirtual&&!!n.default;return Si({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:h,fieldSchema:n})}else {if(l)return Li({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return Ri({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},xe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((p,c)=>{let d=l[c],a=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?p[c]=d:p[c]=xe(d,t,r);else {let f=t in r.entities?r.entities[t]:r.relations[t],[u,$]=Ie(f,c);if(u==="dataField")p[c]=d;else if(u==="linkField"||u==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?p[c]={$id:a,$thing:m}:a.every(B=>isObject(B))&&(p[c]=isArray(d)?{$or:xe(d,m,r)}:xe(d,m,r)),p}else throw new Error(`Field ${c} not found in schema of ${t}`)}return p},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var Jr=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let h=s;if(!h.$thing)return;if(h.$thing){let p=q(e,h),{virtualFields:c}=p,d=h[te];if(!d)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,d),f=a.$fields.map($=>$.$path),u=a.$excludedFields;c.forEach($=>{if(u?.includes($)||f.length>0&&!f.includes($))return;let y=p.dataFields?.find(m=>m.path===$);if(y?.default){let m=Oe({currentThing:h,fieldSchema:y,mandatoryDependencies:!0});h[$]=m;}else if(h[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),u&&u.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[$];});}}})))(r):void 0;var vr=e=>e.replace(/`/g,""),ki=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],rt=e=>ki.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Yr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Pi({query:i,schema:r}))},Pi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push("SELECT");let c=Rt({parentQuery:t,queries:o,level:1,schema:r});c&&p.push(c);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let f=(d.subTypes?[i,...d.subTypes]:[i]).map(u=>rt(u));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(u=>`${u}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let u=t.$id,$=f.flatMap(y=>u?.map(m=>`${y}:\`${m}\``));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(n){let u=ge(n,i,r),$=Re(u);p.push(`WHERE ${$}`);}return h&&p.push(Gr(h)),typeof s=="number"&&p.push(`LIMIT ${s}`),typeof l=="number"&&p.push(`START ${l}`),p.join(`
38
- `)},Rt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],l=o[te];return n.push(T(`"${l}" as \`$$queryPath\``,i)),n.push(T("meta::id(id) as `$id`",i)),n.push(T("meta::tb(id) as `$thing`",i)),t.forEach(s=>{let h=qi({query:s,level:i,schema:r});h&&n.push(h);}),n.length===0?null:n.join(`,
39
- `)},qi=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?xi({query:t,level:i}):t.$fieldType==="link"?ji({query:t,level:i,schema:r}):t.$fieldType==="role"?Ni({query:t,level:i,schema:r}):null},xi=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?T(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?T(`\`${t.$path}\``,r):T(`\`${t.$path}\` AS \`${t.$as}\``,r)},ji=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push(T("(",i));let c=i+1;p.push(T("SELECT",c));let d=Rt({parentQuery:t,queries:o,level:c+1,schema:r});d&&p.push(d);let a=t[ie][me].queryPath;if(p.push(T(`FROM ${a}`,c)),n){let f=ge(n,t.$thing,r),u=Re(f);p.push(`WHERE ${u}`);}return h&&p.push(T(Gr(h),c)),typeof s=="number"&&p.push(T(`LIMIT ${s}`,c)),typeof l=="number"&&p.push(T(`START ${l}`,c)),p.push(T(`) AS \`${t.$as}\``,i)),p.join(`
40
- `)},Ni=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(T("(",i));let n=i+1;o.push(T("SELECT",n));let l=n+1,s=Rt({parentQuery:t,queries:t.$fields,level:l,schema:r});s&&o.push(s);let h=t[ie][me].queryPath;if(o.push(T(`FROM ${h}`,n)),t.$filter){let p=ge(t.$filter,t.$playedBy.thing,r),c=Re(p);o.push(`WHERE ${c}`);}return o.push(T(`) AS \`${t.$as}\``,i)),o.join(`
41
- `)},ge=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>{let h=Object.keys(l).reduce((p,c)=>{let d=l[c];if(c.startsWith("$"))return c==="$not"?{...p,$not:void 0,"$!":ge(d,t,r)}:c==="$or"?{...p,$or:void 0,$OR:ge(d,t,r)}:c==="$and"?{...p,$and:void 0,$AND:ge(d,t,r)}:c==="$eq"?{...p,$nor:void 0,"$=":ge(d,t,r)}:c==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:c==="$thing"?p:{...p,[c]:ge(d,t,r)};let a=t in r.entities?r.entities[t]:r.relations[t],[f,u]=Ie(a,c);if(f==="dataField"){if(a.idFields.length>1)throw new Error("Multiple id fields not supported");return c===a.idFields[0]?{...p,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...p,[c]:d}}if(f==="linkField"||f==="roleField"){let $=u;if($.$things.length!==1)throw new Error(`Not supported yet: Role ${c} in ${d.name} is played by multiple things: ${$.$things.join(", ")}`);let[y]=$.$things,m=$[me].queryPath;return {...p,[m]:ge(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(h)});return i?n:n[0]},Re=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),l=Array.isArray(o)?o.map(s=>Re(s)):[Re(o)];n==="!"?r.push(`!(${l.join(` ${n} `)})`):r.push(`(${l.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Re(o);r.push(`${i}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),l=o[n];if(isArray(l))r.push(`${i} ${n.replace("$","")} [${l.map(s=>`'${s}'`).join(", ")}]`);else if(isObject(l)){let s=Re(l);r.push(`${i} ${n.replace("$","")} ${s}`);}else r.push(`${i} ${n.replace("$","")} '${l}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(l=>`'${l}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Gr=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var Xr=async e=>{let{client:t,queries:r}=e,i=`
36
+ ${y}`})(),n=e.dbConnectors[0].id,c=r.typeDB.get(n)?.session,a=r.typeDB.get(n)?.client;if(!c){console.log("Session Status: ","NO SESSION");return}await c.close();let[{dbName:h}]=e.dbConnectors;await(await a.databases.get(h)).delete(),await a.databases.create(h);let l=await a.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await l.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let s=await l.transaction(TransactionType.READ);(await(await s.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await s.close();};var te=Symbol.for("queryPath"),Ve=Symbol.for("stepPrint"),Se=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),Ae=Symbol.for("dbNode"),dt=Symbol.for("isTransformed"),ie=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),me=Symbol.for("suqlMetadata");var Yt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Gt=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:i})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],n=[e.relation,...o],c=`<-\`${t}_${e.plays}\`<-(\`${n.join("`,`")}\`)`;if(e.target==="relation"){if(i==="edges")return c;if(i==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[a]=e.oppositeLinkFieldsPlayedBy,h=r.entities[a.thing]?.subTypes||r.relations[a.thing]?.subTypes||[],p=[a.thing,...h],l=`->\`${t}_${a.plays}\`->(\`${p.join("`,`")}\`)`;return i==="edges"?`${c}${l}`:i==="refs"?`$parent.\`${a.plays}\``:`${c}${l}`}else throw new Error("Unsupported linkField target")};var tr=(e,t,r)=>r?t:`${e}\xB7${t}`;var nr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],We=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),ir=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:c,value:a,meta:h})=>{if(h.depth===2&&(c&&(a.dataFields=a.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:tr(c,p.path,p.shared)}))),a.extends)){if(!a.defaultDBConnector.as)throw new Error(`[Schema] ${c} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${h.nodePath}`);let p=n.entities[a.extends]||n.relations[a.extends],l=[a.extends,...p.allExtends||[]];if(a.allExtends=l,l.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[c,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[c,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${c} is extending a thing that does not exist in the schema: ${d}`)}),a.idFields=p.idFields?Array.from(new Set((a.idFields||[]).concat(p.idFields))):a.idFields,a.dataFields=p.dataFields?(a.dataFields||[]).concat(p.dataFields.map(d=>{let s=a.extends,f=e.entities[s]||e.relations[s];for(;!f.dataFields?.find(u=>u.path===d.path);)s="extends"in f?f.extends:void 0,f=e.entities[s]||e.relations[s];return {...d,dbPath:tr(s,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||a.extends}}})):a.dataFields,"roles"in p){let d=a,s=p;if(s.roles){let f=mapEntries(s.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||a.extends}}]);d.roles={...d.roles||{},...f};}}a.linkFields=p.linkFields?(a.linkFields||[]).concat(p.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||a.extends}}))):a.linkFields,p?.hooks?.pre&&(a.hooks=a.hooks||{},a.hooks.pre=a.hooks.pre||[],a.hooks.pre=[...p?.hooks?.pre||[],...a?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:c,meta:a})=>{if(n==="linkFields"){let p=(()=>{if(!a.nodePath)throw new Error("No path");let[d,s]=a.nodePath.split(".");return {thing:s,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),l=Array.isArray(c)?c.map(d=>({...d,...p})):[{...c,...p}];r.push(...l);}}),produce(i,n=>traverse(n,({value:c,key:a,meta:h})=>{if(h.depth===2&&c.idFields&&!c.id){c.name=a;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};c.thingType=p();let l=Object.keys(t).find(d=>t[d]?.get(c.defaultDBConnector.id));if(c.db=l,c.dbContext=Yt[l],c.dbProviderConfig=l==="surrealDB"?t[l]?.get(c.defaultDBConnector.id)?.providerConfig:void 0,c.computedFields=[],c.virtualFields=[],c.requiredFields=[],c.enumFields=[],c.fnValidatedFields=[],"roles"in c&&Object.entries(c.roles).forEach(([s,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===a&&w.plays===s)||[];f.playedBy=u,f.path=s;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||c.name;$.length>1&&console.warn(`Not supported yet: Role ${s} in ${c.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let S=G(e,w)?.subTypes||[];return [w,...S]}),B=()=>{if(c.dbProviderConfig.linkMode==="edges")return `->\`${y}_${s}\`->(\`${m.join("`,`")}\`)`;if(c.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.\`${s}\``;if(f.cardinality==="ONE")return `$parent.[\`${s}\`]`}throw new Error("Unsupported linkMode")};if(c.db==="surrealDB"){let w=B();f[me]={queryPath:w};}}),"linkFields"in c&&c.linkFields){let d=c;d.linkFields?.forEach(s=>{s.fieldType="linkField";let f=i.relations[s.relation];if(!s.isVirtual){if(!f)throw new Error(`The relation ${s.relation} does not exist in the schema`);if(f.roles?.[s.plays]===void 0)throw new Error(`The role ${s.plays} is not defined in the relation ${s.relation} (linkField: ${s.path})`)}if(s.target==="relation"){if(s.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${s.path}. Path:${h.nodePath}."`);s.$things=[s.relation],s.oppositeLinkFieldsPlayedBy=[{plays:s.path,thing:s.relation,thingType:"relation"}];}if(s.target==="role"){let u=r.filter($=>$.relation===s.relation&&$.plays!==s.plays)||[];if(s.oppositeLinkFieldsPlayedBy=u,s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),s.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${s.path}. Path:${h.nodePath}."`);s.$things=s.oppositeLinkFieldsPlayedBy.map($=>$.thing),s.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${s.path} in ${d.name} has multiple candidates ${s.oppositeLinkFieldsPlayedBy.map($=>$.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(c.db==="surrealDB"){let u=f?.roles?.[s.plays][$e]?.inheritanceOrigin??s.relation,$=Gt({linkField:s,originalRelation:u,withExtensionsSchema:i,linkMode:c.dbProviderConfig.linkMode});s[me]={queryPath:$};}});}}if(c&&typeof c=="object"&&"playedBy"in c){let p=[...new Set(c.playedBy.map(l=>l.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${a}, path:${h.nodePath}, played by: ${p.join(", ")}`),c.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${a}, path:${h.nodePath}`)}if(h.depth===4){let[p,l]=h.nodePath?.split(".")||[],d=n[p][l];!isArray(c)&&typeof c=="object"&&(c.validations&&(c.validations.required&&d.requiredFields.push(c.path),c.validations.enum&&d.enumFields.push(c.path),c.validations.fn&&d.fnValidatedFields.push(c.path)),c.default?c.isVirtual?d.virtualFields.push(c.path):d.computedFields.push(c.path):c.isVirtual&&d.virtualFields.push(c.path));}}))},G=(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`)},q=(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)}`)},Ie=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ke=(e,t)=>{let r=q(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},or=(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")},pt=(e,t,r)=>{let i=q(e,t),o=i.linkFields?.find(a=>a.path===r);if(o)return o;let n=i.dataFields?.find(a=>a.path===r);if(n)return n;let c="roles"in i?i.roles?.[r]:void 0;if(c)return c;throw new Error(`Field ${r} not found in schema`)},ft=(e,t,r)=>pt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?listify(e.roles,u=>u):[],n=[...r||[],...i||[],...o||[]],a=[...["$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 h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],l=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],d=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!a.includes(u)).filter(u=>u),s=t.$filter?We(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?We(t.$filter,(u,$)=>l.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:d,...p.length?{localFilters:s}:{},...l.length?{nestedFilters:f}:{}}};var sr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ar=(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):{}},Fe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ue=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=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},ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},T=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var ke=(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 cr=(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=ke(t,r),[n]=o,c=e.$op==="create"?"link":"replace",a=n.thing,h=n.thingType,p={$op:c,$thing:a,$thingType:h},l=i.filter(s=>s.startsWith("_:")),d=i.filter(s=>!s.startsWith("_:"));l.length&&!d.length?e[t]=l.map(s=>({...p,$tempId:s,$bzId:s})):l.length&&d.length?e[t]=[...l.map(s=>({...p,$tempId:s,$bzId:s})),{...p,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...p,$id:e[t],$bzId:`S_${nanoid()}`};}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 Le=(e,t,r)=>{let i=q(r,t),{usedDataFields:o}=ue(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 Je=(e,t,r)=>{let i=q(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var hr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Je(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:or(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ve=(e,t)=>{let r=t[Ve];return isSet(r)?r.has("clean")?(Reflect.set(t,Ve,r.add("clean")),!0):!1:(Reflect.set(t,Ve,new Set(["clean"])),!0)};var ur=(e,t,r)=>{if(ve("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(q(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((c,a)=>({...pe(n),$id:c,$bzId:`${n.$bzId}_${a}`,...Fe(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var fr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let c=ke(t,r),[a]=c,h=Je(e,{...n,$thing:a.thing,$thingType:a.thingType},i),l=n.$bzId?n.$bzId:n.$tempId?n.$tempId:n.$id&&!isArray(n.$id)?`SN_ONE_${a.thing}_${n.$id}`:n.$id&&isArray(n.$id)?`SN_MANY_${a.thing}_${nanoid()}`:`SM_${nanoid()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:a.thing,$thingType:a.thingType,$op:h,$bzId:l}});e[t]=isArray(e[t])?o:o[0];};var zn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Vn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$r=e=>{let r=e.toString().replace(zn,"").trim().split("=>")[0].split("{")[0].replace(Vn,"").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(a=>a.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Oe=({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,c=$r(o).filter(a=>!(a in e));if(c.length)throw new Error(`Virtual field: Missing arguments ${c.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 mr=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=q(r,o),{unidentifiedFields:c}=ue(n,o),{computedFields:a,virtualFields:h}=n,p=listify(o,(s,f)=>f!==void 0?s:void 0),l=p.filter(s=>h?.includes(s));if(l.length>0)throw new Error(`Virtual fields can't be sent to DB: "${l.join(",")}"`);if(a.filter(s=>!p.includes(s)).forEach(s=>{let f=n.dataFields?.find(B=>B.path===s),$=n.linkFields?.find(B=>B.path===s)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?nr(n.roles,(B,w)=>B===s):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${s}`);if(o.$op==="create"&&!o[s]){let B=Oe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[s]=B;}}),c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(o)}`)});};var Ye=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let i=`on${sr(e.$op)}`;return r.pre.filter(c=>!c.triggers||c.triggers[i]?.()).flatMap(c=>c.actions)}return []};var gr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:c,enumFields:a,fnValidatedFields:h,dataFields:p}=q(r,n);if("$op"in n&&n.$op==="create"&&c.forEach(l=>{if(!(l in n))throw new Error(`[Validations] Required field "${l}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&a.forEach(l=>{if(l in n){let d=p?.find(s=>s.path===l)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${l}" is missing enum options.`);if(isArray(n[l]))n[l].some(s=>{if(!d.includes(s))throw new Error(`[Validations] Option "${s}" is not a valid option for field "${l}".`)});else if(d&&!d.includes(n[l]))throw new Error(`[Validations] Option "${n[l]}" is not a valid option for field "${l}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(l=>{if(l in n)try{let d=p?.find(s=>s.path===l)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[l]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${l}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let l=n.$thing,d=n,s=clone(pe(e)),f=clone(pe(d)),u=i.mutation?.context||{},$=clone(pe(n[Ae]||{}));Ye(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,s,u,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${l}] ${B.message}`)}}});}}});};var Br=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Ue(n)){if(n.$fields||n[dt])return n;let c=Ye(n,r).filter(d=>d.type==="transform"),a=clone(pe(e)),h=clone(pe(n)),p=i.mutation?.context||{},l=clone(pe(n[Ae]||n.$dbNode));return c.forEach(d=>{let s=d.fn(h,a,p,l||{});Object.keys(s).length!==0&&(n={...h,...s,...Fe(n),[dt]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Fr=(e,t,r)=>{let i=ke(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Pe=e=>{if(Array.isArray(e)){for(let t of e)if(Pe(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"&&Pe(e[t]))return !0}return !1};var ei=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ve("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")},ti=(e,t)=>{},Et=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Pe(Array.isArray(e)?e:[e]),n=produce(i,c=>traverse(c,({value:a,parent:h,key:p,meta:l})=>{if(!(!h||!p)&&isObject(a)){let d=l.nodePath?.split(".")||[];if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let u=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let s=a,f=d.includes("$filter");Object.keys(s).forEach(u=>{if(ei(s,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?pt(t,s,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return ti();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(s[u]===null?Fr(s,u,$):cr(s,u,$)),$.fieldType==="rootField"){if(!("$root"in s))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);hr(s,t);}let y=isArray(s[u])?s[u]:[s[u]],m=d.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&s.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$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)&&fr(s,u,$,t),ur(s,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&mr(s,u,t),(isArray(s[u])?s[u]:[s[u]]).forEach(w=>{let g=q(t,w),{unidentifiedFields:S,usedLinkFields:C,usedFields:A,fields:O}=ue(g,w);if(A.forEach(x=>{if(!O.includes(x))throw new Error(`[Schema] Field ${x} not found in the schema`)}),S.length>0)throw new Error(`Unknown fields: [${S.join(",")}] in ${JSON.stringify(a)}`);if(C.length>1){let x=g.linkFields?.filter(W=>C.includes(W.path));x?.some((W,le)=>x.some((K,D)=>{if(le!==D&&W.target!==K.target&&W.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||(Br(s,u,t,r),gr(s,u,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ge=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 br=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 Ge(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,c=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let a=c&&o.query.insert(c),h=a?await a.collect():void 0;return await o.commit(),{insertions:h}}catch(a){throw new Error(`Transaction failed: ${a.message}`)}finally{await o.close();}};var wr=async(e,t,r,i,o)=>{let n=[...t,...r],c=n.map(a=>{let h=e.insertions?.find(d=>d.get(`${a.$bzId}`))?.get(`${a.$bzId}`),p=a.$thing||a.$relation||a.$entity,l=p?G(i,p):void 0;if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!h&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let d=h?.asThing().iid,s=Object.entries(a).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(l?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(a.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return s;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:d,...a,...s,[a.path]:a.$id,...f}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(c)};var Mr=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 Lr=async(e,t)=>{let r=l=>{let d=[],s=[],f=m=>{if(m.$id)return m.$id;let B=q(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let S=B.dataFields?.find(O=>O.path===g),C=Oe({currentThing:m,fieldSchema:S,mandatoryDependencies:!0}),A=m[g]||m.$id||C;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(s.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B),s.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);s.push({...m,$id:B});return}s.push(m);};return traverse(l,({value:m,parent:B,meta:w})=>{if(!isObject(m))return;let g=m;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 S=q(t,g),{dataFields:C,roleFields:A,linkFields:O,usedFields:x}=ue(S,g),W=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=x.filter(E=>C?.includes(E)),F=x.filter(E=>A?.includes(E)),Q=x.filter(E=>O?.includes(E));if(D.length>0)return "update";if(F.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},le={...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,C||[""])),$op:W(),$bzId:g.$bzId};u(le);let K=g[Be];if(K?.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");d.push({...g,$op:"match"});}let D=K.relation===g.$thing,F=D?g.$bzId:`LT_${v4()}`,E=ar(l,B,w).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return D?"match":"delete";if(g.$op==="unlink")return D?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return D?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},M=q(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 k={$bzId:F,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...D?{}:{[K.path]:g.$bzId},[K.plays]:E,[Be]:K,[Se]:"linkField"};$(k),(g.$op==="unlink"||b()==="unlink")&&D&&$({$thing:K.relation,$thingType:"relation",$bzId:F,$op:"match",[K.plays]:E,[Be]:K,[Se]:"linkField"});}if(g.$thingType==="relation"){let D=We(g,(E,b)=>A.includes(E)),F=mapEntries(D,(E,b)=>isArray(b)?[E,b]:isObject(b)?[E,b.$bzId]:[E,b]),Q=We(m,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(D).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=q(t,g).roles,M=mapEntries(F,(k,L)=>{let N=b[k]?.cardinality;if(!N)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(L)){if(N==="ONE"){if(L.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,L[0].$bzId||L[0]]}return [k,L.map(J=>J.$bzId||J)]}return [k,L.$bzId||L]}),R={...Q,$thing:g.$thing,$thingType:"relation",$op:E(),...M,$bzId:g.$bzId,[Se]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){let E=0;Object.entries(D).forEach(([b,M])=>{let R=isArray(M)?M:[M],k=L=>L==="create"||L==="replace"?"link":L;R.forEach(L=>{if(!L)return;let N=k(L.$op);if(N==="replace")throw new Error("Not supported yet: replace on roleFields");if(N==="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 J={...Q,$thing:g.$thing,$thingType:"relation",$op:N==="delete"?"unlink":N,[b]:L.$bzId,$bzId:g.$bzId,[Se]:"roleField"};$(J);});});}}}}}),[d,s]},[i,o]=r(e),n=i.reduce((l,d)=>{if(!d.$bzId)return [...l,d];let s=l.findIndex(f=>f.$bzId===d.$bzId);if(s===-1)return [...l,d];if(l[s].$op==="create"&&d.$op==="match")return l;if(l[s].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...l.slice(0,s),d,...l.slice(s+1)];if(l[s].$op==="update"&&d.$op==="update")return [...l.slice(0,s),{...l[s],...d},...l.slice(s+1)];if(l[s].$op==="update"&&d.$op==="match"||l[s].$op==="match"&&d.$op==="update")return [...l.slice(0,s),{...l[s],...d,$op:"update"},...l.slice(s+1)];if(l[s].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(l[s].$filter)===JSON.stringify(d.$filter))return l;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${l[s].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${l[s].$op}. Current: ${d.$op}`)},[]),c=o.reduce((l,d)=>{let s=l.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(s){let f={...s};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=s[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...l.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...l,d]},[]);n.forEach(l=>{if((l.$thingType==="relation"||"relation"in l)&&c.filter(d=>d.$bzId===l.$bzId||d.$tempId&&d.$tempId===l.$tempId).length===0){if(l.$op==="delete"||l.$op==="match"||l.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Mr(l))}`)}});let a=[...n,...c],h=new Set(a.filter(l=>l.$tempId).map(l=>l.$tempId)),p=Array.from(h).filter(l=>!a.some(d=>d.$tempId===l&&d.$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:c}};var Bt=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var Cr=async(e,t,r)=>{let i=s=>{let f=s.$op,u=`$${s.$bzId}`,$=q(r,s),{idFields:y,defaultDBConnector:m}=$,B=m?.path||s.$thing,w=s.$id,g=y?.[0],S=listify(s,(D,F)=>{if(D.startsWith("$")||D.startsWith("%")||D===g||F===void 0||F===null)return "";let Q=$.dataFields?.find(M=>M.path===D);if(!Q?.path)return "";let b=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${b} ${F}`;if(Q.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","")}`}if(Q.contentType==="FLEX"){let M=`bza${nanoid()}`,R=isArray(F)?F.map(k=>Bt(k)):Bt(F);if(Array.isArray(R))throw new Error("Array in FLEX fields not supported yet");return `has ${b} $${M}; $${M} '${M}' isa ${b}, has ${R.type}Attribute ${R.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(D=>D),C=`${u}-atts`,A=listify(s,D=>{if(D.startsWith("$")||D.startsWith("%")||D===g)return "";let F=$.dataFields?.find(b=>b.path===D);if(!F?.path)return "";let E=F.dbPath;return `{${C} isa ${E};}`}).filter(D=>D),O=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,x=w?[`has ${g} ${O}`]:[],W=[...x,...S].filter(D=>D).join(","),le=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...x].filter(D=>D).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...x].filter(D=>D).join(",")}, has ${C};
37
+ ${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...x].filter(D=>D).join(",")};`:"";if(Ue(s))return {op:f,deletionMatch:le(),insertionMatch:K(),insertion:f==="create"?`${u} isa ${[B,W].filter(D=>D).join(",")};`:f==="update"&&S.length?`${u} ${S.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&A.length?`${u} has ${C};`:""};throw new Error("in attributes")},o=s=>{let f=s.$op,u=q(r,s),$=`$${s.$bzId}`,y=s.$id,m=u.defaultDBConnector?.path||s.$thing,B="roles"in u?listify(u.roles,F=>F):[],w="roles"in u?mapEntries(u.roles,(F,Q)=>[F,Q.dbConnector?.path||F]):{},g=listify(s,(F,Q)=>{if(!B.includes(F))return null;if(!("roles"in u))throw new Error("This should have roles! ");let E=w[F];return Array.isArray(Q)?Q.map(b=>({path:E,id:b})):{path:E,id:Q}}).filter(F=>F).flat(),S=g.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),C=g.length>0?`( ${S.join(" , ")} )`:"",A=s[Se];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let O=C?`${$} ${C} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",x=`${$} ${A==="linkField"||f==="delete"?`isa ${m}`:""}`,W=()=>O?f==="link"?`${O};`:f==="create"?`${O}, has id '${y}';`:"":"",le=()=>O&&f==="match"?`${O};`:"",K=()=>O?f==="delete"?`${O};`:f==="match"?`${O};`:"":"",D=()=>O?f==="delete"?`${x};`:f==="unlink"?`${$} ${C};`:"":"";return {deletionMatch:K(),insertionMatch:le(),deletion:D(),insertion:W(),op:""}},n=(s,f)=>{let u=f==="edges"?o:i;if(Array.isArray(s))return s.map(g=>{let{preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x}=u(g);return shake({preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x},W=>!W)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w}=u(s);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w},g=>!g)},c=n(e),a=Array.isArray(c)?c:[c],h=n(t,"edges"),p=Array.isArray(h)?h:[h],l=[...a,...p];return shake({insertionMatches:l.map(s=>s.insertionMatch).join(" ").trim(),deletionMatches:l.map(s=>s.deletionMatch).join(" ").trim(),insertions:l.map(s=>s.insertion).join(" ").trim(),deletions:l.map(s=>s.deletion).join(" ").trim()},s=>!s)};var qe={};function X(e){return {enumerable:!0,value:e}}function Dr(e){return {enumerable:!0,writable:!0,value:e}}var fi=()=>!0,Ar=()=>({}),kr=e=>e,$i=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),mi=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),be=(e,t)=>Object.freeze(Object.create(e,t));function Ir(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Or(e){return be(this,{fn:X(e)})}var Pr={},V=Or.bind(Pr);var qr={},bt=Or.bind(qr);function et(e,t){return t.filter(r=>e.isPrototypeOf(r))}function xr(e,t,...r){let i=Ir(et(qr,r).map(n=>n.fn),fi,$i),o=Ir(et(Pr,r).map(n=>n.fn),kr,mi);return be(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var jr={},Nr={},H=xr.bind(jr);xr.bind(Nr,null);function yi(e,t,r){return Mt(t,e,r,this.immediates)||e}function Wr(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 gi={enter:kr};function he(...e){let t=et(jr,e),r=et(Nr,e),i={final:X(e.length===0),transitions:X(Wr(t))};return r.length&&(i.immediates=X(r),i.enter=X(yi)),be(gi,i)}var Ei={enter(e,t,r){let i=this.fn.call(t,t.context,r);return wt.isPrototypeOf(i)?be(_r,{machine:X(i),transitions:X(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},_r={enter(e,t,r){if(t.child=ye(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,Mt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=X(Wr(t));return wt.isPrototypeOf(e)?be(_r,{machine:X(e),transitions:r}):be(Ei,{fn:X(e),transitions:r})}var wt={get state(){return {name:this.current,value:this.states[this.current]}}};function we(e,t,r=Ar){return typeof e!="string"&&(r=t||Ar,t=e,e=Object.keys(t)[0]),qe._create&&qe._create(e,t),be(wt,{context:X(r),current:X(e),states:X(t)})}function Mt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:c,reducers:a}of i)if(c(o,r)){e.context=a.call(e,o,r);let h=t.original||t,p=be(h,{current:X(n),original:{value:h}});qe._onEnter&&qe._onEnter(t,n,e.context,o,r);let l=p.state.value;return e.machine=p,e.onChange(e),l.enter(p,e,r)}}function Bi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Mt(e,i,t,o.transitions.get(r))||i:(qe._send&&qe._send(r,n),i)}var Fi={send(e){Bi(this,e);}};function ye(e,t,r,i){let o=Object.create(Fi,{machine:Dr(e),context:Dr(e.context(r,i)),onChange:X(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var Kr=(e,t)=>{if(!t)return;let r=wi(t);return Mi(r,e.query)},wi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Mi=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Jr=(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:c,meta:a}=n,h=c;if(isObject(h)){if(h.$id){if(a.nodePath?.includes(".$filter"))return;let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},l=q(t,p);if(!l?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=l.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),l?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let p=q(t,h);if(!p?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=p.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&&h.$thing){let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[te]=a.nodePath;let l=q(t,p);if(h.$filter&&(h.$filterByUnique=Lt(h.$filter,l),h.$filter=xe(h.$filter,h.$thing,t)),h.$fields){h.$fields.some(f=>l?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(l.idFields)?l.idFields:[]],h.$idNotIncluded=!0);let s=h.$fields?.flatMap(f=>{let u=Ur(f,l,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=s;}else {let s=St(l)?.flatMap(f=>{let u=Ur(f,l,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=s;}h.$excludedFields&&(h.$fields=h.$fields.filter(d=>tt(l,d)?!0:!h.$excludedFields.includes(d.$path)));}}}))},St=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]},Lt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(a=>(a.dbPath===i||a.path===i)&&a?.validations?.unique),c=i==="$id"&&!Array.isArray(e[i]);return o||n||c}return !1}),tt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Si=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:c}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[ie]:c}},Li=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:c,fieldSchema:a}=e,{target:h,oppositeLinkFieldsPlayedBy:p}=i;return p.map(l=>{let d=h==="role"?l.thingType:"relation",s=h==="role"?l.thing:i.relation,f={[`$${d}`]:s},u=q(c,f),$=t?.$fields?.filter(B=>tt(u,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=u.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=St(u);else y=["id"];t.$excludedFields&&(y=y.filter(B=>tt(u,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,s,c)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:l,$path:l.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:s,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:h,$intermediary:l.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Lt(t.$filter,u),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:a}})},Ri=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:c,fieldSchema:a}=e;return i.playedBy.map(h=>{let{thing:p,thingType:l,relation:d}=h,s={[`$${l}`]:p},f=q(c,s),u=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(u){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=St(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>tt(f,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,p,c)}:void 0;return {$thingType:l,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:u,$filterByUnique:Lt(t.$filter,f),$playedBy:h,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:a}})},Ur=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(h=>h.path===i),c=t.linkFields?.find(h=>h.path===i),a=t.roles?.[i];if(n){let h=!!n.isVirtual&&!!n.default;return Si({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:h,fieldSchema:n})}else {if(c)return Li({field:e,fieldStr:i,linkField:c,$justId:o,dbPath:c.path,schema:r,fieldSchema:c});if(a)return Ri({field:e,fieldStr:i,roleField:a,$justId:o,dbPath:i,schema:r,fieldSchema:a})}return null},xe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(c=>Object.keys(c).reduce((p,l)=>{let d=c[l],s=isArray(d)?d:[d];if(l.startsWith("$"))["$id","$thing"].includes(l)?p[l]=d:p[l]=xe(d,t,r);else {let f=t in r.entities?r.entities[t]:r.relations[t],[u,$]=Ie(f,l);if(u==="dataField")p[l]=d;else if(u==="linkField"||u==="roleField"){let y=$,[m]=y.$things;return s.every(B=>typeof B=="string")?p[l]={$id:s,$thing:m}:s.every(B=>isObject(B))&&(p[l]=isArray(d)?{$or:xe(d,m,r)}:xe(d,m,r)),p}else throw new Error(`Field ${l} not found in schema of ${t}`)}return p},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var vr=async(e,t,r)=>r?(n=>produce(n,c=>traverse(c,({value:a})=>{if(isObject(a)){let h=a;if(!h.$thing)return;if(h.$thing){let p=q(e,h),{virtualFields:l}=p,d=h[te];if(!d)throw new Error("[Internal] QueryPath is missing");let s=getNodeByPath(t,d),f=s.$fields.map($=>$.$path),u=s.$excludedFields;l.forEach($=>{if(u?.includes($)||f.length>0&&!f.includes($))return;let y=p.dataFields?.find(m=>m.path===$);if(y?.default){let m=Oe({currentThing:h,fieldSchema:y,mandatoryDependencies:!0});h[$]=m;}else if(h[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),u&&u.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[$];});}}})))(r):void 0;var Zr=e=>e.replace(/`/g,""),ki=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],rt=e=>ki.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Gr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Pi({query:i,schema:r}))},Pi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:c,$limit:a,$sort:h}=t;if(o.length===0)return null;let p=[];p.push("SELECT");let l=Rt({parentQuery:t,queries:o,level:1,schema:r});l&&p.push(l);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let f=(d.subTypes?[i,...d.subTypes]:[i]).map(u=>rt(u));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(u=>`${u}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let u=t.$id,$=f.flatMap(y=>u?.map(m=>`${y}:\`${m}\``));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(n){let u=ge(n,i,r),$=Re(u);p.push(`WHERE ${$}`);}return h&&p.push(Xr(h)),typeof a=="number"&&p.push(`LIMIT ${a}`),typeof c=="number"&&p.push(`START ${c}`),p.join(`
38
+ `)},Rt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],c=o[te];return n.push(T(`"${c}" as \`$$queryPath\``,i)),n.push(T("meta::id(id) as `$id`",i)),n.push(T("meta::tb(id) as `$thing`",i)),t.forEach(a=>{let h=qi({query:a,level:i,schema:r});h&&n.push(h);}),n.length===0?null:n.join(`,
39
+ `)},qi=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?xi({query:t,level:i}):t.$fieldType==="link"?ji({query:t,level:i,schema:r}):t.$fieldType==="role"?Ni({query:t,level:i,schema:r}):null},xi=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?T(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?T(`\`${t.$path}\``,r):T(`\`${t.$path}\` AS \`${t.$as}\``,r)},ji=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:c,$limit:a,$sort:h}=t;if(o.length===0)return null;let p=[];p.push(T("(",i));let l=i+1;p.push(T("SELECT",l));let d=Rt({parentQuery:t,queries:o,level:l+1,schema:r});d&&p.push(d);let s=t[ie][me].queryPath;if(p.push(T(`FROM ${s}`,l)),n){let f=ge(n,t.$thing,r),u=Re(f);p.push(`WHERE ${u}`);}return h&&p.push(T(Xr(h),l)),typeof a=="number"&&p.push(T(`LIMIT ${a}`,l)),typeof c=="number"&&p.push(T(`START ${c}`,l)),p.push(T(`) AS \`${t.$as}\``,i)),p.join(`
40
+ `)},Ni=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(T("(",i));let n=i+1;o.push(T("SELECT",n));let c=n+1,a=Rt({parentQuery:t,queries:t.$fields,level:c,schema:r});a&&o.push(a);let h=t[ie][me].queryPath;if(o.push(T(`FROM ${h}`,n)),t.$filter){let p=ge(t.$filter,t.$playedBy.thing,r),l=Re(p);o.push(`WHERE ${l}`);}return o.push(T(`) AS \`${t.$as}\``,i)),o.join(`
41
+ `)},ge=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(c=>{let h=Object.keys(c).reduce((p,l)=>{let d=c[l];if(l.startsWith("$"))return l==="$not"?{...p,$not:void 0,"$!":ge(d,t,r)}:l==="$or"?{...p,$or:void 0,$OR:ge(d,t,r)}:l==="$and"?{...p,$and:void 0,$AND:ge(d,t,r)}:l==="$eq"?{...p,$nor:void 0,"$=":ge(d,t,r)}:l==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:l==="$thing"?p:{...p,[l]:ge(d,t,r)};let s=t in r.entities?r.entities[t]:r.relations[t],[f,u]=Ie(s,l);if(f==="dataField"){if(s.idFields.length>1)throw new Error("Multiple id fields not supported");return l===s.idFields[0]?{...p,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...p,[l]:d}}if(f==="linkField"||f==="roleField"){let $=u;if($.$things.length!==1)throw new Error(`Not supported yet: Role ${l} in ${d.name} is played by multiple things: ${$.$things.join(", ")}`);let[y]=$.$things,m=$[me].queryPath;return {...p,[m]:ge(d,y,r)}}throw new Error(`Field ${l} not found in schema, Defined in $filter`)},{});return shake(h)});return i?n:n[0]},Re=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),c=Array.isArray(o)?o.map(a=>Re(a)):[Re(o)];n==="!"?r.push(`!(${c.join(` ${n} `)})`):r.push(`(${c.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Re(o);r.push(`${i}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),c=o[n];if(isArray(c))r.push(`${i} ${n.replace("$","")} [${c.map(a=>`'${a}'`).join(", ")}]`);else if(isObject(c)){let a=Re(c);r.push(`${i} ${n.replace("$","")} ${a}`);}else r.push(`${i} ${n.replace("$","")} '${c}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(c=>`'${c}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Xr=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var en=async e=>{let{client:t,queries:r}=e,i=`
42
42
  BEGIN TRANSACTION;
43
43
  ${r.join(";")};
44
44
  COMMIT TRANSACTION;
45
- `;return await t.query(i)};var en=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>tn(r[n],o))},tn=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Dt(e,t[0])}if(t.length>=1)return t.map(r=>Dt(e,r))}else throw new Error("res is unexpectedly not an array")},Dt=(e,t)=>{let r={[te]:t.$$queryPath,$id:t.$id,$thing:vr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=Wi(i,n));}),r},Wi=(e,t)=>t==null||isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[ie].cardinality==="ONE"&&isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[ie].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[ie].cardinality==="ONE"?Dt(e,t[0]):tn(e,t);var nn=e=>{let{queries:t,schema:r}=e;return t.map(i=>zi({query:i,schema:r}))},zi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=r.entities[i]||r.relations[i];if(!p)throw new Error(`Schema for ${i} not found`);let c=t[te],d=on(c),a=sn(o.filter(g=>g.$fieldType==="data")),f=an(o.filter(g=>g.$fieldType==="link"||g.$fieldType==="role"),r),u=[...d,...a,...f].join(`,
46
- `),$=Vi(t,p),y=n?`WHERE ${Ce(Me(n,i,r))}`:"WHERE id",m=h?ln(h):"",B=typeof s=="number"?`LIMIT ${s}`:"",w=typeof l=="number"?`START ${l}`:"";return `SELECT ${u} ${$} ${y} ${m} ${B} ${w}`},Vi=(e,t)=>{let i=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(l=>rt(l)),o=(l,s)=>`${l}:\`${s}\``,n=l=>i.flatMap(s=>l.map(h=>o(s,h))).join(",");if(!e.$id)return `FROM ${i.join(",")}`;if(typeof e.$id=="string")return `FROM ${n([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${n(e.$id)}`;throw new Error("Invalid $id")},on=e=>[`"${e}" as \`$$queryPath\``,"meta::id(id) as `$id`","meta::tb(id) as `$thing`"],sn=e=>e.map(t=>t.$path==="id"?`meta::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),an=(e,t)=>e.map(r=>{let i=on(r[te]),o=sn(r.$fields.filter(a=>a.$fieldType==="data")),n=an(r.$fields.filter(a=>a.$fieldType==="link"||a.$fieldType==="role"),t),l=[...i,...o,...n].join(`,
47
- `),s=`FROM $parent.\`${r[ie].path}\`[*]`,h=r.$filter?`WHERE ${Ce(Me(r.$filter,r.$thing,t))}`:"WHERE id",p=r.$sort?ln(r.$sort):"",c=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${l} ${s} ${h} ${p} ${c} ${d} ) AS \`${r.$as}\``}).filter(r=>r),Me=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>{let h=Object.keys(l).reduce((p,c)=>{let d=l[c];if(c.startsWith("$"))return c==="$not"?{...p,$not:void 0,"$!":Me(d,t,r)}:c==="$or"?{...p,$or:void 0,$OR:Me(d,t,r)}:c==="$and"?{...p,$and:void 0,$AND:Me(d,t,r)}:c==="$eq"?{...p,$nor:void 0,"$=":Me(d,t,r)}:c==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:c==="$thing"?p:{...p,[c]:Me(d,t,r)};let a=t in r.entities?r.entities[t]:r.relations[t],[f,u]=Ie(a,c);if(f==="dataField"){if(a.idFields.length>1)throw new Error("Multiple id fields not supported");return c===a.idFields[0]?{...p,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...p,[c]:d}}if(f==="linkField"||f==="roleField"){let $=u;if($.$things.length!==1)throw new Error(`Not supported yet: Role ${c} in ${d.name} is played by multiple things: ${$.$things.join(", ")}`);let[y]=$.$things,m=$[me].queryPath;return {...p,[m]:Me(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(h)});return i?n:n[0]},Ce=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),l=Array.isArray(o)?o.map(s=>Ce(s)):[Ce(o)];n==="!"?r.push(`!(${l.join(` ${n} `)})`):r.push(`(${l.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Ce(o);r.push(`${i}[WHERE ${n}]`);}else if(i.startsWith("$parent")){let n=Ce(o),l=i.replace("$parent.","");r.push(`${l}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),l=o[n];if(isArray(l))r.push(`${i} ${n.replace("$","")} [${l.map(s=>`'${s}'`).join(", ")}]`);else if(isObject(l)){let s=Ce(l);r.push(`${i} ${n.replace("$","")} ${s}`);}else r.push(`${i} ${n.replace("$","")} '${l}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(l=>`'${l}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},ln=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var At=H("error","error",V((e,t)=>({...e,error:t.error}))),Hi=we("build",{build:Z(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return Yr({queries:e.bql.queries,schema:e.schema});if(t==="refs")return nn({queries:e.bql.queries,schema:e.schema})},H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),At),run:Z(async e=>Xr({client:e.client,queries:ae(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),At),parse:Z(async e=>en({res:ae(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}}))),At),success:he(),error:he()},e=>e),Ki=async e=>new Promise((t,r)=>{ye(Hi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),cn=async(e,t,r,i)=>Ki({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var It="___",hn=async e=>{let{queries:t,schema:r}=e;return t.map(i=>vi({query:i,schema:r}))},vi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:h,$limit:p,$id:c}=t;if(!i)throw new Error("Path is not defined");let d=[],a=t[te];if(d.push("match"),d.push(`$${i} isa ${o};`),n||c){let $=Ke(r,t),y={...n,...c?{[$]:c}:{}},m=qt({$filter:y,$var:i,$thing:o,schema:r,depth:0});d.push(`
48
- ${m}`);}let f=xt({schema:r,$thing:o,$var:i,$sort:s,depth:0});f&&d.push(f.match);let u=`M_${v4()}`;if(d.push(`?queryPath${u} = "${a}";`),d.push("fetch"),d.push(`?queryPath${u} as "queryPath";`),l){let $=l.filter(B=>B.$fieldType==="data");$&&$.length>0&&d.push(...kt($,i,0));let y=l.filter(B=>B.$fieldType==="link");y&&y.length>0&&d.push(...Pt(y,i,i,0,r));let m=l.filter(B=>B.$fieldType==="role");m&&m.length>0&&d.push(...Ot(m,i,i,0,r));}return f&&d.push(f.sort),typeof h=="number"&&d.push(`
45
+ `;return await t.query(i)};var tn=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>rn(r[n],o))},rn=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Dt(e,t[0])}if(t.length>=1)return t.map(r=>Dt(e,r))}else throw new Error("res is unexpectedly not an array")},Dt=(e,t)=>{let r={[te]:t.$$queryPath,$id:t.$id,$thing:Zr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=Wi(i,n));}),r},Wi=(e,t)=>t==null||isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[ie].cardinality==="ONE"&&isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[ie].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[ie].cardinality==="ONE"?Dt(e,t[0]):rn(e,t);var on=e=>{let{queries:t,schema:r}=e;return t.map(i=>zi({query:i,schema:r}))},zi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:c,$limit:a,$sort:h}=t;if(o.length===0)return null;let p=r.entities[i]||r.relations[i];if(!p)throw new Error(`Schema for ${i} not found`);let l=t[te],d=sn(l),s=an(o.filter(g=>g.$fieldType==="data")),f=ln(o.filter(g=>g.$fieldType==="link"||g.$fieldType==="role"),r),u=[...d,...s,...f].join(`,
46
+ `),$=Vi(t,p),y=n?`WHERE ${Ce(Me(n,i,r))}`:"WHERE id",m=h?cn(h):"",B=typeof a=="number"?`LIMIT ${a}`:"",w=typeof c=="number"?`START ${c}`:"";return `SELECT ${u} ${$} ${y} ${m} ${B} ${w}`},Vi=(e,t)=>{let i=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(c=>rt(c)),o=(c,a)=>`${c}:\`${a}\``,n=c=>i.flatMap(a=>c.map(h=>o(a,h))).join(",");if(!e.$id)return `FROM ${i.join(",")}`;if(typeof e.$id=="string")return `FROM ${n([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${n(e.$id)}`;throw new Error("Invalid $id")},sn=e=>[`"${e}" as \`$$queryPath\``,"meta::id(id) as `$id`","meta::tb(id) as `$thing`"],an=e=>e.map(t=>t.$path==="id"?`meta::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),ln=(e,t)=>e.map(r=>{let i=sn(r[te]),o=an(r.$fields.filter(s=>s.$fieldType==="data")),n=ln(r.$fields.filter(s=>s.$fieldType==="link"||s.$fieldType==="role"),t),c=[...i,...o,...n].join(`,
47
+ `),a=`FROM $parent.\`${r[ie].path}\`[*]`,h=r.$filter?`WHERE ${Ce(Me(r.$filter,r.$thing,t))}`:"WHERE id",p=r.$sort?cn(r.$sort):"",l=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${c} ${a} ${h} ${p} ${l} ${d} ) AS \`${r.$as}\``}).filter(r=>r),Me=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(c=>{let h=Object.keys(c).reduce((p,l)=>{let d=c[l];if(l.startsWith("$"))return l==="$not"?{...p,$not:void 0,"$!":Me(d,t,r)}:l==="$or"?{...p,$or:void 0,$OR:Me(d,t,r)}:l==="$and"?{...p,$and:void 0,$AND:Me(d,t,r)}:l==="$eq"?{...p,$nor:void 0,"$=":Me(d,t,r)}:l==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:l==="$thing"?p:{...p,[l]:Me(d,t,r)};let s=t in r.entities?r.entities[t]:r.relations[t],[f,u]=Ie(s,l);if(f==="dataField"){if(s.idFields.length>1)throw new Error("Multiple id fields not supported");return l===s.idFields[0]?{...p,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...p,[l]:d}}if(f==="linkField"||f==="roleField"){let $=u;if($.$things.length!==1)throw new Error(`Not supported yet: Role ${l} in ${d.name} is played by multiple things: ${$.$things.join(", ")}`);let[y]=$.$things,m=$[me].queryPath;return {...p,[m]:Me(d,y,r)}}throw new Error(`Field ${l} not found in schema, Defined in $filter`)},{});return shake(h)});return i?n:n[0]},Ce=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),c=Array.isArray(o)?o.map(a=>Ce(a)):[Ce(o)];n==="!"?r.push(`!(${c.join(` ${n} `)})`):r.push(`(${c.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Ce(o);r.push(`${i}[WHERE ${n}]`);}else if(i.startsWith("$parent")){let n=Ce(o),c=i.replace("$parent.","");r.push(`${c}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),c=o[n];if(isArray(c))r.push(`${i} ${n.replace("$","")} [${c.map(a=>`'${a}'`).join(", ")}]`);else if(isObject(c)){let a=Ce(c);r.push(`${i} ${n.replace("$","")} ${a}`);}else r.push(`${i} ${n.replace("$","")} '${c}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(c=>`'${c}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},cn=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var At=H("error","error",V((e,t)=>({...e,error:t.error}))),Hi=we("build",{build:Z(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return Gr({queries:e.bql.queries,schema:e.schema});if(t==="refs")return on({queries:e.bql.queries,schema:e.schema})},H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),At),run:Z(async e=>en({client:e.client,queries:ae(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),At),parse:Z(async e=>tn({res:ae(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}}))),At),success:he(),error:he()},e=>e),Ki=async e=>new Promise((t,r)=>{ye(Hi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),dn=async(e,t,r,i)=>Ki({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var It="___",un=async e=>{let{queries:t,schema:r}=e;return t.map(i=>vi({query:i,schema:r}))},vi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:c,$sort:a,$offset:h,$limit:p,$id:l}=t;if(!i)throw new Error("Path is not defined");let d=[],s=t[te];if(d.push("match"),d.push(`$${i} isa ${o};`),n||l){let $=Ke(r,t),y={...n,...l?{[$]:l}:{}},m=qt({$filter:y,$var:i,$thing:o,schema:r,depth:0});d.push(`
48
+ ${m}`);}let f=xt({schema:r,$thing:o,$var:i,$sort:a,depth:0});f&&d.push(f.match);let u=`M_${v4()}`;if(d.push(`?queryPath${u} = "${s}";`),d.push("fetch"),d.push(`?queryPath${u} as "queryPath";`),c){let $=c.filter(B=>B.$fieldType==="data");$&&$.length>0&&d.push(...kt($,i,0));let y=c.filter(B=>B.$fieldType==="link");y&&y.length>0&&d.push(...Pt(y,i,i,0,r));let m=c.filter(B=>B.$fieldType==="role");m&&m.length>0&&d.push(...Ot(m,i,i,0,r));}return f&&d.push(f.sort),typeof h=="number"&&d.push(`
49
49
  offset ${h};`),typeof p=="number"&&d.push(`
50
50
  limit ${p};`),d.join(`
51
- `)},kt=(e,t,r)=>{let i=[],o=[],n=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||i.push(e[c].$dbPath),e[c][ie].contentType==="FLEX"&&n.push({path:e[c][ie].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let l=i.join(", "),h=`$metadata:{as:[${o.join(",")}]}`,p=[T(`$${t} as "${t}.${h}.$dataFields": ${l};`,r)];return n.length>0&&n.forEach(c=>{p.push(T(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),p},Ot=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:h,$as:p,$justId:c,$idNotIncluded:d,$filterByUnique:a,$thing:f,$sort:u,$offset:$,$limit:y}=s,m=s[te],B=`$metadata:{as:${p},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(T(`"${r}.${B}.${s.$var}": {`,i)),l.push(T("match",n));let w=`${t}${It}${s.$var}`;if(l.push(T(`$${w} isa ${s.$thing};`,n)),l.push(T(`$${t} (${s.$var}: $${t}${It}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter||s.$id){let S=Ke(o,s),C=s.$id?{[S]:s.$id}:{},A={...s.$filter,...C};l.push(qt({$filter:A,$var:w,$thing:s.$thing,schema:o,depth:n}));}let g=xt({schema:o,$thing:f,$var:w,$sort:u,depth:n});if(g&&l.push(g.match),h){let S=`M_${v4()}`;l.push(T(`
52
- ?queryPath${S} = "${m}";`,n)),l.push(T("fetch",n)),l.push(T(`?queryPath${S} as "queryPath";`,n));let C=h?.filter(x=>x.$fieldType==="data");C&&C.length>0&&l.push(...kt(C,w,n));let A=h?.filter(x=>x.$fieldType==="link");A&&A.length>0&&l.push(...Pt(A,w,`${t}.${s.$var}`,n,o));let O=h?.filter(x=>x.$fieldType==="role");O&&O.length>0&&l.push(...Ot(O,w,`${t}.${s.$var}`,n,o));}g&&l.push(g.sort),typeof $=="number"&&l.push(T(`offset ${$};`,n)),typeof y=="number"&&l.push(T(`limit ${y};`,n)),l.push(T("};",i));}return l},Pt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:h,$as:p,$justId:c,$idNotIncluded:d,$filterByUnique:a,$playedBy:f,$thing:u,$sort:$,$offset:y,$limit:m}=s,B=s[te],w=`$metadata:{as:${p},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(T(`"${r}.${w}.${s.$var}": {`,i)),l.push(T("match",n));let g=`${t}${It}${s.$var}`;if(l.push(T(`$${g} isa ${s.$thing};`,n)),s.$filter||s.$id){let C=Ke(o,s),A=s.$id?{[C]:s.$id}:{},O={...s.$filter,...A};l.push(qt({$filter:O,$var:g,$thing:s.$thing,schema:o,depth:n}));}let S=xt({schema:o,$thing:u,$var:g,$sort:$,depth:n});if(S&&l.push(S.match),s.$target==="role"?l.push(T(`$${t}_intermediary (${s.$plays}: $${t}, ${f.plays}: $${g}) isa ${s.$intermediary};`,n)):l.push(T(`$${g} (${s.$plays}: $${t});`,n)),h){let C=`M_${v4()}`;l.push(T(`?queryPath${C} = "${B}";`,n)),l.push(T("fetch",n)),l.push(T(`?queryPath${C} as "queryPath";`,n));let A=h?.filter(W=>W.$fieldType==="data");A&&A.length>0&&l.push(...kt(A,g,n));let O=h?.filter(W=>W.$fieldType==="link");O&&O.length>0&&l.push(...Pt(O,g,`${t}.${s.$var}`,n,o));let x=h?.filter(W=>W.$fieldType==="role");x&&x.length>0&&l.push(...Ot(x,g,`${t}.${s.$var}`,n,o));}S&&l.push(S.sort),typeof y=="number"&&l.push(T(`offset ${y};`,n)),typeof m=="number"&&l.push(T(`limit ${m};`,n)),l.push(T("};",i));}return l},Zi=(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=dn(o,r);return i&&(n.$not=dn(i,r)),n},dn=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},qt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,l=Zi(t,G(o,i)),{$not:s,...h}=l,p=G(o,i),c=[];return Object.entries(s||{}).forEach(([d,a])=>{if(d.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===d)){a===null?c.push(T(`$${r} has ${d} $${d}_${v4()};`,n)):Array.isArray(a)?a.forEach($=>{c.push(T(`not { $${r} has ${d} ${oe($)}; };`,n));}):c.push(T(`not { $${r} has ${d} ${oe(a)}; };`,n));return}let u=p.linkFields?.find($=>$.path===d);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")a===null?c.push(T(`(${u.plays}: $${r}) isa ${u.relation};`,n)):Array.isArray(a)?a.forEach(B=>{c.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(B)}; };`,n));}):c.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(a)}; };`,n));else {let B=`${$.thing}_${v4()}`;a===null?c.push(T(`$${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n)):Array.isArray(a)?a.forEach(w=>{c.push(T(`not { $${B} isa ${$.thing}, has ${m} ${oe(w)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}):c.push(T(`not { $${B} isa ${$.thing}, has ${m} ${oe(a)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}return}if(p.thingType==="relation"){let $=p.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;a===null?(c.push(T(`$${S} isa ${i};`,n)),c.push(T(`$${S} (${y.plays}: ${w});`,n)),c.push(T(`$${r} is $${S};`,n))):Array.isArray(a)?a.forEach(C=>{c.push(T(`$${S} isa ${i};`,n)),c.push(T(`not { $${w} isa ${y.thing}, has ${B} ${oe(C)}; $${S} (${y.plays}: $${w}); };`,n)),c.push(T(`$${r} is $${S};`,n));}):(c.push(T(`$${S} isa ${i};`,n)),c.push(T(`not { $${w} isa ${y.thing}, has ${B} ${oe(a)}; $${S} (${y.plays}: $${w}); };`,n)),c.push(T(`$${r} is $${S};`,n)));return}}}),Object.entries(h).forEach(([d,a])=>{if(d.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===d)){if(a===null)c.push(T(`not { $${r} has ${d} $${d}_${v4()}; };`,n));else if(Array.isArray(a)){let $=a.map(m=>`$${r} has ${d} ${oe(m)};`),y=it($);y&&c.push(T(y,n));}else c.push(T(`$${r} has ${d} ${oe(a)};`,n));return}let u=p.linkFields?.find($=>$.path===d);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")if(a===null)c.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}; };`,n));else if(Array.isArray(a)){let B=a.map(g=>`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(g)};`),w=it(B);w&&c.push(T(w,n));}else c.push(T(`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(a)};`,n));else {let B=`${$.thing}_${v4()}`;if(a===null)c.push(T(`not { $${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));else if(Array.isArray(a)){let w=a.map(S=>`$${B} isa ${$.thing}, has ${m} ${oe(S)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`),g=it(w);g&&c.push(T(g,n));}else c.push(T(`$${B} isa ${$.thing}, has ${m} ${oe(a)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n));}return}if(p.thingType==="relation"){let $=p.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;if(a===null)c.push(T(`$${S} isa ${i};`,n)),c.push(T(`not { $${S} (${y.plays}: ${w}); };`,n)),c.push(T(`$${r} is $${S};`,n));else if(Array.isArray(a)){let C=a.map(O=>`$${w} isa ${y.thing}, has ${B} ${oe(O)}; $${S} (${y.plays}: $${w});`),A=it(C);A&&(c.push(T(`$${S} isa ${i};`,n)),c.push(T(A,n)),c.push(T(`$${r} is $${S};`,n)));}else c.push(T(`$${S} isa ${i};`,n)),c.push(T(`$${w} isa ${y.thing}, has ${B} ${oe(a)}; $${S} (${y.plays}: $${w});`,n)),c.push(T(`$${r} is $${S};`,n));return}}throw new Error(`"${i}" does not have property "${d}"`)}),c.join(`
53
- `)},it=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},oe=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,Yi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},xt=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=G(i,r),s=[],h=[];if(o?.forEach(p=>{let c=Yi(p),d=l.dataFields?.find(u=>u.path===c.field);if(!d)throw new Error(`"${r}" does not have data field "${c.field}"`);let a=`${c.field}_${v4()}`;s.push(T("{",n)),s.push(T(`$${t} has ${d.dbPath} $${a}_1;`,n+1)),s.push(T("not {",n+1)),s.push(T(`$${t} has ${d.dbPath} $${a}_2;`,n+2)),s.push(T(`$${a}_2 < $${a}_1;`,n+2)),s.push(T("};",n+1)),s.push(T(`?${a}_ = $${a}_1;`,n+1)),s.push(T("} or {",n)),s.push(T(`not { $${t} has ${d.dbPath} $${a}_1; };`,n+1)),s.push(T(`?${a}_ = "~";`,n+1)),s.push(T("};",n)),s.push(T(`?${a} = ?${a}_;`,n));let f=c.desc?"desc":"asc";h.push(`?${a} ${f}`);}),s.length!==0)return {match:s.join(""),sort:T(`sort ${h.join(", ")};`,n)}};var pn=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 h=r[s],p=t[s];return Xi(l,h,p,i,o)})},Xi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?un(e[0],t,i,o):e.map(n=>un(n,t,i,o)),un=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:h}=jt(e,r),p=Nt(o,n,i),c=_t(l,r,i),d=Wt(s,r,i),a=t?.$fields?.every(u=>!n?.idFields?.includes(typeof u=="string"?u:u.$path));return {...c,...d,...h,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...a?Object.fromEntries(Object.entries(p).filter(([u])=>!n?.idFields?.includes(u))):p}},jt=(e,t)=>{let r=Object.keys(e),i=r.find(f=>f.endsWith(".$dataFields")),o=r.filter(f=>f.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(f=>{let u=f.replace(/\.\$multiVal$/,""),$=e[f][0][u].attribute;e[i][u]=$;});let n=e[i],l=i.split(".")[i.split(".").length-2];if(n.$metaData=l,n.length===0)throw new Error("No dataFields");let s=n.type,h={$thing:s.label,$thingType:s.root,[te]:e.queryPath.value},p={[`$${h.$thingType}`]:h.$thing},c=q(t,p),d=r.filter(f=>{let u=ae(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===u)}).map(f=>{let u=ae(f.split(".").pop()),$=ae(c.linkFields?.find(y=>y.path===u));return {$linkFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),a=r.filter(f=>{let u=f.split(".").pop();return u&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[u]}).map(f=>{let u=ae(f.split(".").pop());return {$roleFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[u].cardinality}});return {dataFields:n,schemaValue:h,currentSchema:c,linkFields:d,roleFields:a}},Nt=(e,t,r)=>{let{$metaData:i}=e,{as:o}=eo(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let h=t.dataFields?.find(a=>a.path===l||a.dbPath===l),p=l==="id",c=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,d;if(h?.cardinality==="ONE"){if(d=s[0]?s[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"||h.contentType==="FLEX"&&s[0].type.value_type==="datetime"?d=d&&`${d}Z`:h.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[c,d],["$id",d]].filter(([a,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];h.contentType==="DATE"?d=s.map(a=>`${a.value}Z`):h.contentType==="FLEX"?d=s.map(a=>a.type.value_type==="datetime"?`${a.value}Z`:a.value):h.contentType==="JSON"?d=s.map(a=>a.value&&JSON.parse(a.value)):d=s.map(a=>a.value);}return [[c,d]].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:h,justId:p,idNotIncluded:c,filterByUnique:d}=fn(l);if(h===null)return;let a=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return c==="true"&&$?.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});a.length>0?i[h]=s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls&&(i[h]=null);}),i},_t=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:h,justId:p,idNotIncluded:c,filterByUnique:d}=fn(l);if(h===null)return;let a=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return c==="true"&&$.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});i[h]=a.length>0?s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},fn=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),h=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:h?h[1]:null}},eo=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,h)=>/^{.*}$/.test(h)?`:${h}`:`:${s}"${h}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var $n=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ge(r,i),l=await n.transaction(TransactionType.READ,o),[s,h]=await tryit(parallel)(t.length,t,async p=>await l.query.fetch(p).collect());if(s){await l.rollback();let p=s;throw new Error(`Error running TQL query: ${p.errors}`)}return await l.close(),h};var oo=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,so=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,ao=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,zt=H("error","error",V((e,t)=>({...e,error:t.error}))),lo=we("build",{build:Z(async e=>hn({queries:e.bql.queries,schema:e.schema}),H("done","run",V(so)),zt),run:Z(async e=>$n({dbHandles:e.handles,tqlRequest:ae(e.tql.queries),config:e.config}),H("done","parse",V(ao)),zt),parse:Z(async e=>pn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ae(e.tql.res)}),H("done","success",V(oo)),zt),success:he(),error:he()},e=>e),co=async e=>new Promise((t,r)=>{ye(lo,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),mn=async(e,t,r,i,o)=>co({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var ho=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Vt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ot=H("error","error",V((e,t)=>({...e,error:t.error}))),uo=we("enrich",{enrich:Z(async e=>Ur(e.bql.raw,e.schema),H("done","adapter",V(ho)),ot),adapter:Z(async e=>{let t={};e.bql.queries?.forEach((s,h)=>{let p=e.bql.raw[h],c=G(e.schema,s.$thing),{id:d}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let a=t[d];a.rawBql.push(p),a.bqlQueries.push(s),a.indices.push(h);});let r=Object.values(t),i=r.map(s=>{if(s.db==="typeDB")return mn(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return cn(s.bqlQueries,e.schema,e.config,s.client);throw new Error("Unsupported DB provider")}),o=await Promise.all(i),n=r.flatMap((s,h)=>{let p=o[h];return s.indices.map((c,d)=>({index:c,result:p[d]}))});return n.sort((s,h)=>s.index<h.index?-1:s.index>h.index?1:0),n.map(({result:s})=>s)},H("done","postHooks",V(Vt)),ot),postHooks:Z(async e=>Jr(e.schema,ae(e.bql.queries),ae(e.bql.res)),H("done","clean",V(Vt)),ot),clean:Z(async e=>Hr(e.config,ae(e.bql.res)),H("done","success",V(Vt)),ot),success:he(),error:he()},e=>e),po=async e=>new Promise((t,r)=>{ye(uo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),je=async(e,t,r,i)=>po({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Ht="___",fo=Symbol.for("grandChildOfCreate"),yn=async(e,t,r,i)=>{let o=(F,Q)=>Object.keys(F).filter(E=>!E.startsWith("$")&&F[E]!==void 0?Q?!q(t,F).dataFields?.find(M=>M.path===E):!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:F,key:Q,value:E})=>{F&&Q&&!Q.includes("$")&&isObject(F)?(Array.isArray(F[Q])?F[Q]:[F[Q]]).forEach(M=>{if(isObject(M)){if(F.$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`)}}):!F&&isObject(E)&&(n.includes(E.$op)||n.push(E.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(F=>{let Q=(E,b)=>{let M=[],R={},k=["$op","$bzId","$parentKey"],L=["$relation","$entity","$id",...k];for(let N in E)if(!k.includes(N)&&!(L.includes(N)&&!b))if(!N.includes("$")&&(isObject(E[N])||Array.isArray(E[N]))){let J=E[N];if(Array.isArray(J)&&J.length>0)J.forEach(ce=>{let Qe={$path:N,...Q(ce),...ce.$filter&&{$as:ce.$bzId}};M.find(U=>U.$path===Qe.$path&&!U.$filter)||(M=[...M,Qe]);});else {let ce={$path:N,...Q(J),...!J.$filter&&{$as:J.$bzId}};M=[...M,ce];}}else R[N]=E[N];return {...R,$fields:M}};return F.map(E=>Q(E,!0))})(Array.isArray(e)?e:[e]),p=(await je(s,t,{...r,query:{...r.query,returnNulls:!0}},i)).bql.res,c=(F,Q)=>{let E=F.$id||F.id||F.$bzId;if(F.$objectPath){let{$objectPath:b}=F,M=b?.beforePath||"root",R=Array.isArray(b.ids)?`[${b.ids}]`:b.ids;return {beforePath:`${M}.${R}___${b.key}`,ids:E,key:Q}}else return {beforePath:"root",ids:E,key:Q}},d=(F,Q)=>{let E=F?.beforePath||"root";if(typeof E!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let b=(Array.isArray(F?.ids)?`[${F?.ids}]`:F?.ids);return `${E}.${b}___${F?.key}`},a=F=>{if(F.includes("[")&&F.includes("]")){let[Q,E,b]=F.split(/[[\]]/);return E.split(",").map(R=>`${Q}${R}${b}`)}else return [F]},f={};(F=>produce(F,Q=>traverse(Q,({key:E,parent:b})=>{if(b&&E&&b.$id&&!E.includes("$")){let M=c(b,E),R=d(M);if(Array.isArray(b[E])){let k=[];b[E].forEach(L=>{isObject(L)?(L.$objectPath=M,k.push(L.$id.toString())):L&&k.push(L.toString());}),f[R]={$objectPath:M,$ids:k};}else {let k=b[E];isObject(k)?(f[R]={$objectPath:M,$ids:[k.$id.toString()]},k.$objectPath=M):k?f[R]={$objectPath:M,$ids:[k.toString()]}:k===null&&(f[R]=null);}}})))(p||{});let $=F=>produce(F,Q=>traverse(Q,({key:E,value:b,parent:M})=>{M&&E&&!E.includes("$")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(M)&&(Array.isArray(M[E])?M[E].forEach(R=>{typeof R!="string"&&(R.$objectPath=c(M,E),R.$parentIsCreate=M.$op==="create",R[fo]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[E])&&(M[E].$parentIsCreate=M.$op==="create",M[E][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[E].$objectPath=c(M,E)));})),y=$(e),m=F=>{let Q=[];return F.forEach(b=>{if(!b.$id&&!b.id&&!b.$tempId)if(b.$filter){let M=d({...b.$objectPath,key:b.$bzId}),R=f[M];R&&(Array.isArray(R.$ids)?R.$ids:[R.$ids]).forEach(L=>{let N={...b,$id:L,$bzId:`T4_${v4()}`,$filterBzId:b.$bzId};Q.push(N);});}else {let M=d(b.$objectPath),R=f[M];R?R?.$ids?.forEach(k=>{let L={...b,$id:k,$bzId:`T4_${v4()}`};Q.push(L);}):Q.push(b);}else Q.push(b);}),Q.map(b=>{let M={...b};return o(M,!0).forEach(R=>{let k=Array.isArray(M[R])?M[R]:[M[R]],L=m(k);M[R]=L;}),M})},B=m(Array.isArray(y)?y:[y]),w=$(B),S=(F=>{let Q=E=>{let b=U=>{let ee=[],z=[],P=[];return U.forEach(j=>{let se=o(j,!0);if(se.length>0){let I=!1;se.forEach(_=>{(Array.isArray(j[_])?j[_]:[j[_]]).filter(Y=>!Y.$id&&!Y.id&&typeof j=="object").length&&(I=!0);}),I?ee.push(j):z.push(j);}else j.$id?P.push({...j,$bzId:j.$tempId||j.$bzId}):P.push({...j,$bzId:j.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:P}},{operationWithMultiples:M,operationWithoutMultiples:R,otherOps:k}=b(E),L=U=>{let z=(()=>{let _={};for(let re in U){let v=q(t,U);!re.startsWith("$")&&v.dataFields?.find(Y=>Y.path===re)&&(_[re]=U[re]);}return _})(),P=Object.keys(U),j=o(U,!0),se=[],I=(_,re)=>{if(_===j.length){let Y={...re};P.forEach(ne=>{ne.startsWith("$")&&(Y[ne]=U[ne]);}),se.push({...Y,...z});return}let v={...re,[j[_]]:U[j[_]],...Fe(re),...z};I(_+1,v),I(_+1,re);};return I(0,{...Fe(U)}),se},N=[];return M.forEach(U=>{let ee=L(U),z=[];ee.forEach(P=>{let j=o(P,!0);if(P.$op==="create")z.push(P);else if(P.$id){let se=d(P.$objectPath),I=[];if(j.forEach(_=>{let re=`${se.includes("undefined")?"root":se}.${P.$id}${Ht}${_}`,v=f[re];P[_].filter(ne=>ne.$op==="unlink"||ne.$op==="delete"||ne.$op==="update").length>0?v?.$ids&&I.push({key:_,ids:v.$ids}):I.push({key:_,ids:[""]});}),I.length===j.length&&!z.find(_=>_.$id===P.$id))z.push(P);else {let _={...P,$bzId:P.$tempId||`T4_${v4()}`};j.forEach(v=>{let Y=P[v].filter(ne=>ne.$id);Y.length>0?_[v]=Y:_[v]=void 0;}),o(_,!0).length>0&&z.push(_);}}else if(P.$objectPath){let se=d(P.$objectPath),I=f[se]?.$ids||[];I.forEach(_=>{let re=[];j.forEach(v=>{let Y=`${se}.${_}${Ht}${v}`,ne=f[Y];ne&&re.push({key:v,ids:ne.$ids});}),j.length===0?I.filter(Y=>!z.find(ne=>ne.$id===Y)).forEach(Y=>{z.push({...P,$id:Y,$bzId:P.$tempId||`PQT2_${v4()}`});}):re.length===j.length&&!z.find(v=>v.$id===_)&&(j.forEach(v=>{let Y=`${d(P.$objectPath)}.${_}${Ht}${v}`,ne=f[Y]?.$ids||[],Dn=P[v].find(De=>!De.$id),Jt=[...ne.map(De=>({...Dn,$id:De,$objectPath:{beforePath:P.$objectPath.beforePath,ids:De,key:v}})),...P[v].filter(De=>De.$id)];Jt.length>0&&(P[v]=Jt);}),z.push({...P,$id:_,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else z.push(P);}),z.forEach(P=>{N.push(P);});}),[...N,...R,...k].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let P=Array.isArray(ee[z])?ee[z]:[ee[z]],j=Q(P);ee[z]=j;}),ee})};return Q(F)})(Array.isArray(w)?w:[w]),C=F=>F.map(Q=>{let E=o(Q,!0),b={...Q};return E.forEach(M=>{let R=Array.isArray(Q[M])?Q[M]:[Q[M]],k=[],L=[],N=[],J={},ce=ft(t,Q,M);R.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?L=[...L,...I.$id]:L.push(I.$id)):I.$op==="create"&&ce==="ONE"&&I.id?(J=I,Array.isArray(I.id)?N=[...L,...I.id]:N.push(I.id)):k.push(I);});let Qe=d(J.$objectPath),ee=a(Qe).map(I=>f[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I?.$ids||[]];});let P=z.filter(I=>!L.includes(I)),j=L.filter(I=>!z.includes(I)),se=Fe(J);P.length>0&&k.push({...J,$op:"unlink",$id:P,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...se}),j.length>0&&j.forEach(I=>{k.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${v4()}`,...se});}),N.length>0&&N.forEach(I=>{k.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${v4()}`,...se});}),b[M]=C(k);}),b}),A=$(C($(S)));(F=>produce(F,Q=>traverse(Q,E=>{let{key:b,value:M,parent:R}=E;b&&R&&!b?.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(R)&&(Array.isArray(M)?M:[M]).forEach(L=>{let N=L.$filter?{...L.$objectPath,key:L.$filterBzId}:L.$objectPath,J=d(N),ce=f[J],Qe=(z,P)=>z.every(j=>P.includes(j)),U=L.$id?Array.isArray(L.$id)?Qe(L.$id,ce&&ce.$ids?ce.$ids:[]):ce?.$ids?.includes(L.$id):ce,ee=ft(t,R,L.$objectPath.key);if(L.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(L.$objectPath)}" because it is already occupied.`);if(L.$op)switch(L.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${L.$id}" because it is already linked to $id:"${R.$id}"`);break;}});})))(A);let W=(F=>produce(F,Q=>traverse(Q,E=>{let{value:b,meta:M}=E;isObject(b)&&(b[Symbol.for("path")]=M.nodePath,delete b.$objectPath,delete b.$parentIsCreate);})))(A);return [...Array.isArray(W)?W:[W]].sort((F,Q)=>F.$op==="create"&&Q.$op!=="create"?-1:F.$op!=="create"&&Q.$op==="create"?1:0)};var gn=(e,t)=>produce(e,i=>at(t,i)),at=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>at(e,o,r));return}let i=G(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||mo(e,t,o,i);});},mo=(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;at(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[h]=s.playedBy||[];if(!h)throw new Error(`Role ${s.path} in ${i} is not played by anything`);at(e,o,h.thing);}};var bn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(h=>Kt(h,!0)),s=(await je(n,t,r,i)).bql.res;return o.map((h,p)=>{let c=G(t,h.$thing);return Mn({mut:h,node:s[p],schema:t,thing:c})})},wn=new Set(["$op","$bzId","$parentKey"]),go=new Set(["$relation","$entity","$id",...wn]),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(wn.has(o)||go.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},Mn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=Qn(o),l=Bo(r);if(Array.isArray(t))return t.map(h=>{let p=l[h.$id];return p?En({mut:h,node:p,schema:i,thing:o,...n}):h});let s=l[t.$id];return En({mut:t,node:s,schema:i,thing:o,...n})},En=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:h,...p}=t;if(!r)return p;let c=Tn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),d={...p,[Ae]:c};for(let a in t){if(a.startsWith("$"))continue;let f=t[a];if(n[a]||!f||typeof f!="object"){d[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 y=G(i,$);d[a]=Mn({mut:f,schema:i,node:r[a],thing:y});}return d},Tn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,h=t||Eo(o),p={$id:r.$id};return h.forEach(c=>{let d=typeof c!="string",a=d?c.$path:c,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(!d){f&&(p[a]=Array.isArray(f)?f.map(Bn):Bn(f));return}let y=G(i,$),m=Qn(y);p[a]=Array.isArray(f)?f.map(B=>Fn({...m,$fields:c.$fields,value:B,schema:i,thing:y})):Fn({...m,$fields:c.$fields,value:f,schema:i,thing:y});}),p},Eo=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},Bn=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},Fn=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 Tn({...e,node:t})},Qn=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}},Bo=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 Sn=he,Ne=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Fo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),bo=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),wo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Mo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),To=async e=>Object.keys(e.bql.current).length?Et(e.bql.current,e.schema,e.config):Et(e.bql.raw,e.schema,e.config),Qo=async e=>yn(e.bql.current,e.schema,e.config,e.handles),So=async e=>bn(e.bql.current,e.schema,e.config,e.handles),Lo=async e=>Sr(e.bql.current,e.schema),Ro=async e=>Rr(e.bql.things,e.bql.edges,e.schema),Co=async e=>Fr(e.typeDB.tqlMutation,e.handles,e.config),Do=async e=>br(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Ao=()=>!0,Io=e=>Pe(e.bql.current),Te=H("error","error",V((e,t)=>({...e,error:t.error}))),ko=we("stringify",{stringify:Z(async e=>gn(e.bql.raw,e.schema),H("done","enrich",V(Ne)),Te),enrich:Z(To,H("done","preQuery",bt(Ao),V(Ne)),H("done","parseBQL",V(Ne)),Te),preHookDependencies:Z(So,H("done","enrich",V(Ne)),Te),preQuery:Z(Qo,H("done","preHookDependencies",bt(Io),V(Ne)),H("done","parseBQL",V(Ne)),Te),parseBQL:Z(Lo,H("done","buildMutation",V(bo)),Te),buildMutation:Z(Ro,H("done","runMutation",V(wo)),Te),runMutation:Z(Co,H("done","parseMutation",V(Mo)),Te),parseMutation:Z(Do,H("done","success",V(Fo)),Te),success:Sn(),error:Sn()},e=>e),Oo=async e=>new Promise((t,r)=>{ye(ko,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),Ln=async(e,t,r,i)=>Oo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Ut=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,{namespace:i.namespace,database:i.dbName,auth:{namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}}),t.surrealDB.set(i.id,{client:o,providerConfig:i.providerConfig});}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=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,l]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let s=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await l.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:l,session:s});}catch(s){let h=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let r=ir(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(),Zt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...ct.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await tryit(je)(n,this.schema,i,this.dbHandles);if(l){let p=new Error(l.error);throw p.stack=l.error.stack,p}let h=s.bql.res;return o?h:h[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...ct.mutation,...this.config.mutation,...r}},[o,n]=await tryit(Ln)(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();});}},Kc=Ut;//! Todo: delete when this works with the new $thing and $thingType fields
51
+ `)},kt=(e,t,r)=>{let i=[],o=[],n=[];for(let l=0;l<e.length;l++)e[l].$isVirtual||i.push(e[l].$dbPath),e[l][ie].contentType==="FLEX"&&n.push({path:e[l][ie].dbPath}),o.push(`{${e[l].$dbPath}:${e[l].$as}}`);let c=i.join(", "),h=`$metadata:{as:[${o.join(",")}]}`,p=[T(`$${t} as "${t}.${h}.$dataFields": ${c};`,r)];return n.length>0&&n.forEach(l=>{p.push(T(`"${l.path}.$multiVal": {match $${t} has ${l.path} $${l.path}; fetch $${l.path}: attribute;};`,r));}),p},Ot=(e,t,r,i,o)=>{let n=i+1,c=[];for(let a of e){let{$fields:h,$as:p,$justId:l,$idNotIncluded:d,$filterByUnique:s,$thing:f,$sort:u,$offset:$,$limit:y}=a,m=a[te],B=`$metadata:{as:${p},justId:${l?"T":"F"},idNotIncluded:${d},filterByUnique:${s}}`;c.push(T(`"${r}.${B}.${a.$var}": {`,i)),c.push(T("match",n));let w=`${t}${It}${a.$var}`;if(c.push(T(`$${w} isa ${a.$thing};`,n)),c.push(T(`$${t} (${a.$var}: $${t}${It}${a.$var}) isa ${a.$intermediary};`,n)),a.$filter||a.$id){let S=Ke(o,a),C=a.$id?{[S]:a.$id}:{},A={...a.$filter,...C};c.push(qt({$filter:A,$var:w,$thing:a.$thing,schema:o,depth:n}));}let g=xt({schema:o,$thing:f,$var:w,$sort:u,depth:n});if(g&&c.push(g.match),h){let S=`M_${v4()}`;c.push(T(`
52
+ ?queryPath${S} = "${m}";`,n)),c.push(T("fetch",n)),c.push(T(`?queryPath${S} as "queryPath";`,n));let C=h?.filter(x=>x.$fieldType==="data");C&&C.length>0&&c.push(...kt(C,w,n));let A=h?.filter(x=>x.$fieldType==="link");A&&A.length>0&&c.push(...Pt(A,w,`${t}.${a.$var}`,n,o));let O=h?.filter(x=>x.$fieldType==="role");O&&O.length>0&&c.push(...Ot(O,w,`${t}.${a.$var}`,n,o));}g&&c.push(g.sort),typeof $=="number"&&c.push(T(`offset ${$};`,n)),typeof y=="number"&&c.push(T(`limit ${y};`,n)),c.push(T("};",i));}return c},Pt=(e,t,r,i,o)=>{let n=i+1,c=[];for(let a of e){let{$fields:h,$as:p,$justId:l,$idNotIncluded:d,$filterByUnique:s,$playedBy:f,$thing:u,$sort:$,$offset:y,$limit:m}=a,B=a[te],w=`$metadata:{as:${p},justId:${l?"T":"F"},idNotIncluded:${d},filterByUnique:${s}}`;c.push(T(`"${r}.${w}.${a.$var}": {`,i)),c.push(T("match",n));let g=`${t}${It}${a.$var}`;if(c.push(T(`$${g} isa ${a.$thing};`,n)),a.$filter||a.$id){let C=Ke(o,a),A=a.$id?{[C]:a.$id}:{},O={...a.$filter,...A};c.push(qt({$filter:O,$var:g,$thing:a.$thing,schema:o,depth:n}));}let S=xt({schema:o,$thing:u,$var:g,$sort:$,depth:n});if(S&&c.push(S.match),a.$target==="role"?c.push(T(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${g}) isa ${a.$intermediary};`,n)):c.push(T(`$${g} (${a.$plays}: $${t});`,n)),h){let C=`M_${v4()}`;c.push(T(`?queryPath${C} = "${B}";`,n)),c.push(T("fetch",n)),c.push(T(`?queryPath${C} as "queryPath";`,n));let A=h?.filter(W=>W.$fieldType==="data");A&&A.length>0&&c.push(...kt(A,g,n));let O=h?.filter(W=>W.$fieldType==="link");O&&O.length>0&&c.push(...Pt(O,g,`${t}.${a.$var}`,n,o));let x=h?.filter(W=>W.$fieldType==="role");x&&x.length>0&&c.push(...Ot(x,g,`${t}.${a.$var}`,n,o));}S&&c.push(S.sort),typeof y=="number"&&c.push(T(`offset ${y};`,n)),typeof m=="number"&&c.push(T(`limit ${m};`,n)),c.push(T("};",i));}return c},Zi=(e,t)=>{let r={};if(t.dataFields?.forEach(c=>{c.path!==c.dbPath&&(r[c.path]=c.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=hn(o,r);return i&&(n.$not=hn(i,r)),n},hn=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},qt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,c=Zi(t,G(o,i)),{$not:a,...h}=c,p=G(o,i),l=[];return Object.entries(a||{}).forEach(([d,s])=>{if(d.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===d)){s===null?l.push(T(`$${r} has ${d} $${d}_${v4()};`,n)):Array.isArray(s)?s.forEach($=>{l.push(T(`not { $${r} has ${d} ${oe($)}; };`,n));}):l.push(T(`not { $${r} has ${d} ${oe(s)}; };`,n));return}let u=p.linkFields?.find($=>$.path===d);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")s===null?l.push(T(`(${u.plays}: $${r}) isa ${u.relation};`,n)):Array.isArray(s)?s.forEach(B=>{l.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(B)}; };`,n));}):l.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(s)}; };`,n));else {let B=`${$.thing}_${v4()}`;s===null?l.push(T(`$${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n)):Array.isArray(s)?s.forEach(w=>{l.push(T(`not { $${B} isa ${$.thing}, has ${m} ${oe(w)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}):l.push(T(`not { $${B} isa ${$.thing}, has ${m} ${oe(s)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}return}if(p.thingType==="relation"){let $=p.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;s===null?(l.push(T(`$${S} isa ${i};`,n)),l.push(T(`$${S} (${y.plays}: ${w});`,n)),l.push(T(`$${r} is $${S};`,n))):Array.isArray(s)?s.forEach(C=>{l.push(T(`$${S} isa ${i};`,n)),l.push(T(`not { $${w} isa ${y.thing}, has ${B} ${oe(C)}; $${S} (${y.plays}: $${w}); };`,n)),l.push(T(`$${r} is $${S};`,n));}):(l.push(T(`$${S} isa ${i};`,n)),l.push(T(`not { $${w} isa ${y.thing}, has ${B} ${oe(s)}; $${S} (${y.plays}: $${w}); };`,n)),l.push(T(`$${r} is $${S};`,n)));return}}}),Object.entries(h).forEach(([d,s])=>{if(d.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===d)){if(s===null)l.push(T(`not { $${r} has ${d} $${d}_${v4()}; };`,n));else if(Array.isArray(s)){let $=s.map(m=>`$${r} has ${d} ${oe(m)};`),y=it($);y&&l.push(T(y,n));}else l.push(T(`$${r} has ${d} ${oe(s)};`,n));return}let u=p.linkFields?.find($=>$.path===d);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")if(s===null)l.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}; };`,n));else if(Array.isArray(s)){let B=s.map(g=>`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(g)};`),w=it(B);w&&l.push(T(w,n));}else l.push(T(`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(s)};`,n));else {let B=`${$.thing}_${v4()}`;if(s===null)l.push(T(`not { $${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));else if(Array.isArray(s)){let w=s.map(S=>`$${B} isa ${$.thing}, has ${m} ${oe(S)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`),g=it(w);g&&l.push(T(g,n));}else l.push(T(`$${B} isa ${$.thing}, has ${m} ${oe(s)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n));}return}if(p.thingType==="relation"){let $=p.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;if(s===null)l.push(T(`$${S} isa ${i};`,n)),l.push(T(`not { $${S} (${y.plays}: ${w}); };`,n)),l.push(T(`$${r} is $${S};`,n));else if(Array.isArray(s)){let C=s.map(O=>`$${w} isa ${y.thing}, has ${B} ${oe(O)}; $${S} (${y.plays}: $${w});`),A=it(C);A&&(l.push(T(`$${S} isa ${i};`,n)),l.push(T(A,n)),l.push(T(`$${r} is $${S};`,n)));}else l.push(T(`$${S} isa ${i};`,n)),l.push(T(`$${w} isa ${y.thing}, has ${B} ${oe(s)}; $${S} (${y.plays}: $${w});`,n)),l.push(T(`$${r} is $${S};`,n));return}}throw new Error(`"${i}" does not have property "${d}"`)}),l.join(`
53
+ `)},it=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},oe=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,Yi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},xt=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,c=G(i,r),a=[],h=[];if(o?.forEach(p=>{let l=Yi(p),d=c.dataFields?.find(u=>u.path===l.field);if(!d)throw new Error(`"${r}" does not have data field "${l.field}"`);let s=`${l.field}_${v4()}`;a.push(T("{",n)),a.push(T(`$${t} has ${d.dbPath} $${s}_1;`,n+1)),a.push(T("not {",n+1)),a.push(T(`$${t} has ${d.dbPath} $${s}_2;`,n+2)),a.push(T(`$${s}_2 < $${s}_1;`,n+2)),a.push(T("};",n+1)),a.push(T(`?${s}_ = $${s}_1;`,n+1)),a.push(T("} or {",n)),a.push(T(`not { $${t} has ${d.dbPath} $${s}_1; };`,n+1)),a.push(T(`?${s}_ = "~";`,n+1)),a.push(T("};",n)),a.push(T(`?${s} = ?${s}_;`,n));let f=l.desc?"desc":"asc";h.push(`?${s} ${f}`);}),a.length!==0)return {match:a.join(""),sort:T(`sort ${h.join(", ")};`,n)}};var fn=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((c,a)=>{let h=r[a],p=t[a];return Xi(c,h,p,i,o)})},Xi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?pn(e[0],t,i,o):e.map(n=>pn(n,t,i,o)),pn=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:c,roleFields:a,schemaValue:h}=jt(e,r),p=Nt(o,n,i),l=_t(c,r,i),d=Wt(a,r,i),s=t?.$fields?.every(u=>!n?.idFields?.includes(typeof u=="string"?u:u.$path));return {...l,...d,...h,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...s?Object.fromEntries(Object.entries(p).filter(([u])=>!n?.idFields?.includes(u))):p}},jt=(e,t)=>{let r=Object.keys(e),i=r.find(f=>f.endsWith(".$dataFields")),o=r.filter(f=>f.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(f=>{let u=f.replace(/\.\$multiVal$/,""),$=e[f][0][u].attribute;e[i][u]=$;});let n=e[i],c=i.split(".")[i.split(".").length-2];if(n.$metaData=c,n.length===0)throw new Error("No dataFields");let a=n.type,h={$thing:a.label,$thingType:a.root,[te]:e.queryPath.value},p={[`$${h.$thingType}`]:h.$thing},l=q(t,p),d=r.filter(f=>{let u=ae(f.split(".").pop());return !f.endsWith(".$dataFields")&&l.linkFields?.some($=>$.path===u)}).map(f=>{let u=ae(f.split(".").pop()),$=ae(l.linkFields?.find(y=>y.path===u));return {$linkFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),s=r.filter(f=>{let u=f.split(".").pop();return u&&!f.endsWith(".$dataFields")&&l.thingType==="relation"&&l.roles?.[u]}).map(f=>{let u=ae(f.split(".").pop());return {$roleFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:l.roles[u].cardinality}});return {dataFields:n,schemaValue:h,currentSchema:l,linkFields:d,roleFields:s}},Nt=(e,t,r)=>{let{$metaData:i}=e,{as:o}=eo(i),n=Object.entries(e).filter(([c])=>c!=="type"&&!c.startsWith("$")).map(([c,a])=>{let h=t.dataFields?.find(s=>s.path===c||s.dbPath===c),p=c==="id",l=Array.isArray(o)?o.find(s=>s[c])?.[c]:c,d;if(h?.cardinality==="ONE"){if(d=a[0]?a[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"||h.contentType==="FLEX"&&a[0].type.value_type==="datetime"?d=d&&`${d}Z`:h.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[l,d],["$id",d]].filter(([s,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!isArray(a))throw new Error("Typedb fetch has changed its format");if(a.length===0)return r.query?.returnNulls?[[l,null]]:[];h.contentType==="DATE"?d=a.map(s=>`${s.value}Z`):h.contentType==="FLEX"?d=a.map(s=>s.type.value_type==="datetime"?`${s.value}Z`:s.value):h.contentType==="JSON"?d=a.map(s=>s.value&&JSON.parse(s.value)):d=a.map(s=>s.value);}return [[l,d]].filter(([s,f])=>f!==void 0)}).flat();return Object.fromEntries([...n])},Wt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:c,$cardinality:a}=o,{as:h,justId:p,idNotIncluded:l,filterByUnique:d}=$n(c);if(h===null)return;let s=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return l==="true"&&$?.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});s.length>0?i[h]=a==="MANY"&&d==="false"?s:s[0]:r.query?.returnNulls&&(i[h]=null);}),i},_t=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:c,$cardinality:a}=o,{as:h,justId:p,idNotIncluded:l,filterByUnique:d}=$n(c);if(h===null)return;let s=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return l==="true"&&$.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});i[h]=s.length>0?a==="MANY"&&d==="false"?s:s[0]:r.query?.returnNulls?null:void 0;}),i},$n=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),c=e.match(r),a=e.match(i),h=e.match(o);return {as:n?n[1]:null,justId:c?c[1]:null,idNotIncluded:a?a[1]:null,filterByUnique:h?h[1]:null}},eo=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,(c,a,h)=>/^{.*}$/.test(h)?`:${h}`:`:${a}"${h}"`),n=n.replace(/\[([^\]]+)\]/g,(c,a)=>`[${a.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var mn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ge(r,i),c=await n.transaction(TransactionType.READ,o),[a,h]=await tryit(parallel)(t.length,t,async p=>await c.query.fetch(p).collect());if(a){await c.rollback();let p=a;throw new Error(`Error running TQL query: ${p.errors}`)}return await c.close(),h};var oo=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,so=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,ao=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,zt=H("error","error",V((e,t)=>({...e,error:t.error}))),lo=we("build",{build:Z(async e=>un({queries:e.bql.queries,schema:e.schema}),H("done","run",V(so)),zt),run:Z(async e=>mn({dbHandles:e.handles,tqlRequest:ae(e.tql.queries),config:e.config}),H("done","parse",V(ao)),zt),parse:Z(async e=>fn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ae(e.tql.res)}),H("done","success",V(oo)),zt),success:he(),error:he()},e=>e),co=async e=>new Promise((t,r)=>{ye(lo,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),yn=async(e,t,r,i,o)=>co({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var ho=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Vt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ot=H("error","error",V((e,t)=>({...e,error:t.error}))),uo=we("enrich",{enrich:Z(async e=>Jr(e.bql.raw,e.schema),H("done","adapter",V(ho)),ot),adapter:Z(async e=>{let t={};e.bql.queries?.forEach((a,h)=>{let p=e.bql.raw[h],l=G(e.schema,a.$thing),{id:d}=l.defaultDBConnector;if(l.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${l.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(l.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${l.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${l.db}"`);let s=t[d];s.rawBql.push(p),s.bqlQueries.push(a),s.indices.push(h);});let r=Object.values(t),i=r.map(a=>{if(a.db==="typeDB")return yn(a.rawBql,a.bqlQueries,e.schema,e.config,e.handles);if(a.db==="surrealDB")return dn(a.bqlQueries,e.schema,e.config,a.client);throw new Error("Unsupported DB provider")}),o=await Promise.all(i),n=r.flatMap((a,h)=>{let p=o[h];return a.indices.map((l,d)=>({index:l,result:p[d]}))});return n.sort((a,h)=>a.index<h.index?-1:a.index>h.index?1:0),n.map(({result:a})=>a)},H("done","postHooks",V(Vt)),ot),postHooks:Z(async e=>vr(e.schema,ae(e.bql.queries),ae(e.bql.res)),H("done","clean",V(Vt)),ot),clean:Z(async e=>Kr(e.config,ae(e.bql.res)),H("done","success",V(Vt)),ot),success:he(),error:he()},e=>e),po=async e=>new Promise((t,r)=>{ye(uo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),je=async(e,t,r,i)=>po({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Ht="___",fo=Symbol.for("grandChildOfCreate"),gn=async(e,t,r,i)=>{let o=(F,Q)=>Object.keys(F).filter(E=>!E.startsWith("$")&&F[E]!==void 0?Q?!q(t,F).dataFields?.find(M=>M.path===E):!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:F,key:Q,value:E})=>{F&&Q&&!Q.includes("$")&&isObject(F)?(Array.isArray(F[Q])?F[Q]:[F[Q]]).forEach(M=>{if(isObject(M)){if(F.$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`)}}):!F&&isObject(E)&&(n.includes(E.$op)||n.push(E.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let a=(F=>{let Q=(E,b)=>{let M=[],R={},k=["$op","$bzId","$parentKey"],L=["$relation","$entity","$id",...k];for(let N in E)if(!k.includes(N)&&!(L.includes(N)&&!b))if(!N.includes("$")&&(isObject(E[N])||Array.isArray(E[N]))){let J=E[N];if(Array.isArray(J)&&J.length>0)J.forEach(ce=>{let Qe={$path:N,...Q(ce),...ce.$filter&&{$as:ce.$bzId}};M.find(U=>U.$path===Qe.$path&&!U.$filter)||(M=[...M,Qe]);});else {let ce={$path:N,...Q(J),...!J.$filter&&{$as:J.$bzId}};M=[...M,ce];}}else R[N]=E[N];return {...R,$fields:M}};return F.map(E=>Q(E,!0))})(Array.isArray(e)?e:[e]),p=(await je(a,t,{...r,query:{...r.query,returnNulls:!0}},i)).bql.res,l=(F,Q)=>{let E=F.$id||F.id||F.$bzId;if(F.$objectPath){let{$objectPath:b}=F,M=b?.beforePath||"root",R=Array.isArray(b.ids)?`[${b.ids}]`:b.ids;return {beforePath:`${M}.${R}___${b.key}`,ids:E,key:Q}}else return {beforePath:"root",ids:E,key:Q}},d=(F,Q)=>{let E=F?.beforePath||"root";if(typeof E!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let b=(Array.isArray(F?.ids)?`[${F?.ids}]`:F?.ids);return `${E}.${b}___${F?.key}`},s=F=>{if(F.includes("[")&&F.includes("]")){let[Q,E,b]=F.split(/[[\]]/);return E.split(",").map(R=>`${Q}${R}${b}`)}else return [F]},f={};(F=>produce(F,Q=>traverse(Q,({key:E,parent:b})=>{if(b&&E&&b.$id&&!E.includes("$")){let M=l(b,E),R=d(M);if(Array.isArray(b[E])){let k=[];b[E].forEach(L=>{isObject(L)?(L.$objectPath=M,k.push(L.$id.toString())):L&&k.push(L.toString());}),f[R]={$objectPath:M,$ids:k};}else {let k=b[E];isObject(k)?(f[R]={$objectPath:M,$ids:[k.$id.toString()]},k.$objectPath=M):k?f[R]={$objectPath:M,$ids:[k.toString()]}:k===null&&(f[R]=null);}}})))(p||{});let $=F=>produce(F,Q=>traverse(Q,({key:E,value:b,parent:M})=>{M&&E&&!E.includes("$")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(M)&&(Array.isArray(M[E])?M[E].forEach(R=>{typeof R!="string"&&(R.$objectPath=l(M,E),R.$parentIsCreate=M.$op==="create",R[fo]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[E])&&(M[E].$parentIsCreate=M.$op==="create",M[E][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[E].$objectPath=l(M,E)));})),y=$(e),m=F=>{let Q=[];return F.forEach(b=>{if(!b.$id&&!b.id&&!b.$tempId)if(b.$filter){let M=d({...b.$objectPath,key:b.$bzId}),R=f[M];R&&(Array.isArray(R.$ids)?R.$ids:[R.$ids]).forEach(L=>{let N={...b,$id:L,$bzId:`T4_${v4()}`,$filterBzId:b.$bzId};Q.push(N);});}else {let M=d(b.$objectPath),R=f[M];R?R?.$ids?.forEach(k=>{let L={...b,$id:k,$bzId:`T4_${v4()}`};Q.push(L);}):Q.push(b);}else Q.push(b);}),Q.map(b=>{let M={...b};return o(M,!0).forEach(R=>{let k=Array.isArray(M[R])?M[R]:[M[R]],L=m(k);M[R]=L;}),M})},B=m(Array.isArray(y)?y:[y]),w=$(B),S=(F=>{let Q=E=>{let b=U=>{let ee=[],z=[],P=[];return U.forEach(j=>{let se=o(j,!0);if(se.length>0){let I=!1;se.forEach(_=>{(Array.isArray(j[_])?j[_]:[j[_]]).filter(Y=>!Y.$id&&!Y.id&&typeof j=="object").length&&(I=!0);}),I?ee.push(j):z.push(j);}else j.$id?P.push({...j,$bzId:j.$tempId||j.$bzId}):P.push({...j,$bzId:j.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:P}},{operationWithMultiples:M,operationWithoutMultiples:R,otherOps:k}=b(E),L=U=>{let z=(()=>{let _={};for(let re in U){let v=q(t,U);!re.startsWith("$")&&v.dataFields?.find(Y=>Y.path===re)&&(_[re]=U[re]);}return _})(),P=Object.keys(U),j=o(U,!0),se=[],I=(_,re)=>{if(_===j.length){let Y={...re};P.forEach(ne=>{ne.startsWith("$")&&(Y[ne]=U[ne]);}),se.push({...Y,...z});return}let v={...re,[j[_]]:U[j[_]],...Fe(re),...z};I(_+1,v),I(_+1,re);};return I(0,{...Fe(U)}),se},N=[];return M.forEach(U=>{let ee=L(U),z=[];ee.forEach(P=>{let j=o(P,!0);if(P.$op==="create")z.push(P);else if(P.$id){let se=d(P.$objectPath),I=[];if(j.forEach(_=>{let re=`${se.includes("undefined")?"root":se}.${P.$id}${Ht}${_}`,v=f[re];P[_].filter(ne=>ne.$op==="unlink"||ne.$op==="delete"||ne.$op==="update").length>0?v?.$ids&&I.push({key:_,ids:v.$ids}):I.push({key:_,ids:[""]});}),I.length===j.length&&!z.find(_=>_.$id===P.$id))z.push(P);else {let _={...P,$bzId:P.$tempId||`T4_${v4()}`};j.forEach(v=>{let Y=P[v].filter(ne=>ne.$id);Y.length>0?_[v]=Y:_[v]=void 0;}),o(_,!0).length>0&&z.push(_);}}else if(P.$objectPath){let se=d(P.$objectPath),I=f[se]?.$ids||[];I.forEach(_=>{let re=[];j.forEach(v=>{let Y=`${se}.${_}${Ht}${v}`,ne=f[Y];ne&&re.push({key:v,ids:ne.$ids});}),j.length===0?I.filter(Y=>!z.find(ne=>ne.$id===Y)).forEach(Y=>{z.push({...P,$id:Y,$bzId:P.$tempId||`PQT2_${v4()}`});}):re.length===j.length&&!z.find(v=>v.$id===_)&&(j.forEach(v=>{let Y=`${d(P.$objectPath)}.${_}${Ht}${v}`,ne=f[Y]?.$ids||[],An=P[v].find(De=>!De.$id),Jt=[...ne.map(De=>({...An,$id:De,$objectPath:{beforePath:P.$objectPath.beforePath,ids:De,key:v}})),...P[v].filter(De=>De.$id)];Jt.length>0&&(P[v]=Jt);}),z.push({...P,$id:_,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else z.push(P);}),z.forEach(P=>{N.push(P);});}),[...N,...R,...k].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let P=Array.isArray(ee[z])?ee[z]:[ee[z]],j=Q(P);ee[z]=j;}),ee})};return Q(F)})(Array.isArray(w)?w:[w]),C=F=>F.map(Q=>{let E=o(Q,!0),b={...Q};return E.forEach(M=>{let R=Array.isArray(Q[M])?Q[M]:[Q[M]],k=[],L=[],N=[],J={},ce=ft(t,Q,M);R.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?L=[...L,...I.$id]:L.push(I.$id)):I.$op==="create"&&ce==="ONE"&&I.id?(J=I,Array.isArray(I.id)?N=[...L,...I.id]:N.push(I.id)):k.push(I);});let Qe=d(J.$objectPath),ee=s(Qe).map(I=>f[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I?.$ids||[]];});let P=z.filter(I=>!L.includes(I)),j=L.filter(I=>!z.includes(I)),se=Fe(J);P.length>0&&k.push({...J,$op:"unlink",$id:P,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...se}),j.length>0&&j.forEach(I=>{k.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${v4()}`,...se});}),N.length>0&&N.forEach(I=>{k.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${v4()}`,...se});}),b[M]=C(k);}),b}),A=$(C($(S)));(F=>produce(F,Q=>traverse(Q,E=>{let{key:b,value:M,parent:R}=E;b&&R&&!b?.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(R)&&(Array.isArray(M)?M:[M]).forEach(L=>{let N=L.$filter?{...L.$objectPath,key:L.$filterBzId}:L.$objectPath,J=d(N),ce=f[J],Qe=(z,P)=>z.every(j=>P.includes(j)),U=L.$id?Array.isArray(L.$id)?Qe(L.$id,ce&&ce.$ids?ce.$ids:[]):ce?.$ids?.includes(L.$id):ce,ee=ft(t,R,L.$objectPath.key);if(L.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(L.$objectPath)}" because it is already occupied.`);if(L.$op)switch(L.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${L.$id}" because it is already linked to $id:"${R.$id}"`);break;}});})))(A);let W=(F=>produce(F,Q=>traverse(Q,E=>{let{value:b,meta:M}=E;isObject(b)&&(b[Symbol.for("path")]=M.nodePath,delete b.$objectPath,delete b.$parentIsCreate);})))(A);return [...Array.isArray(W)?W:[W]].sort((F,Q)=>F.$op==="create"&&Q.$op!=="create"?-1:F.$op!=="create"&&Q.$op==="create"?1:0)};var En=(e,t)=>produce(e,i=>at(t,i)),at=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>at(e,o,r));return}let i=G(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||mo(e,t,o,i);});},mo=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(a=>a.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let c=i.linkFields?.find(a=>a.path===r);if(c){let a=c.oppositeLinkFieldsPlayedBy[0]?.thing;at(e,o,a);return}if(i.thingType==="relation"){let a=i.roles[r];if(!a)throw new Error(`[Schema] Role ${r} in ${i.name} is not defined`);let[h]=a.playedBy||[];if(!h)throw new Error(`Role ${a.path} in ${i} is not played by anything`);at(e,o,h.thing);}};var wn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(h=>Kt(h,!0)),a=(await je(n,t,r,i)).bql.res;return o.map((h,p)=>{let l=G(t,h.$thing);return Tn({mut:h,node:a[p],schema:t,thing:l})})},Mn=new Set(["$op","$bzId","$parentKey"]),go=new Set(["$relation","$entity","$id",...Mn]),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(Mn.has(o)||go.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},Tn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=Sn(o),c=Bo(r);if(Array.isArray(t))return t.map(h=>{let p=c[h.$id];return p?Bn({mut:h,node:p,schema:i,thing:o,...n}):h});let a=c[t.$id];return Bn({mut:t,node:a,schema:i,thing:o,...n})},Bn=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}=e,{$fields:h,...p}=t;if(!r)return p;let l=Qn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}),d={...p,[Ae]:l};for(let s in t){if(s.startsWith("$"))continue;let f=t[s];if(n[s]||!f||typeof f!="object"){d[s]=f;continue}let $=c[s]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[s]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${s}"`);let y=G(i,$);d[s]=Tn({mut:f,schema:i,node:r[s],thing:y});}return d},Qn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}=e,h=t||Eo(o),p={$id:r.$id};return h.forEach(l=>{let d=typeof l!="string",s=d?l.$path:l,f=r[s];if(n[s]){p[s]=f;return}let $=c[s]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[s]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${s}"`);if(!d){f&&(p[s]=Array.isArray(f)?f.map(Fn):Fn(f));return}let y=G(i,$),m=Sn(y);p[s]=Array.isArray(f)?f.map(B=>bn({...m,$fields:l.$fields,value:B,schema:i,thing:y})):bn({...m,$fields:l.$fields,value:f,schema:i,thing:y});}),p},Eo=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},Fn=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},bn=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 Qn({...e,node:t})},Sn=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}},Bo=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 Ln=he,Ne=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Fo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),bo=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),wo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Mo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),To=async e=>Object.keys(e.bql.current).length?Et(e.bql.current,e.schema,e.config):Et(e.bql.raw,e.schema,e.config),Qo=async e=>gn(e.bql.current,e.schema,e.config,e.handles),So=async e=>wn(e.bql.current,e.schema,e.config,e.handles),Lo=async e=>Lr(e.bql.current,e.schema),Ro=async e=>Cr(e.bql.things,e.bql.edges,e.schema),Co=async e=>br(e.typeDB.tqlMutation,e.handles,e.config),Do=async e=>wr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Ao=()=>!0,Io=e=>Pe(e.bql.current),Te=H("error","error",V((e,t)=>({...e,error:t.error}))),ko=we("stringify",{stringify:Z(async e=>En(e.bql.raw,e.schema),H("done","enrich",V(Ne)),Te),enrich:Z(To,H("done","preQuery",bt(Ao),V(Ne)),H("done","parseBQL",V(Ne)),Te),preQuery:Z(Qo,H("done","preHookDependencies",bt(Io),V(Ne)),H("done","parseBQL",V(Ne)),Te),preHookDependencies:Z(So,H("done","enrich",V(Ne)),Te),parseBQL:Z(Lo,H("done","buildMutation",V(bo)),Te),buildMutation:Z(Ro,H("done","runMutation",V(wo)),Te),runMutation:Z(Co,H("done","parseMutation",V(Mo)),Te),parseMutation:Z(Do,H("done","success",V(Fo)),Te),success:Ln(),error:Ln()},e=>e),Oo=async e=>new Promise((t,r)=>{ye(ko,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),Rn=async(e,t,r,i)=>Oo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Ut=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,{namespace:i.namespace,database:i.dbName,auth:{namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}}),t.surrealDB.set(i.id,{client:o,providerConfig:i.providerConfig});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let c=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(c)}try{let c=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:c});}catch(c){let a=`[BORM:${i.provider}:${i.dbName}:session] ${(c.messageTemplate?._messageBody()||c.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,c]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let a=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await c.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:c,session:a});}catch(a){let h=`[BORM:${i.provider}:${i.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let r=ir(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(),Zt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...ct.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[c,a]=await tryit(je)(n,this.schema,i,this.dbHandles);if(c){let p=new Error(c.error);throw p.stack=c.error.stack,p}let h=a.bql.res;return o?h:h[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...ct.mutation,...this.config.mutation,...r}},[o,n]=await tryit(Rn)(t,this.schema,i,this.dbHandles);if(o){let a=new Error(o.error.message);throw a.stack=o.error.stack,a}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();});}},Kc=Ut;//! Todo: delete when this works with the new $thing and $thingType fields
54
54
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
55
55
  //! Todo: Sandbox the function in computeFunction()
56
56
  //! reads all the insertions and gets the first match. This means each id must be unique