@blitznocode/blitz-orm 0.12.3 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,38 +1,38 @@
1
1
  import { isObject, isArray, mapEntries, isDate, tryit, parallel, shake, clone, listify, pick, isSymbol } from 'radash';
2
2
  import { TypeDBOptions, TransactionType, SessionType, TypeDB, TypeDBCredential } from 'typedb-driver';
3
- import yr from 'dayjs';
3
+ import wi from 'dayjs';
4
4
  import { enableMapSet, produce, isDraft, current } from 'immer';
5
5
  import { traverse, getNodeByPath } from 'object-traversal';
6
6
  import { customAlphabet } from 'nanoid';
7
7
  import { isSet } from 'util/types';
8
8
  import 'acorn';
9
9
  import { v4 } from 'uuid';
10
- import Zs from 'surrealdb';
10
+ import ta from 'surrealdb';
11
11
 
12
- var wt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Bi=e=>{let t=[],r=new Map;return e.forEach(n=>{let{dbPath:a,contentType:i}=n,s=`${a}-${i}`;r.has(s)||(r.set(s,!0),t.push(n));}),t},Fi=(e="default",t)=>{let r="",n=[];r+=`
13
- `,Object.keys(t.entities).filter(o=>t.entities[o].defaultDBConnector.id===e).forEach(o=>{let d=t.entities[o],{dataFields:h,linkFields:c,name:u}=d;if(r+=`${u} sub ${"extends"in d?d.extends:"entity"},
12
+ var wt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Bi=e=>{let t=[],r=new Map;return e.forEach(n=>{let{dbPath:o,contentType:i}=n,a=`${o}-${i}`;r.has(a)||(r.set(a,!0),t.push(n));}),t},Fi=(e="default",t)=>{let r="",n=[];r+=`
13
+ `,Object.keys(t.entities).filter(s=>t.entities[s].defaultDBConnector.id===e).forEach(s=>{let d=t.entities[s],{dataFields:h,linkFields:c,name:u}=d;if(r+=`${u} sub ${"extends"in d?d.extends:"entity"},
14
14
  `,h&&h.length>0&&h.forEach(l=>{l.contentType!=="REF"&&(l.inherited||(l.isIdField?r+=` owns ${l.dbPath} @key,
15
15
  `:r+=` owns ${l.dbPath},
16
16
  `,n.push({dbPath:l.dbPath,contentType:l.contentType})));}),c&&c.length>0){let l=[];c.forEach(p=>{let{relation:f,plays:$,inherited:E}=p;if(E)return;!t.relations[f].roles[$].inherited&&!l.includes(`${f}:${$}`)&&(r+=` plays ${f}:${$},
17
17
  `,l.push(`${f}:${$}`));});}r=r.replace(/,\s*$/,`;
18
18
  `),r+=`
19
- `;}),Object.keys(t.relations).filter(o=>t.relations[o].defaultDBConnector.id===e).forEach(o=>{let d=t.relations[o],{dataFields:h,roles:c,name:u,linkFields:l}=d;if(r+=`${u} sub ${"extends"in d?d.extends:"relation"},
19
+ `;}),Object.keys(t.relations).filter(s=>t.relations[s].defaultDBConnector.id===e).forEach(s=>{let d=t.relations[s],{dataFields:h,roles:c,name:u,linkFields:l}=d;if(r+=`${u} sub ${"extends"in d?d.extends:"relation"},
20
20
  `,h&&h.length>0&&h.forEach(p=>{p.inherited||(p.isIdField?r+=` owns ${p.dbPath} @key,
21
21
  `:r+=` owns ${p.dbPath},
22
22
  `,n.push({dbPath:p.dbPath,contentType:p.contentType}));}),c&&Object.keys(c).forEach(p=>{c[p].inherited||(r+=` relates ${p},
23
23
  `);}),l&&l.length>0){let p=[];l.forEach(f=>{let{plays:$,relation:E}=f;!t.relations[E].roles[$].inherited&&!f.inherited&&!p.includes(`${E}:${$}`)&&(r+=` plays ${f.relation}:${$},
24
24
  `,p.push(`${E}:${$}`));});}r=r.replace(/,\s*$/,`;
25
25
  `),r+=`
26
- `;});let a=`define
26
+ `;});let o=`define
27
27
 
28
- `;return Bi(n).forEach(o=>{if(o.contentType==="TEXT"||o.contentType==="ID"||o.contentType==="JSON")a+=`${o.dbPath} sub attribute, value string;
29
- `;else if(o.contentType==="EMAIL")a+=`${o.dbPath} sub attribute, value string,
30
- `,a+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';
31
- `;else if(o.contentType==="DATE")a+=`${o.dbPath} sub attribute, value datetime;
32
- `;else if(o.contentType==="BOOLEAN")a+=`${o.dbPath} sub attribute, value boolean;
33
- `;else if(o.contentType==="NUMBER")a+=`${o.dbPath} sub attribute, value long;
34
- `;else if(o.contentType==="FLEX")a+=`${o.dbPath} sub flexAttribute;
35
- `;else {if(o.contentType==="REF")return;throw new Error(`Conversion of borm schema to TypeDB schema for data type "${o.contentType}" is not implemented`)}}),`${a}
28
+ `;return Bi(n).forEach(s=>{if(s.contentType==="TEXT"||s.contentType==="ID"||s.contentType==="JSON")o+=`${s.dbPath} sub attribute, value string;
29
+ `;else if(s.contentType==="EMAIL")o+=`${s.dbPath} sub attribute, value string,
30
+ `,o+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';
31
+ `;else if(s.contentType==="DATE")o+=`${s.dbPath} sub attribute, value datetime;
32
+ `;else if(s.contentType==="BOOLEAN")o+=`${s.dbPath} sub attribute, value boolean;
33
+ `;else if(s.contentType==="NUMBER")o+=`${s.dbPath} sub attribute, value long;
34
+ `;else if(s.contentType==="FLEX")o+=`${s.dbPath} sub flexAttribute;
35
+ `;else {if(s.contentType==="REF")return;throw new Error(`Conversion of borm schema to TypeDB schema for data type "${s.contentType}" is not implemented`)}}),`${o}
36
36
 
37
37
  ${r}
38
38
  #Tools, reserved for every schema using borm
@@ -48,29 +48,29 @@ flexAttribute sub attribute, abstract, value string,
48
48
  owns doubleAttribute,
49
49
  owns booleanAttribute,
50
50
  owns datetimeAttribute;
51
- `},fr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let a=Fi(e,r),i=n.typeDB.get(e)?.session,s=n.typeDB.get(e)?.client;if(!i){console.log("Session Status: ","NO SESSION");return}if(!s)throw new Error("No TypeDB client found");await i.close();let[{dbName:o}]=t.dbConnectors;await(await s.databases.get(o)).delete(),await s.databases.create(o);let c=await(await s.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(a),await c.commit(),await c.close(),a};var $r=e=>e.replace(/`/g,""),bi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],te=e=>bi.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var Tt=e=>{if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return `'${e}'`;if(["number","boolean"].includes(typeof e))return e;throw new Error(`Unsupported type ${typeof e}`)};var gr={TEXT:"string",RICH_TEXT:"string",LANGUAGE_TEXT:"string",PASSWORD:"string",URL:"string",PHONE:"string",ID:"string",EMAIL:"string",NUMBER:"number",NUMBER_DECIMAL:"decimal",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},je=(e,t)=>{if(e===null)return "NONE";if(t)switch(t){case"TEXT":case"RICH_TEXT":case"LANGUAGE_TEXT":case"PASSWORD":case"URL":case"PHONE":case"ID":case"EMAIL":if(typeof e!="string")throw new Error(`Invalid value for TEXT type: ${e}`);return JSON.stringify(e);case"NUMBER":case"NUMBER_DECIMAL":case"BOOLEAN":case"JSON":return e;case"DATE":return typeof e=="string"&&yr(e,"YYYY-MM-DDTHH:mm:ssZ",!0).isValid()?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`$<datetime>"${e}"`;case"FLEX":{if(typeof e=="string"&&yr(e,"YYYY-MM-DDTHH:mm:ssZ",!0).isValid())return `<datetime>"${e}"`;let r=isArray(e)?e.map(n=>Tt(n)):Tt(e);return `${isArray(r)?r.map(n=>n):r}`}default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var Mi=" ",ke=e=>Mi.repeat(e),it=(e,t)=>e.split(`
51
+ `},fr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let o=Fi(e,r),i=n.typeDB.get(e)?.session,a=n.typeDB.get(e)?.client;if(!i){console.log("Session Status: ","NO SESSION");return}if(!a)throw new Error("No TypeDB client found");await i.close();let[{dbName:s}]=t.dbConnectors;await(await a.databases.get(s)).delete(),await a.databases.create(s);let c=await(await a.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(o),await c.commit(),await c.close(),o};var $r=e=>e.replace(/`/g,""),bi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],te=e=>bi.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var Tt=e=>{if(typeof e=="string"&&wi(e,"YYYY-MM-DDTHH:mm:ssZ",!0).isValid())return `<datetime>"${e}"`;if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return JSON.stringify(e);if(["number","boolean"].includes(typeof e))return e;throw new Error(`Unsupported type ${typeof e}`)};var yr={TEXT:"string",RICH_TEXT:"string",LANGUAGE_TEXT:"string",PASSWORD:"string",URL:"string",PHONE:"string",ID:"string",EMAIL:"string",NUMBER:"number",NUMBER_DECIMAL:"decimal",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},je=(e,t)=>{if(e===null)return "NONE";if(t)switch(t){case"TEXT":case"RICH_TEXT":case"LANGUAGE_TEXT":case"PASSWORD":case"URL":case"PHONE":case"ID":case"EMAIL":if(typeof e!="string")throw new Error(`Invalid value for TEXT type: ${e}`);return JSON.stringify(e);case"NUMBER":case"NUMBER_DECIMAL":case"BOOLEAN":case"JSON":return e;case"DATE":return typeof e=="string"&&wi(e,"YYYY-MM-DDTHH:mm:ssZ",!0).isValid()?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`$<datetime>"${e}"`;case"FLEX":{let r=isArray(e)?e.map(n=>Tt(n)):Tt(e);return `${isArray(r)?r.map(n=>n):r}`}default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var Li=" ",ke=e=>Li.repeat(e),nt=(e,t)=>e.split(`
52
52
  `).map(r=>r.trim()?`${ke(t)}${r}`:r).join(`
53
- `),Si=e=>{let t=`USE NS test;
53
+ `),Qi=e=>{let t=`USE NS test;
54
54
  USE DB test;
55
55
 
56
56
  BEGIN TRANSACTION;
57
57
  `,r=`-- ENTITIES
58
- ${Er(e.entities)}`,n=`
58
+ ${gr(e.entities)}`,n=`
59
59
  -- RELATIONS
60
- ${Er(e.relations)}`,a=Oi();return `${t}${r}${n}${a}COMMIT TRANSACTION;`},Er=e=>Object.entries(e).map(([t,r])=>Li(te(t),r,1)).join(`
60
+ ${gr(e.relations)}`,o=ki();return `${t}${r}${n}${o}COMMIT TRANSACTION;`},gr=e=>Object.entries(e).map(([t,r])=>Ri(te(t),r,1)).join(`
61
61
 
62
- `),Li=(e,t,r)=>{let n=`${ke(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,a=it(`-- DATA FIELDS
63
- ${Qi(t.dataFields??[],e,r)}`,r+1),i=it(`
62
+ `),Ri=(e,t,r)=>{let n=`${ke(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,o=nt(`-- DATA FIELDS
63
+ ${Di(t.dataFields??[],e,r)}`,r+1),i=nt(`
64
64
  -- LINK FIELDS
65
- ${Ri(t.linkFields??[],e,r)}`,r+1),s="roles"in t?it(`
65
+ ${Ii(t.linkFields??[],e,r)}`,r+1),a="roles"in t?nt(`
66
66
  -- ROLES
67
- ${Di(t.roles,e,r)}`,r+1):"";return `${n}
68
- ${a}${i}${s}`},Qi=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let a=Ci(n.contentType,n.validations),i=`${ke(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${i} VALUE ${s};`:""}return `${i} TYPE ${a};`}).filter(Boolean).join(`
69
- `),Ri=(e,t,r)=>e.map(n=>{let a=n.cardinality==="MANY"?`option<array<record<${n.$things.map(te).join("|")}>>>`:`option<record<${n.$things.map(te).join("|")}>>`,i=`${ke(r)}DEFINE FIELD ${te(n.path)} ON TABLE ${t}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${i} VALUE ${s};`:""}if(n.target==="role"){let s=e.find(f=>f.target==="relation"&&f.relation===n.relation),d=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!d||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let h=n.cardinality==="ONE"?`record<${te(n.relation)}>`:`array<record<${te(n.relation)}>>`,c=te(n.pathToRelation||""),u=`${c}.${d}`,l=n.cardinality==="ONE"?`${i} VALUE <future> {RETURN SELECT VALUE ${u} FROM ONLY $this};`:`${i} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${u} || []) FROM ONLY $this)};`,p=s?.path?"":`${ke(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${h}>;`;return [l,p].join(`
70
- `)}if(n.target==="relation")return `${`${ke(r)}DEFINE FIELD ${te(n.path)} ON TABLE ${t} TYPE ${a};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
71
- `),Di=(e,t,r)=>Object.entries(e).map(([n,a])=>{let i=a.cardinality==="MANY"?`array<record<${a.$things.map(te).join("|")}>>`:`record<${a.$things.map(te).join("|")}>`,s=`${ke(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,o=Ii(n,t,a,r);return `${s}
72
- ${o}`}).join(`
73
- `),Ii=(e,t,r,n)=>{let a=`update_${e}`,i=r.playedBy?.find(F=>F.target==="relation"),s=i?.pathToRelation,o=r.playedBy?.find(F=>F.target==="role"),d=o?.pathToRelation,h=i??o;if(!h)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=te(s??d),u=(F,m)=>F.map(({path:S,cardinality:M})=>`${S} ${m==="remove"?M==="ONE"?"=":"-=":M==="ONE"?"=":"+="} ${m==="remove"?M==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),l=r.impactedLinkFields?.map(F=>({path:F.path,cardinality:F.cardinality}))||[],f=[{path:c,cardinality:h.cardinality},...l],$=u(f,"remove"),E=u(f,"add"),g=`
67
+ ${Ci(t.roles,e,r)}`,r+1):"";return `${n}
68
+ ${o}${i}${a}`},Di=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let o=Ai(n.contentType,n.validations),i=`${ke(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}return `${i} TYPE ${o};`}).filter(Boolean).join(`
69
+ `),Ii=(e,t,r)=>e.map(n=>{let o=n.cardinality==="MANY"?`option<array<record<${n.$things.map(te).join("|")}>>>`:`option<record<${n.$things.map(te).join("|")}>>`,i=`${ke(r)}DEFINE FIELD ${te(n.path)} ON TABLE ${t}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}if(n.target==="role"){let a=e.find(f=>f.target==="relation"&&f.relation===n.relation),d=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!d||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let h=n.cardinality==="ONE"?`record<${te(n.relation)}>`:`array<record<${te(n.relation)}>>`,c=te(n.pathToRelation||""),u=`${c}.${d}`,l=n.cardinality==="ONE"?`${i} VALUE <future> {RETURN SELECT VALUE ${u} FROM ONLY $this};`:`${i} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${u} || []) FROM ONLY $this)};`,p=a?.path?"":`${ke(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${h}>;`;return [l,p].join(`
70
+ `)}if(n.target==="relation")return `${`${ke(r)}DEFINE FIELD ${te(n.path)} ON TABLE ${t} TYPE ${o};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
71
+ `),Ci=(e,t,r)=>Object.entries(e).map(([n,o])=>{let i=o.cardinality==="MANY"?`array<record<${o.$things.map(te).join("|")}>>`:`record<${o.$things.map(te).join("|")}>`,a=`${ke(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,s=Oi(n,t,o,r);return `${a}
72
+ ${s}`}).join(`
73
+ `),Oi=(e,t,r,n)=>{let o=`update_${e}`,i=r.playedBy?.find(F=>F.target==="relation"),a=i?.pathToRelation,s=r.playedBy?.find(F=>F.target==="role"),d=s?.pathToRelation,h=i??s;if(!h)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=te(a??d),u=(F,m)=>F.map(({path:S,cardinality:M})=>`${S} ${m==="remove"?M==="ONE"?"=":"-=":M==="ONE"?"=":"+="} ${m==="remove"?M==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),l=r.impactedLinkFields?.map(F=>({path:F.path,cardinality:F.cardinality}))||[],f=[{path:c,cardinality:h.cardinality},...l],$=u(f,"remove"),E=u(f,"add"),g=`
74
74
  IF ($before.${e}) THEN {UPDATE $before.${e} SET ${$}} END;
75
75
  IF ($after.${e}) THEN {UPDATE $after.${e} SET ${E}} END;`,y=`
76
76
  LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
@@ -78,8 +78,8 @@ ${o}`}).join(`
78
78
  FOR $link IN $edges.additions {${h.cardinality==="ONE"?`
79
79
  IF ($link.${c}) THEN {UPDATE $link.${c} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
80
80
  UPDATE $link SET ${E};
81
- };`;return it(`DEFINE EVENT ${a} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?g:y}
82
- };`,n+1)},Ci=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>je(n,e)).join("|")}`:gr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},Oi=()=>`
81
+ };`;return nt(`DEFINE EVENT ${o} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?g:y}
82
+ };`,n+1)},Ai=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>je(n,e)).join("|")}`:yr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},ki=()=>`
83
83
  -- BORM TOOLS
84
84
  DEFINE FUNCTION fn::get_mutated_edges(
85
85
  $before_relation: option<array|record>,
@@ -101,27 +101,27 @@ ${o}`}).join(`
101
101
  DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
102
102
  RETURN (type::is::array($var) AND $var) OR [$var]
103
103
  };
104
- `,Br=e=>Si(e);var Fr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([d])=>[d,await fr(d,e,t,r)]))).map(d=>[d[0],d[1]]),o=(await Promise.all([...r.surrealDB||[]].map(async([d])=>[d,Br(t)]))).map(d=>[d[0],d[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(o)}})();var ee=Symbol.for("queryPath"),ot=Symbol.for("stepPrint"),qe=Symbol.for("edgeType"),Me=Symbol.for("edgeSchema"),_e=Symbol.for("dbNode"),Mt=Symbol.for("isTransformed"),st=Symbol.for("parent"),ie=Symbol.for("fieldSchema"),z=Symbol.for("sharedMetadata"),De=Symbol.for("suqlMetadata");var br={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var wr=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let a=r.relations[e.relation].subTypes||[],i=[e.relation,...a],s=`<-\u27E8${t}_${e.plays}\u27E9<-(\u27E8${i.join("\u27E9,\u27E8")}\u27E9)`;if(e.target==="relation"){if(n==="edges")return s;if(n==="refs")return e.cardinality==="MANY"?`$parent.[\`${e.path}\`]`:`$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[o]=e.oppositeLinkFieldsPlayedBy,d=r.entities[o.thing]?.subTypes||r.relations[o.thing]?.subTypes||[],h=[o.thing,...d],c=`->\u27E8${t}_${o.plays}\u27E9->(\u27E8${h.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${s}${c}`:n==="refs"?e.cardinality==="MANY"?`$parent.[\`${o.plays}\`]`:`$parent.\`${o.plays}\``:`${s}${c}`}else throw new Error("Unsupported linkField target")};var Sr=(e,t,r)=>r?t:`${e}\xB7${t}`;var Qr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ce=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,a])=>{let[i,s]=tryit(()=>t(n,a))();return i?!1:s}))},Rr=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:s,value:o,meta:d})=>{if(d.depth!==2)return;let h=o;if(s&&(h.dataFields=h.dataFields?.map(c=>({...c,...h.idFields?.includes(c.path)?{isIdField:!0}:{isIdField:!1},cardinality:c.cardinality||"ONE",dbPath:"dbPath"in c?c.dbPath:Sr(s,c.path,c.shared),[z]:{fieldType:"dataField"}})),h.refFields=mapEntries(h.refFields||{},(c,u)=>[c,{...u,cardinality:u.cardinality||"ONE",path:c,[z]:{fieldType:"refField"}}]),h.linkFields=h.linkFields?.map(c=>({...c,[z]:{fieldType:"linkField"}})),"roles"in h&&(h.roles=mapEntries(h.roles||{},(c,u)=>[c,{...u,cardinality:u.cardinality||"ONE",[z]:{fieldType:"roleField"}}]))),o.extends){if(!o.defaultDBConnector.as)throw new Error(`[Schema] ${s} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${d.nodePath}`);let c=i.entities[o.extends]||i.relations[o.extends],u=[o.extends,...c.allExtends||[]];if(o.allExtends=u,u.forEach(l=>{if(i.entities[l])i.entities[l].subTypes=[s,...i.entities[l].subTypes||[]];else if(i.relations[l])i.relations[l].subTypes=[s,...i.relations[l].subTypes||[]];else throw new Error(`[Schema] ${s} is extending a thing that does not exist in the schema: ${l}`)}),o.idFields=c.idFields?Array.from(new Set((o.idFields||[]).concat(c.idFields))):o.idFields,o.dataFields=c.dataFields?(o.dataFields||[]).concat(c.dataFields.map(l=>{let p=o.extends,f=e.entities[p]||e.relations[p];for(;!f.dataFields?.find($=>$.path===l.path);)p="extends"in f?f.extends:void 0,f=e.entities[p]||e.relations[p];return {...l,inherited:!0,dbPath:"dbPath"in l?l.dbPath:Sr(p,l.path,l.shared),[z]:{...l[z],inheritanceOrigin:l[z]?.inheritanceOrigin||o.extends}}})):o.dataFields,"roles"in c){let l=o,p=c;if(p.roles){let f=mapEntries(p.roles,($,E)=>[$,{...E,inherited:!0,[z]:{...E[z],inheritanceOrigin:E[z]?.inheritanceOrigin||o.extends}}]);l.roles={...l.roles||{},...f};}}if("refFields"in c){let l=o,p=c;if(p.refFields){let f=mapEntries(p.refFields,($,E)=>[$,{...E,inherited:!0,[z]:{...E[z],inheritanceOrigin:E[z]?.inheritanceOrigin||o.extends}}]);l.refFields={...l.refFields||{},...f};}}o.linkFields=c.linkFields?(o.linkFields||[]).concat(c.linkFields.map(l=>({...l,inherited:!0,[z]:{...l[z],inheritanceOrigin:l[z]?.inheritanceOrigin||o.extends}}))):o.linkFields,c?.hooks?.pre&&(o.hooks=o.hooks||{},o.hooks.pre=o.hooks.pre||[],o.hooks.pre=[...c?.hooks?.pre||[],...o?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:i,value:s,meta:o})=>{if(i==="linkFields"){let h=(()=>{if(!o.nodePath)throw new Error("No path");let[u,l]=o.nodePath.split(".");return {thing:l,thingType:u==="entities"?"entity":u==="relations"?"relation":""}})(),c=Array.isArray(s)?s.map(u=>({...u,...h})):[{...s,...h}];r.push(...c);}}),produce(n,i=>traverse(i,({value:s,key:o,meta:d})=>{if(d.depth===2&&s.idFields&&!s.id){s.name=o;let h=()=>{if(d.nodePath?.split(".")[0]==="entities")return "entity";if(d.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};s.thingType=h();let c=Object.keys(t).find(u=>t[u]?.get(s.defaultDBConnector.id));if(s.db=c,s.dbContext=br[c],s.dbProviderConfig=c==="surrealDB"?t[c]?.get(s.defaultDBConnector.id)?.providerConfig:void 0,s.computedFields=[],s.virtualFields=[],s.requiredFields=[],s.enumFields=[],s.fnValidatedFields=[],"linkFields"in s&&s.linkFields){let u=s;u.linkFields?.forEach(l=>{if(u.dataFields?.find(f=>f.path===l.path)||Object.keys(u.roles||{}).includes(l.path))throw new Error(`[Schema] The path ${l.path} is already in use by a dataField or linkField in ${u.name}. Path:${d.nodePath}`);let p=n.relations[l.relation];if(!l.isVirtual){if(!p)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(p.roles?.[l.plays]===void 0)throw new Error(`The role ${l.plays} is not defined in the relation ${l.relation} (linkField: ${l.path})`)}if(l.target==="relation"){if(l.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${u.name}" LinkField: "${l.path}. Path:${d.nodePath}."`);l.$things=[l.relation,...p.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){if(l.oppositeLinkFieldsPlayedBy=r.filter(f=>f.relation===l.relation&&f.plays!==l.plays&&f.target==="role"),l.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${u.name}" LinkField: "${l.path}. Path:${d.nodePath}."`);l.pathToRelation=u.linkFields?.find(f=>f.target==="relation"&&f.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(f=>[f.thing,...Y(n,f.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${u.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(f=>f.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(s.db==="surrealDB"){let f=p?.roles?.[l.plays][z]?.inheritanceOrigin??l.relation,$=wr({linkField:l,originalRelation:f,withExtensionsSchema:n,linkMode:s.dbProviderConfig.linkMode});l[De]={queryPath:$};}});}if("refFields"in s&&s.refFields&&(s.refFields=mapEntries(s.refFields,(u,l)=>{let p={...l,dbPath:l.dbPath||u};return [u,p]})),"roles"in s){let u=s;Object.entries(u.roles).forEach(([l,p])=>{if(u.dataFields?.find(m=>m.path===l)||u.linkFields?.find(m=>m.path===l))throw new Error(`[Schema] The path ${l} is already in use by a dataField or linkField in ${u.name}. Path:${d.nodePath}`);let f=r.filter(m=>m.relation===o&&m.plays===l)||[];p.playedBy=f.map(m=>({...m,pathToRelation:m.target==="relation"?m.path:u.linkFields?.find(S=>S.target==="relation"&&S.relation===o&&S.plays===l)?.path??m.relation.toLocaleLowerCase()}));let $=r.filter(m=>m.target==="relation"&&m.plays===l&&u.allExtends?.includes(m.relation));p.impactedLinkFields=$,p.path=l;let E=[...new Set(f.flatMap(m=>[...Y(n,m.thing).subTypes||[],m.thing]).flat().filter(Boolean))];p.$things=E;let g=p[z]?.inheritanceOrigin||s.name,y=E.flatMap(m=>{let M=Y(e,m)?.subTypes||[];return [m,...M]}),F=()=>{if(s.dbProviderConfig.linkMode==="edges")return `->\`${g}_${l}\`->(\`${y.join("`,`")}\`)`;if(s.dbProviderConfig.linkMode==="refs"){if(p.cardinality==="MANY")return `$parent.[\`${l}\`]`;if(p.cardinality==="ONE")return `$parent.\`${l}\``}throw new Error("Unsupported linkMode")};if(s.db==="surrealDB"){let m=F();p[De]={queryPath:m};}});}}if(s&&typeof s=="object"&&"playedBy"in s){let h=[...new Set(s.playedBy.map(c=>c.thing))];if(h.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${o}, path:${d.nodePath}, played by: ${h.join(", ")}`),s.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${o}, path:${d.nodePath}`)}if(d.depth===4){let[h,c]=d.nodePath?.split(".")||[],u=i[h][c];!isArray(s)&&typeof s=="object"&&(s.validations&&(s.validations.required&&u.requiredFields.push(s.path),s.validations.enum&&u.enumFields.push(s.path),s.validations.fn&&u.fnValidatedFields.push(s.path)),s.default?s.isVirtual?u.virtualFields.push(s.path):u.computedFields.push(s.path):s.isVirtual&&u.virtualFields.push(s.path));}}))},Y=(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`)},j=(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)}`)},at=(e,t)=>{let r=e.dataFields?.find(i=>i.path===t);if(e.idFields?.includes(t)){if(!r)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",r]}if(r)return ["dataField",r];let n=e.linkFields?.find(i=>i.path===t);if(n)return ["linkField",n];let a="roles"in e?e.roles[t]:void 0;if(a)return ["roleField",a];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},lt=(e,t)=>{let r=j(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[n]=r.idFields;return n},Dr=(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")},Qt=(e,t,r)=>{let n=j(e,t),a=n.linkFields?.find(d=>d.path===r);if(a)return a;let i=n.dataFields?.find(d=>d.path===r);if(i)return i;let s="roles"in n?n.roles?.[r]:void 0;if(s)return s;let o="refFields"in n?n.refFields?.[r]:void 0;if(o)return o;throw new Error(`Field ${r} not found in schema`)},Rt=(e,t,r)=>Qt(e,t,r)?.cardinality,de=(e,t)=>{let r=e.dataFields?.map($=>$.path)||[],n=e.linkFields?.map($=>$.path)||[],a="refFields"in e?listify(e.refFields,$=>$):[],i="roles"in e?listify(e.roles,$=>$):[],s=[...r||[],...n||[],...i||[],...a||[]],d=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...s];if(!t)return {fields:s,dataFields:r,roleFields:i,linkFields:n};let h=t.$fields?t.$fields.map($=>{if(typeof $=="string"){if($.startsWith("$")||$.startsWith("%"))return;if(!s.includes($))throw new Error(`Field ${$} not found in the schema`);return $}if("$path"in $&&typeof $.$path=="string")return $.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,$=>{if(!($.startsWith("$")||$.startsWith("%"))){if(!s.includes($))throw new Error(`[Schema] Field ${$} not found in the schema`);return $}}).filter($=>$!==void 0),c=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&r?.includes($)):[],u=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&[...i||[],...n||[]].includes($)):[],l=[...h,...c].filter($=>!$?.startsWith("%")).filter($=>!d.includes($)).filter($=>$),p=t.$filter?ce(t.$filter,($,E)=>c.includes($)):{},f=t.$filter?ce(t.$filter,($,E)=>u.includes($)):{};return {fields:s,dataFields:r,roleFields:i,linkFields:n,refFields:a,usedFields:h,usedLinkFields:n.filter($=>h.includes($)),usedRoleFields:i.filter($=>h.includes($)),usedDataFields:r.filter($=>h.includes($)),usedRefFields:a.filter($=>h.includes($)),unidentifiedFields:l,...c.length?{localFilters:p}:{},...u.length?{nestedFilters:f}:{}}};var Ir=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Cr=(e,t,r)=>{let a=(r.nodePath||"").split("."),i=isArray(t)?a.slice(0,-2).join("."):a.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},Ie=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var ct=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Se=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(([n,a])=>{r[n]=isDraft(a)?current(a):a;}),r}else return e},$e=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},Q=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},be=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var Ue=(e,t)=>{if(t[z].fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t[z].fieldType==="roleField"){let r=t;if([...new Set(r.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Ar=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(!n.every(a=>typeof a=="object"))if(n.every(a=>typeof a=="string")){let a=Ue(t,r),[i]=a,s=e.$op==="create"?"link":"replace",o=i.thing,d=i.thingType,h={$op:s,$thing:o,$thingType:d},c=n.filter(l=>l.startsWith("_:")),u=n.filter(l=>!l.startsWith("_:"));c.length&&!u.length?e[t]=c.map(l=>({...h,$tempId:l,$bzId:l})):c.length&&u.length?e[t]=[...c.map(l=>({...h,$tempId:l,$bzId:l})),{...h,$id:u,$bzId:`S_${be()}`}]:e[t]={...h,$id:e[t],$bzId:`S_${be()}`};}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(n)} Parent: ${JSON.stringify(e,null,2)})`)},kr=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(r.contentType==="REF"){if(n.some(a=>!isObject(a)))throw new Error("[Wrong format] Field of contentType REF can't use strings as references");return}if(r.contentType!=="FLEX")throw new Error(`[Internal] Field ${t} is not a refField`)};var Ce=(e,t,r)=>{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`);let n=j(r,t),{usedDataFields:a}=de(n,t);if(t.$op==="delete"&&a.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&a.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}},qr=(e,t,r)=>{(isArray(t)?t:[t]).forEach(a=>{Ce(e,a,r);});};var Pr=e=>{let t=Object.keys(e).filter(r=>!(r.startsWith("$")||r.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},Nr=(e,t,r)=>{let n=j(r,t),{usedFields:a}=de(n,t);return t.$op?(Ce(e,t,r),t.$op):t.$id||t.$filter?a.length>0?(Ce(e,{...t,$op:"update"},r),"update"):(Ce(e,{...t,$op:"link"},r),"link"):t.$tempId?a.length>0?(Ce(e,{...t,$op:"create"},r),"create"):(Ce(e,{...t,$op:"create"},r),"link"):(Ce(e,{...t,$op:"create"},r),"create")};var jr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(a=>{let i=Nr(a,a,t);return {...{...a.$thing?{}:{$thing:a.$entity||a.$relation},...a.$thingType?{}:{$thingType:Dr(a,t)},...a.$op?{}:{$op:i},...a.$bzId?{}:{$bzId:`R_${be()}`}},...a}});e.$root=isArray(e.$root)?n:n[0];};var dt=(e,t)=>{let r=t[ot];return isSet(r)?r.has("clean")?(Reflect.set(t,ot,r.add("clean")),!0):!1:(Reflect.set(t,ot,new Set(["clean"])),!0)};var _r=(e,t,r)=>{if(dt("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(a=>{if(isObject(a)&&"$id"in a&&isArray(a.$id)){let i=a;if(j(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((s,o)=>({...Se(i),$id:s,$bzId:`${i.$bzId}_${o}`,...Ie(i)}))}return a});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var It=(e,t)=>e.$bzId?e.$bzId:e.$tempId?e.$tempId:e.$id&&!isArray(e.$id)?t?`SN_ONE_${t}_${e.$id}`:`SN_ONE_${e.$id}`:e.$id&&isArray(e.$id)?t?`SN_MANY_${t}_${be()}`:`SN_MANY_${be()}`:`SM_${be()}`;var Vr=(e,t,r,n)=>{let a=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);let s=Pr(i),o=It(i);if(r[z].fieldType==="refField"){let c=r;if(!isObject(i)){if(c.contentType==="FLEX")return i;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!i.$thing)throw new Error("[Wrong format] The field $thing is required in refFields");return {...i,$op:s,$bzId:o}}let d=r;if(d.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let h=r;if(h.$things.length===1){let c=Ue(t,d),[u]=c;if(i.$thing&&i.$thing!==u.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${u.thing}.`);return {...i,[Me]:h,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:s,$bzId:o}}if(h.$things.length>1){if(i.$thing)return [{...i,[Me]:h,$thing:i.$thing,$thingType:i.$thing in n.entities?"entity":"relation",$op:s,$bzId:o}];if(!i.$thing){if(i.$tempId)throw new Error("[Unsupported] Objects with $tempId and multiple potential players require to explicitly indicate the $thing type.");if(s==="create")throw new Error(`[Wrong format] The field ${t} can be played by multiple things, please specify one on creation.`);return h.$things.map(c=>({...i,[Me]:h,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:s,$bzId:It(i,c)}))}}});isArray(e[t])||a.length>1?e[t]=a:e[t]=a[0],e[t]=isArray(e[t])?a:a[0];};var Wi=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,zi=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Wr=e=>{let r=e.toString().replace(Wi,"").trim().split("=>")[0].split("{")[0].replace(zi,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(o=>o.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var Ve=({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:n}=t.default,i=Wr(n).filter(s=>!(s in e));if(i.length)throw new Error(`Virtual field: Missing arguments ${i.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var zr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(a=>{if(a.$op!=="create")return;let i=j(r,a),{unidentifiedFields:s}=de(i,a),{computedFields:o,virtualFields:d}=i,h=listify(a,(l,p)=>p!==void 0?l:void 0),c=h.filter(l=>d?.includes(l));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(o.filter(l=>!h.includes(l)).forEach(l=>{let p=i.dataFields?.find(y=>y.path===l),$=i.linkFields?.find(y=>y.path===l)?.oppositeLinkFieldsPlayedBy[0],E="roles"in i?Qr(i.roles,(y,F)=>y===l):void 0,g=p||$||E;if(!g)throw new Error(`no field Def for ${l}`);if(!a[l]){let y=Ve({currentThing:a,fieldSchema:g,mandatoryDependencies:!0});a[l]=y;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(a)}`)}),e};var ut=(e,t)=>{let r=j(t,e).hooks;if(r?.pre){let n=`on${Ir(e.$op)}`;return r.pre.filter(s=>!s.triggers||s.triggers[n]?.()).flatMap(s=>s.actions)}return []};var vr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){if(i.$fields)return i;let{requiredFields:s,enumFields:o,fnValidatedFields:d,dataFields:h}=j(r,i);if("$op"in i&&i.$op==="create"&&s.forEach(c=>{if(!(c in i))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&o.forEach(c=>{if(c in i){let u=h?.find(l=>l.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(i[c]))i[c].some(l=>{if(!u.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${c}".`)});else if(u&&!u.includes(i[c]))throw new Error(`[Validations] Option "${i[c]}" is not a valid option for field "${c}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&d.forEach(c=>{if(c in i)try{let u=h?.find(l=>l.path===c)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(i[c]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${c}] ${u.message}`)}}),isObject(i)&&"$thing"in i){let c=i.$thing,u=i,l=clone(Se(e)),p=clone(Se(u)),f=n.mutation?.context||{},$=clone(Se(i[_e]||{}));ut(u,r).forEach(g=>{if(g.type==="validate"){if(g.severity!=="error")return;try{let y=g.fn(p,l,f,$);if(y===!1)throw new Error(`${g.message}.`);if(y!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(y){throw new Error(`[Validations:thing:${c}] ${y.message}`)}}});}}});};var Kr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if(!ct(i)||i.$fields||i[Mt])return;let s=ut(i,r).filter(u=>u.type==="transform"),o=clone(Se(e)),d=clone(Se(i)),h=n.mutation?.context||{},c=clone(Se(i[_e]||i.$dbNode));s.forEach(u=>{let l=u.fn(d,o,h,c||{});Object.keys(l).length!==0&&(d={...d,...l,...Ie(i),[Mt]:!0},Object.assign(i,d));});});};var Jr=(e,t,r)=>{let n=Ue(t,r),[a]=n;e[t]={$thing:a.thing,$thingType:a.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Me]:r};};var We=e=>{if(Array.isArray(e)){for(let t of e)if(We(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"&&We(e[t]))return !0}return !1};var Xr=(e,t)=>{for(let a of e)if(!("$entity"in a)&&!("$relation"in a)&&(!("$thing"in a)||!("$thingType"in a)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,a=>traverse(a,i=>{let{value:s,meta:o}=i,d=s;if(isObject(d)){if(o.nodePath?.includes(".$filter")||o.nodePath?.includes(".$playedBy"))return;if(d[ee]=o.nodePath,d.$id){let h=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing},c=j(t,h);if(!c?.name)throw new Error(`Schema not found for ${d.$thing}`);if(d.$path=c.name,Array.isArray(d.$id)||(d.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in d||"$relation"in d||"$thing"in d){let h=j(t,d);if(!h?.name)throw new Error(`Schema not found for ${d.$thing}`);d.$path=h.name;}if(d.$entity?(d.$thing=d.$entity,d.$thingType="entity",delete d.$entity):d.$relation&&(d.$thing=d.$relation,d.$thingType="relation",delete d.$relation),isObject(d)&&"$thing"in d&&d.$thing){let h=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing},c=j(t,h);if(d.$filter&&(Object.keys(d.$filter).length===0?d.$filter=void 0:(d.$filter=Oe(d.$filter,d.$thing,t),d.$filterByUnique=qt(d.$filter,c))),d.$fields){d.$fields.some(p=>c?.idFields?.includes(p?.$path||p))||(d.$fields=[...d.$fields,...Array.isArray(c.idFields)?c.idFields:[]],d.$idNotIncluded=!0);let l=d.$fields?.flatMap(p=>{let f=Yr(p,c,t);return Array.isArray(f)?f:[f]}).filter(Boolean);d.$fields=l;}else {let l=kt(c)?.flatMap(p=>{let f=Yr(p,c,t);return Array.isArray(f)?f:[f]}).filter(Boolean);d.$fields=l;}d.$excludedFields&&(d.$fields=d.$fields.filter(u=>ht(c,u)?!0:!d.$excludedFields.includes(u.$path)));}}}))},kt=e=>{let t=e.dataFields?.map(s=>s.path)||[],r=e.linkFields?.map(s=>s.path)||[],n=Object.keys(e.roles||{})||[],a=Object.keys(e.refFields||{})||[];return [...t,...r,...n,...a]},qt=(e,t)=>Object.keys(e||{}).some(n=>{let a=e[n];if(a!==null&&typeof a<"u"){let i=t.idFields?.includes(n),s=t.dataFields?.some(h=>(h.dbPath===n||h.path===n)&&h?.validations?.unique),o=n==="$id"&&!Array.isArray(a);if(i||s||o){if(typeof a!="object"||a===null||Array.isArray(a))return !Array.isArray(a);{let h=Object.keys(a);if(h.length===1&&h[0]==="$eq"){let c=a.$eq;if(typeof c!="object"||c===null||!Array.isArray(c))return !0}return !1}}}return !1}),ht=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Zi=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:a,isVirtual:i,fieldSchema:s}=e;return {$path:r,$dbPath:a,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[ie]:s}},eo=e=>{let{field:t,fieldStr:r,linkField:n,$justId:a,dbPath:i,schema:s,fieldSchema:o}=e,{target:d,oppositeLinkFieldsPlayedBy:h}=n;return h.map(c=>{let u=d==="role"?c.thingType:"relation",l=d==="role"?c.thing:n.relation,p={[`$${u}`]:l},f=j(s,p),$=t?.$fields?.filter(y=>ht(f,y)).length===0,E=[];if(typeof t!="string")if(t.$fields)if($){let y=f.idFields||[];E=[...t.$fields,...y];}else E=t.$fields;else E=kt(f);else E=["id"];t.$excludedFields&&(E=E.filter(y=>ht(f,y)?!0:!t.$excludedFields.includes(y.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$plays:n.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:l,$fields:E,$excludedFields:t.$excludedFields,$fieldType:"link",$target:d,$intermediary:c.relation,$justId:a,$id:t.$id,$filter:g,$idNotIncluded:$,$filterByUnique:qt(t.$filter,f),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:o}})},to=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:a,fieldSchema:i}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:r,$dbPath:a,$contentType:i.contentType,$as:t.$as||r,$var:r,$fieldType:"ref",$justId:n,$fields:t.$fields,$id:t.$id,[ie]:i}},ro=e=>{let{field:t,fieldStr:r,roleField:n,$justId:a,dbPath:i,schema:s,fieldSchema:o}=e;return n.playedBy.map(d=>{let{thing:h,thingType:c,relation:u}=d,l={[`$${c}`]:h},p=j(s,l),f=t?.$fields?.filter(g=>p?.idFields?.includes(g)||p?.idFields?.includes(g.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(f){let g=p.idFields||[];$=[...t.$fields,...g];}else $=t.$fields;else $=kt(p);else $=["id"];t.$excludedFields&&($=$.filter(g=>ht(p,g)?!0:!t.$excludedFields.includes(g.$path)));let E=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:h,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:a,$id:t.$id,$filter:E,$idNotIncluded:f,$filterByUnique:qt(t.$filter,p),$playedBy:{...d,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:o}})},Yr=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,a=typeof e=="string",i=t.dataFields?.find(h=>h.path===n),s=t.linkFields?.find(h=>h.path===n),o=t.roles?.[n],d=t.refFields?.[n];if(i){let h=!!i.isVirtual&&!!i.default;return Zi({field:e,fieldStr:n,$justId:a,dbPath:i.dbPath,isVirtual:h,fieldSchema:i})}else {if(s)return eo({field:e,fieldStr:n,linkField:s,$justId:a,dbPath:s.path,schema:r,fieldSchema:s});if(o)return ro({field:e,fieldStr:n,roleField:o,$justId:a,dbPath:n,schema:r,fieldSchema:o});if(d)return to({field:e,fieldStr:n,$justId:a,dbPath:n,isVirtual:!1,fieldSchema:d})}return null},Oe=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(s=>Object.keys(s).reduce((h,c)=>{let u=s[c],l=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))h[c]=u;else if(["$not","$or","$and"].includes(c))h[c]=Oe(u,t,r);else if(["$eq","$in","$exists"].includes(c))h[c]=u;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let p=t in r.entities?r.entities[t]:r.relations[t],[f,$]=at(p,c);if(f==="idField")h[c]=u;else if(f==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?h[c]=isArray(u)?{$or:Oe(u,t,r)}:Oe(u,t,r):isArray(u)?h[c]={$in:u}:h[c]={$eq:u};else if(f==="linkField"||f==="roleField"){let E=$,[g]=E.$things;l.every(y=>typeof y=="string")?h[c]={$id:l,$thing:g}:l.every(y=>isObject(y))&&(h[c]=isArray(u)?{$or:Oe(u,g,r)}:Oe(u,g,r));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return h},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var Gr=(e,t,r,n)=>{let a=isArray(e[t])?e[t]:[e[t]],i=n.slice(1).join(".");a.forEach(s=>{if(s){if(r?.cardinality==="ONE"&&!s.$op&&!s.$id&&!s.$filter&&!s.$tempId&&e.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${i}.${t}`);if(s.$tempId&&!(s.$op===void 0||s.$op==="link"||s.$op==="create"||s.$op==="update"||s.$op==="replace"))throw new Error(`Invalid op ${s.$op} for tempId. TempIds can be created, or linked when created in another part of the same mutation.`)}});};var co=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(dt("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");t==="$filter"&&e.$filter&&Object.keys(e.$filter).length===0&&(e.$filter=void 0);},uo=(e,t)=>{},Pt=(e,t,r)=>{let n={$rootWrap:{$root:e}},a=We(Array.isArray(e)?e:[e]),i=produce(n,s=>traverse(s,({value:o,parent:d,key:h,meta:c})=>{if(!(!d||!h)&&isObject(o)){let u=c.nodePath?.split(".")||[];if(u.some(f=>f.startsWith("%")))return;if(!("$root"in o)){if(!("$thing"in o||"$entity"in o||"$relation"in o)){let f=["$fields","$dbNode","$filter"],$=u[u.length-1],E=u[u.length-2];if(h==="$root")throw new Error("Root things must specify $entity or $relation");if(!f.includes($)&&!f.includes(E)&&!$.startsWith("%")&&!E.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(o)?current(o):o)}`)}}let l=o,p=u.includes("$filter");"$filter"in l&&l.$filter&&(l.$filter=Oe(l.$filter,l.$thing,t)),Object.keys(l).forEach(f=>{if(co(l,f),f!=="$root"&&p||f!=="$root"&&(f.startsWith("$")||f.startsWith("%")))return;let $=f!=="$root"?Qt(t,l,f):{[z]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${f} not found in schema`);let{fieldType:E}=$[z],g=["linkField","roleField"].includes(E),y=E==="refField",F=E==="rootField";if(E==="dataField")return uo();if((g||y)&&(l[f]===null?g&&Jr(l,f,$):g?Ar(l,f,$):kr(l,f,$)),F){if(!("$root"in l))throw new Error(`[Internal] Field ${f} is a rootField but the object is not a root`);jr(l,t);}(g||y)&&Gr(l,f,$,u),(g||y)&&(Vr(l,f,$,t),qr(l,l[f],t)),(g||F)&&(_r(l,f,t),zr(l,f,t),(isArray(l[f])?l[f]:[l[f]]).forEach(S=>{let M=j(t,S),{unidentifiedFields:R,usedLinkFields:I,usedFields:x,fields:J}=de(M,S);if(x.forEach(re=>{if(!J.includes(re))throw new Error(`[Schema] Field ${re} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(o)}`);if(I.length>1){let re=M.linkFields?.filter(fe=>I.includes(fe.path));re?.some((fe,A)=>re.some((D,L)=>{if(A!==L&&fe.target!==D.target&&fe.relation===D.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),a||(Kr(l,f,t,r),vr(l,f,t,r)));});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var en=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(e,r=>traverse(r,t))};var on=async(e,t)=>{let r=c=>{let u=[],l=[],p=g=>{if(g.$id)return g.$id;let y=j(t,g),{idFields:F}=y;if(!F)throw new Error(`no idFields: ${JSON.stringify(g)}`);let[m]=F;if(!m)throw new Error(`no idField: ${JSON.stringify(g)}`);let S=y.dataFields?.find(I=>I.path===m),M=Ve({currentThing:g,fieldSchema:S,mandatoryDependencies:!0}),R=g[m]||g.$id||M;if(!R)throw new Error(`no idValue: ${JSON.stringify(g)}`);return R},f=g=>{if(g.$op==="create"){let y=p(g);if(u.find(F=>F.$id===y&&F.$op==="create"))throw new Error(`Duplicate id ${y} for node ${JSON.stringify(g)}`);u.push({...g,$id:y});return}g.$tempId&&g.$op==="match"||u.push(g);},$=g=>{if(g.$op==="create"){let y=p(g);if(u.find(F=>F.$id===y&&F.$op==="create"))throw new Error(`Duplicate id ${y} for edge ${JSON.stringify(g)}`);l.push({...g,$id:y});return}l.push(g);};return traverse(c,({value:g,parent:y,meta:F})=>{if(!isObject(g))return;let m=g;if(!F.nodePath?.includes(".$filter")&&m.$thing){if(!m.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(m)}`);if(!m.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(m)}`);let S=j(t,m),{dataFields:M,roleFields:R,linkFields:I,refFields:x,usedFields:J}=de(S,m),re=()=>{if(m.$op==="create"||m.$op==="delete")return m.$op;if(m.$op==="update"){let D=J.filter(T=>M?.includes(T)),L=J.filter(T=>R?.includes(T)),b=J.filter(T=>I?.includes(T)),B=J.filter(T=>x?.includes(T));if(D.length>0)return "update";if(L.length>0||b.length>0||B.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(m)}`)}return "match"},fe={...m.$id&&{$id:m.$id},...m.$tempId&&{$tempId:m.$tempId},...m.$filter&&{$filter:m.$filter},$thing:m.$thing,...m.$thingType&&{$thingType:m.$thingType},...shake(pick(m,M||[""])),$op:re(),$bzId:m.$bzId};f(fe);let A=m[Me];if(A?.[z].fieldType==="linkField"){if((m.$op==="link"||m.$op==="unlink")&&(m.$id||m.$filter)){if(m.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...m,$op:"match"});}let D=A.$things.includes(m.$thing),L=D?m.$bzId:`LT_${v4()}`,B=Cr(c,y,F).$bzId;if(!B)throw new Error("No parent id found");let T=()=>m.$op==="delete"?D?"match":"delete":m.$op==="unlink"?D?"unlink":"delete":m.$op==="link"||m.$op==="create"?D?"link":"create":m.$op==="replace"?"replace":"match",w=j(t,{$thing:A.relation,$thingType:"relation"});if(!Object.keys(w.roles).includes(A.plays))throw new Error(`[Wrong format] Field ${A.plays} is not a role of relation ${A.relation}`);let P={$bzId:L,$thing:D?m.$thing:A.relation,$thingType:"relation",...m.$tempId?{$tempId:m.$tempId}:{},$op:T(),...D?{}:{[A.path]:m.$bzId},[A.plays]:B,[Me]:A,[qe]:"linkField"};$(P),(m.$op==="unlink"||T()==="unlink")&&D&&$({$thing:A.relation,$thingType:"relation",$bzId:L,$op:"match",[A.plays]:B,[Me]:A,[qe]:"linkField"});}if(m.$thingType==="relation"){let D=ce(m,(B,T)=>R.includes(B)),L=mapEntries(D,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),b=ce(g,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(D).filter(B=>!B.startsWith("$")).length>0){if(m.$op==="create"||m.$op==="delete"){let B=()=>{if(m.$op==="create")return "link";if(m.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=j(t,m).roles,w=mapEntries(L,(P,q)=>{let O=T[P]?.cardinality;if(!O)throw new Error(`Role ${P} not found in schema`);return Array.isArray(q)?O==="ONE"?q.length>1?[P,q.map(v=>v.$bzId||v)]:[P,q[0].$bzId||q[0]]:[P,q.map(v=>v.$bzId||v)]:[P,q.$bzId||q]}),C={...b,$thing:m.$thing,$thingType:"relation",$op:B(),...w,$bzId:m.$bzId,[qe]:"roleField"};$(C);return}if(m.$op==="match"||m.$op==="update"&&Object.keys(D).length>0){let B=0;Object.entries(D).forEach(([T,w])=>{let C=isArray(w)?w:[w],P=q=>q==="create"||q==="replace"?"link":q;C.forEach(q=>{if(!q)return;let O=P(q.$op);if(O==="replace")throw new Error("Not supported yet: replace on roleFields");if(O==="unlink"&&B>0)throw B+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let v={...b,$thing:m.$thing,$thingType:"relation",$op:O==="delete"?"unlink":O,[T]:q.$bzId,$bzId:m.$bzId,[qe]:"roleField"};$(v);});});}}}}}),[u,l]},[n,a]=r(e),i=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let l=c.findIndex(p=>p.$bzId===u.$bzId);if(l===-1)return [...c,u];if(c[l].$op==="create"&&u.$op==="match")return c;if(c[l].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,l),u,...c.slice(l+1)];if(c[l].$op==="update"&&u.$op==="update")return [...c.slice(0,l),{...c[l],...u},...c.slice(l+1)];if(c[l].$op==="update"&&u.$op==="match"||c[l].$op==="match"&&u.$op==="update")return [...c.slice(0,l),{...c[l],...u,$op:"update"},...c.slice(l+1)];if(c[l].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[l].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[l].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[l].$op}. Current: ${u.$op}`)},[]),s=a.reduce((c,u)=>{let l=c.find(p=>(p.$id&&p.$id===u.$id||p.$bzId&&p.$bzId===u.$bzId)&&p.$thing===u.$thing&&p.$op===u.$op);if(l){let p={...l};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let E=l[$],g=u[$];Array.isArray(E)&&Array.isArray(g)?p[$]=Array.from(new Set([...E,...g])):!Array.isArray(E)&&Array.isArray(g)?E!==void 0?p[$]=Array.from(new Set([E,...g])):p[$]=g:Array.isArray(E)&&!Array.isArray(g)?g!==void 0&&(p[$]=Array.from(new Set([...E,g]))):E!==null&&g!==null&&E!==void 0&&g!==void 0?p[$]=Array.from(new Set([E,g])):E==null&&(p[$]=g);}),[...c.filter($=>!(($.$id&&$.$id===u.$id||$.$bzId&&$.$bzId===u.$bzId)&&$.$thing===u.$thing&&$.$op===u.$op)),p]}return [...c,u]},[]);i.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&s.filter(u=>u.$bzId===c.$bzId||u.$tempId&&u.$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(en(c))}`)}});let o=[...i,...s],d=new Set(o.filter(c=>c.$tempId).map(c=>c.$tempId)),h=Array.from(d).filter(c=>!o.some(u=>u.$tempId===c&&u.$op==="create"));if(h.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${h.join(", ")}`);return {mergedThings:i,mergedEdges:s}};var He={};function oe(e){return {enumerable:!0,value:e}}function sn(e){return {enumerable:!0,writable:!0,value:e}}var go=()=>!0,an=()=>({}),cn=e=>e,Eo=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),Bo=(e,t,r,[n,a])=>t.call(r,e.call(r,n,a),a),Ae=(e,t)=>Object.freeze(Object.create(e,t));function ln(e,t,r){return e.reduce((n,a)=>function(...i){return r(n,a,this,i)},t)}function dn(e){return Ae(this,{fn:oe(e)})}var un={},_=dn.bind(un);var hn={},Nt=dn.bind(hn);function pt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function pn(e,t,...r){let n=ln(pt(hn,r).map(i=>i.fn),go,Eo),a=ln(pt(un,r).map(i=>i.fn),cn,Bo);return Ae(this,{from:oe(e),to:oe(t),guards:oe(n),reducers:oe(a)})}var fn={},$n={},U=pn.bind(fn);pn.bind($n,null);function Fo(e,t,r){return jt(t,e,r,this.immediates)||e}function mn(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 bo={enter:cn};function ue(...e){let t=pt(fn,e),r=pt($n,e),n={final:oe(e.length===0),transitions:oe(mn(t))};return r.length&&(n.immediates=oe(r),n.enter=oe(Fo)),Ae(bo,n)}var wo={enter(e,t,r){let n=this.fn.call(t,t.context,r);return xt.isPrototypeOf(n)?Ae(yn,{machine:oe(n),transitions:oe(this.transitions)}).enter(e,t,r):(n.then(a=>t.send({type:"done",data:a})).catch(a=>t.send({type:"error",error:a})),e)}},yn={enter(e,t,r){if(t.child=ye(this.machine,n=>{t.onChange(n),t.child==n&&n.machine.state.value.final&&(delete t.child,t.send({type:"done",data:n.context}));},t.context,r),t.child.machine.state.value.final){let n=t.child.context;return delete t.child,jt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function H(e,...t){let r=oe(mn(t));return xt.isPrototypeOf(e)?Ae(yn,{machine:oe(e),transitions:r}):Ae(wo,{fn:oe(e),transitions:r})}var xt={get state(){return {name:this.current,value:this.states[this.current]}}};function Ee(e,t,r=an){return typeof e!="string"&&(r=t||an,t=e,e=Object.keys(t)[0]),He._create&&He._create(e,t),Ae(xt,{context:oe(r),current:oe(e),states:oe(t)})}function jt(e,t,r,n){let{context:a}=e;for(let{to:i,guards:s,reducers:o}of n)if(s(a,r)){e.context=o.call(e,a,r);let d=t.original||t,h=Ae(d,{current:oe(i),original:{value:d}});He._onEnter&&He._onEnter(t,i,e.context,a,r);let c=h.state.value;return e.machine=h,e.onChange(e),c.enter(h,e,r)}}function To(e,t){let r=t.type||t,{machine:n}=e,{value:a,name:i}=n.state;return a.transitions.has(r)?jt(e,n,t,a.transitions.get(r))||n:(He._send&&He._send(r,i),n)}var Mo={send(e){To(this,e);}};function ye(e,t,r,n){let a=Object.create(Mo,{machine:sn(e),context:sn(e.context(r,n)),onChange:oe(t)});return a.send=a.send.bind(a),a.machine=a.machine.state.value.enter(a.machine,a,n),a}var Fn=(e,t)=>{if(!t)return;let r=Lo(t);return Qo(r,e.query)},Lo=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Qo=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let a=n;Object.keys(a).forEach(i=>{(a[i]===void 0||a[i]===null||isArray(a[i])&&a[i].length===0)&&(t?.returnNulls?a[i]=null:delete a[i]),a[i]===void 0&&delete a[i];}),Object.getOwnPropertySymbols(a).forEach(i=>{delete a[i];}),t?.noMetadata===!0&&Object.keys(a).forEach(i=>{i.startsWith("$")&&delete a[i];});}}));var bn=async(e,t,r)=>r?(i=>produce(i,s=>traverse(s,({value:o})=>{if(isObject(o)){let d=o;if(!d.$thing)return;if(d.$thing){let h=j(e,d),{virtualFields:c}=h,u=d[ee];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(d)}`);let l=getNodeByPath(t,u);if(l.$fieldType==="ref")return;let p=l.$fields.map($=>$.$path),f=l.$excludedFields;c.forEach($=>{if(f?.includes($)||p.length>0&&!p.includes($))return;let E=h.dataFields?.find(g=>g.path===$);if(E?.default){let g=Ve({currentThing:d,fieldSchema:E,mandatoryDependencies:!0});d[$]=g;}else if(d[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),f&&f.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete d[$];});}}})))(r):void 0;var et={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Be=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(s=>{let d=Object.keys(s).reduce((h,c)=>{let u=s[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...h,[c]:void 0,[et[c]]:Be(u,t,r)};if(c==="$id")return {...h,$id:void 0,[et[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return h;if(c==="$exists")return {...h,$exists:void 0,[et[c]]:u};if(c==="$eq")return {...h,$eq:void 0,[et[c]]:u};if(c==="$in")return {...h,$in:void 0,[et[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let l=t in r.entities?r.entities[t]:r.relations[t],[p,f]=at(l,c);if(p==="idField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return {...h,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(p==="dataField")return {...h,[c]:Be(u,t,r)};if(p==="linkField"||p==="roleField"){let E=f[De].queryPath;return {...h,[E]:Be(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(d)});return n?i:i[0]},me=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,a])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),s=Array.isArray(a)?a.map(o=>me(o)):[me(a)];i==="!"?r.push(`!(${s.join(" AND ")})`):r.push(`(${s.join(` ${i} `)})`);return}if(isObject(a))if(n.includes("<-")||n.includes("->")){let i=me(a);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=me(a),s=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${s})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=me(a),s=n.replace("$parent.","");r.push(`fn::as_array(${s})[WHERE id && ${i}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let i=Object.keys(a);if(i.length===1&&i[0].startsWith("$")){let[s]=i,o=a[s];if(s==="$exists")if(o===!0)r.push(`${n} IS NOT NONE`);else if(o===!1)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${o}`);else {let d=s.replace("$","");if(Array.isArray(o))r.push(`${n} ${d} [${o.map(h=>h===null?"NONE":`'${h}'`).join(", ")}]`);else if(isObject(o)){let h=me(o);r.push(`${n} ${d} ${h}`);}else r.push(`${n} ${d} ${o===null?"NONE":`'${o}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(a)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${a.map(s=>s===null?"NONE":`'${s}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${a===null?"NONE":`'${a}'`}`);}}),r.join(" AND ")},ve=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:a}=r;return `${n}${a?" DESC":" ASC"}`}).join(", ")}`;var Tn=e=>{let{queries:t,schema:r}=e;return t.map(n=>ko({query:n,schema:r}))},ko=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:a,$filter:i,$offset:s,$limit:o,$sort:d}=t;if(a.length===0)return null;let h=[];h.push("SELECT");let c=Ut({parentQuery:t,queries:a,level:1,schema:r});c&&h.push(c);let u=r.entities[n]||r.relations[n];if(!u)throw new Error(`Schema for ${n} not found`);let p=(u.subTypes?[n,...u.subTypes]:[n]).map(f=>te(f));if(t.$id)if(typeof t.$id=="string")h.push(`FROM ${p.map(f=>`${f}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let f=t.$id,$=p.flatMap(E=>f?.map(g=>`${E}:\u27E8${g}\u27E9`));h.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else h.push(`FROM ${p.join(",")}`);if(i){let f=Be(i,n,r),$=me(f);h.push(`WHERE ${$}`);}return d&&h.push(ve(d)),typeof o=="number"&&h.push(`LIMIT ${o}`),typeof s=="number"&&h.push(`START ${s}`),h.join(`
105
- `)},Ut=e=>{let{queries:t,schema:r,level:n,parentQuery:a}=e,i=[],s=a[ee];return i.push(Q(`"${s}" as \`$$queryPath\``,n)),i.push(Q("record::id(id) as `$id`",n)),i.push(Q("record::tb(id) as `$thing`",n)),t.forEach(o=>{let d=qo({query:o,level:n,schema:r});d&&i.push(d);}),i.length===0?null:i.join(`,
106
- `)},qo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fieldType==="data")return Po({query:t,level:n});if(t.$fieldType==="ref")throw new Error("Ref fields are not supported in this context");return t.$fieldType==="link"?No({query:t,level:n,schema:r}):t.$fieldType==="role"?xo({query:t,level:n,schema:r}):null},Po=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?Q(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?Q(`\`${t.$path}\``,r):Q(`\`${t.$path}\` AS \`${t.$as}\``,r)},No=e=>{let{query:t,schema:r,level:n}=e,{$fields:a,$filter:i,$offset:s,$limit:o,$sort:d}=t;if(a.length===0)return null;let h=[];h.push(Q("(",n));let c=n+1;h.push(Q("SELECT",c));let u=Ut({parentQuery:t,queries:a,level:c+1,schema:r});u&&h.push(u);let l=t[ie][De].queryPath;if(h.push(Q(`FROM ${l}`,c)),i){let p=Be(i,t.$thing,r),f=me(p);h.push(`WHERE ${f}`);}return d&&h.push(Q(ve(d),c)),typeof o=="number"&&h.push(Q(`LIMIT ${o}`,c)),typeof s=="number"&&h.push(Q(`START ${s}`,c)),h.push(Q(`) AS \`${t.$as}\``,n)),h.join(`
107
- `)},xo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let a=[];a.push(Q("(",n));let i=n+1;a.push(Q("SELECT",i));let s=i+1,o=Ut({parentQuery:t,queries:t.$fields,level:s,schema:r});o&&a.push(o);let d=t[ie][De].queryPath;if(a.push(Q(`FROM ${d}`,i)),t.$filter){let h=Be(t.$filter,t.$playedBy.thing,r),c=me(h);a.push(`WHERE ${c}`);}return a.push(Q(`) AS \`${t.$as}\``,n)),a.join(`
108
- `)};var se="0.12.3";var Mn=new Set((process.env.LOG_LEVEL||"").split(",").map(e=>e.trim()).filter(e=>!!e)),jo=(e,...t)=>{(Array.isArray(e)?e.some(n=>Mn.has(n)):Mn.has(e))&&console.log(...t);},ae=(...e)=>jo("debug",...e);var Sn=async e=>{let{client:t,queries:r,config:n}=e,a=`
104
+ `,Er=e=>Qi(e);var Br=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([d])=>[d,await fr(d,e,t,r)]))).map(d=>[d[0],d[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([d])=>[d,Er(t)]))).map(d=>[d[0],d[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(s)}})();var ee=Symbol.for("queryPath"),it=Symbol.for("stepPrint"),qe=Symbol.for("edgeType"),Te=Symbol.for("edgeSchema"),_e=Symbol.for("dbNode"),Mt=Symbol.for("isTransformed"),ot=Symbol.for("parent"),ie=Symbol.for("fieldSchema"),z=Symbol.for("sharedMetadata"),Re=Symbol.for("suqlMetadata");var Fr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var br=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],i=[e.relation,...o],a=`<-\u27E8${t}_${e.plays}\u27E9<-(\u27E8${i.join("\u27E9,\u27E8")}\u27E9)`;if(e.target==="relation"){if(n==="edges")return a;if(n==="refs")return e.cardinality==="MANY"?`$parent.[\`${e.path}\`]`:`$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[s]=e.oppositeLinkFieldsPlayedBy,d=r.entities[s.thing]?.subTypes||r.relations[s.thing]?.subTypes||[],h=[s.thing,...d],c=`->\u27E8${t}_${s.plays}\u27E9->(\u27E8${h.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${a}${c}`:n==="refs"?e.cardinality==="MANY"?`$parent.[\`${s.plays}\`]`:`$parent.\`${s.plays}\``:`${a}${c}`}else throw new Error("Unsupported linkField target")};var Mr=(e,t,r)=>r?t:`${e}\xB7${t}`;var Lr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ce=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,o])=>{let[i,a]=tryit(()=>t(n,o))();return i?!1:a}))},Qr=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:a,value:s,meta:d})=>{if(d.depth!==2)return;let h=s;if(a&&(h.dataFields=h.dataFields?.map(c=>({...c,...h.idFields?.includes(c.path)?{isIdField:!0}:{isIdField:!1},cardinality:c.cardinality||"ONE",dbPath:"dbPath"in c?c.dbPath:Mr(a,c.path,c.shared),[z]:{fieldType:"dataField"}})),h.refFields=mapEntries(h.refFields||{},(c,u)=>[c,{...u,cardinality:u.cardinality||"ONE",path:c,[z]:{fieldType:"refField"}}]),h.linkFields=h.linkFields?.map(c=>({...c,[z]:{fieldType:"linkField"}})),"roles"in h&&(h.roles=mapEntries(h.roles||{},(c,u)=>[c,{...u,cardinality:u.cardinality||"ONE",[z]:{fieldType:"roleField"}}]))),s.extends){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${d.nodePath}`);let c=i.entities[s.extends]||i.relations[s.extends],u=[s.extends,...c.allExtends||[]];if(s.allExtends=u,u.forEach(l=>{if(i.entities[l])i.entities[l].subTypes=[a,...i.entities[l].subTypes||[]];else if(i.relations[l])i.relations[l].subTypes=[a,...i.relations[l].subTypes||[]];else throw new Error(`[Schema] ${a} is extending a thing that does not exist in the schema: ${l}`)}),s.idFields=c.idFields?Array.from(new Set((s.idFields||[]).concat(c.idFields))):s.idFields,s.dataFields=c.dataFields?(s.dataFields||[]).concat(c.dataFields.map(l=>{let p=s.extends,f=e.entities[p]||e.relations[p];for(;!f.dataFields?.find($=>$.path===l.path);)p="extends"in f?f.extends:void 0,f=e.entities[p]||e.relations[p];return {...l,inherited:!0,dbPath:"dbPath"in l?l.dbPath:Mr(p,l.path,l.shared),[z]:{...l[z],inheritanceOrigin:l[z]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in c){let l=s,p=c;if(p.roles){let f=mapEntries(p.roles,($,E)=>[$,{...E,inherited:!0,[z]:{...E[z],inheritanceOrigin:E[z]?.inheritanceOrigin||s.extends}}]);l.roles={...l.roles||{},...f};}}if("refFields"in c){let l=s,p=c;if(p.refFields){let f=mapEntries(p.refFields,($,E)=>[$,{...E,inherited:!0,[z]:{...E[z],inheritanceOrigin:E[z]?.inheritanceOrigin||s.extends}}]);l.refFields={...l.refFields||{},...f};}}s.linkFields=c.linkFields?(s.linkFields||[]).concat(c.linkFields.map(l=>({...l,inherited:!0,[z]:{...l[z],inheritanceOrigin:l[z]?.inheritanceOrigin||s.extends}}))):s.linkFields,c?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...c?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:i,value:a,meta:s})=>{if(i==="linkFields"){let h=(()=>{if(!s.nodePath)throw new Error("No path");let[u,l]=s.nodePath.split(".");return {thing:l,thingType:u==="entities"?"entity":u==="relations"?"relation":""}})(),c=Array.isArray(a)?a.map(u=>({...u,...h})):[{...a,...h}];r.push(...c);}}),produce(n,i=>traverse(i,({value:a,key:s,meta:d})=>{if(d.depth===2&&a.idFields&&!a.id){a.name=s;let h=()=>{if(d.nodePath?.split(".")[0]==="entities")return "entity";if(d.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=h();let c=Object.keys(t).find(u=>t[u]?.get(a.defaultDBConnector.id));if(a.db=c,a.dbContext=Fr[c],a.dbProviderConfig=c==="surrealDB"?t[c]?.get(a.defaultDBConnector.id)?.providerConfig:void 0,a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"linkFields"in a&&a.linkFields){let u=a;u.linkFields?.forEach(l=>{if(u.dataFields?.find(f=>f.path===l.path)||Object.keys(u.roles||{}).includes(l.path))throw new Error(`[Schema] The path ${l.path} is already in use by a dataField or linkField in ${u.name}. Path:${d.nodePath}`);let p=n.relations[l.relation];if(!l.isVirtual){if(!p)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(p.roles?.[l.plays]===void 0)throw new Error(`The role ${l.plays} is not defined in the relation ${l.relation} (linkField: ${l.path})`)}if(l.target==="relation"){if(l.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${u.name}" LinkField: "${l.path}. Path:${d.nodePath}."`);l.$things=[l.relation,...p.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){if(l.oppositeLinkFieldsPlayedBy=r.filter(f=>f.relation===l.relation&&f.plays!==l.plays&&f.target==="role"),l.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${u.name}" LinkField: "${l.path}. Path:${d.nodePath}."`);l.pathToRelation=u.linkFields?.find(f=>f.target==="relation"&&f.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(f=>[f.thing,...Y(n,f.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${u.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(f=>f.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(a.db==="surrealDB"){let f=p?.roles?.[l.plays][z]?.inheritanceOrigin??l.relation,$=br({linkField:l,originalRelation:f,withExtensionsSchema:n,linkMode:a.dbProviderConfig.linkMode});l[Re]={queryPath:$};}});}if("refFields"in a&&a.refFields&&(a.refFields=mapEntries(a.refFields,(u,l)=>{let p={...l,dbPath:l.dbPath||u};return [u,p]})),"roles"in a){let u=a;Object.entries(u.roles).forEach(([l,p])=>{if(u.dataFields?.find(m=>m.path===l)||u.linkFields?.find(m=>m.path===l))throw new Error(`[Schema] The path ${l} is already in use by a dataField or linkField in ${u.name}. Path:${d.nodePath}`);let f=r.filter(m=>m.relation===s&&m.plays===l)||[];p.playedBy=f.map(m=>({...m,pathToRelation:m.target==="relation"?m.path:u.linkFields?.find(S=>S.target==="relation"&&S.relation===s&&S.plays===l)?.path??m.relation.toLocaleLowerCase()}));let $=r.filter(m=>m.target==="relation"&&m.plays===l&&u.allExtends?.includes(m.relation));p.impactedLinkFields=$,p.path=l;let E=[...new Set(f.flatMap(m=>[...Y(n,m.thing).subTypes||[],m.thing]).flat().filter(Boolean))];p.$things=E;let g=p[z]?.inheritanceOrigin||a.name,y=E.flatMap(m=>{let M=Y(e,m)?.subTypes||[];return [m,...M]}),F=()=>{if(a.dbProviderConfig.linkMode==="edges")return `->\`${g}_${l}\`->(\`${y.join("`,`")}\`)`;if(a.dbProviderConfig.linkMode==="refs"){if(p.cardinality==="MANY")return `$parent.[\`${l}\`]`;if(p.cardinality==="ONE")return `$parent.\`${l}\``}throw new Error("Unsupported linkMode")};if(a.db==="surrealDB"){let m=F();p[Re]={queryPath:m};}});}}if(a&&typeof a=="object"&&"playedBy"in a){let h=[...new Set(a.playedBy.map(c=>c.thing))];if(h.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${d.nodePath}, played by: ${h.join(", ")}`),a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${d.nodePath}`)}if(d.depth===4){let[h,c]=d.nodePath?.split(".")||[],u=i[h][c];!isArray(a)&&typeof a=="object"&&(a.validations&&(a.validations.required&&u.requiredFields.push(a.path),a.validations.enum&&u.enumFields.push(a.path),a.validations.fn&&u.fnValidatedFields.push(a.path)),a.default?a.isVirtual?u.virtualFields.push(a.path):u.computedFields.push(a.path):a.isVirtual&&u.virtualFields.push(a.path));}}))},Y=(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`)},j=(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)}`)},st=(e,t)=>{let r=e.dataFields?.find(i=>i.path===t);if(e.idFields?.includes(t)){if(!r)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",r]}if(r)return ["dataField",r];let n=e.linkFields?.find(i=>i.path===t);if(n)return ["linkField",n];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`)},at=(e,t)=>{let r=j(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[n]=r.idFields;return n},Rr=(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")},Qt=(e,t,r)=>{let n=j(e,t),o=n.linkFields?.find(d=>d.path===r);if(o)return o;let i=n.dataFields?.find(d=>d.path===r);if(i)return i;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;let s="refFields"in n?n.refFields?.[r]:void 0;if(s)return s;throw new Error(`Field ${r} not found in schema`)},Rt=(e,t,r)=>Qt(e,t,r)?.cardinality,de=(e,t)=>{let r=e.dataFields?.map($=>$.path)||[],n=e.linkFields?.map($=>$.path)||[],o="refFields"in e?listify(e.refFields,$=>$):[],i="roles"in e?listify(e.roles,$=>$):[],a=[...r||[],...n||[],...i||[],...o||[]],d=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...a];if(!t)return {fields:a,dataFields:r,roleFields:i,linkFields:n};let h=t.$fields?t.$fields.map($=>{if(typeof $=="string"){if($.startsWith("$")||$.startsWith("%"))return;if(!a.includes($))throw new Error(`Field ${$} not found in the schema`);return $}if("$path"in $&&typeof $.$path=="string")return $.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,$=>{if(!($.startsWith("$")||$.startsWith("%"))){if(!a.includes($))throw new Error(`[Schema] Field ${$} not found in the schema`);return $}}).filter($=>$!==void 0),c=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&r?.includes($)):[],u=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&[...i||[],...n||[]].includes($)):[],l=[...h,...c].filter($=>!$?.startsWith("%")).filter($=>!d.includes($)).filter($=>$),p=t.$filter?ce(t.$filter,($,E)=>c.includes($)):{},f=t.$filter?ce(t.$filter,($,E)=>u.includes($)):{};return {fields:a,dataFields:r,roleFields:i,linkFields:n,refFields:o,usedFields:h,usedLinkFields:n.filter($=>h.includes($)),usedRoleFields:i.filter($=>h.includes($)),usedDataFields:r.filter($=>h.includes($)),usedRefFields:o.filter($=>h.includes($)),unidentifiedFields:l,...c.length?{localFilters:p}:{},...u.length?{nestedFilters:f}:{}}};var Dr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Ir=(e,t,r)=>{let o=(r.nodePath||"").split("."),i=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},De=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var lt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Me=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(([n,o])=>{r[n]=isDraft(o)?current(o):o;}),r}else return e},$e=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},Q=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Ie=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var Or=e=>{if(typeof e!="string")return {isPrefixed:!1,obj:e};let t=e.match(/^(?!_:)([^:]+):([^:]+)$/);if(!t)return {isPrefixed:!1,obj:e};let[,r,n]=t;return {isPrefixed:!0,obj:{$thing:r,$id:n}}},Ar=(e,t)=>{let r=isArray(e[t])?e[t]:[e[t]];if(r.every(o=>typeof o=="object"))return;if(!r.every(o=>typeof o=="string"||isObject(o)&&"$op"in o&&o.$op==="replace"))throw new Error(`[Mutation Error] Replace can only be used with a single id, an array of ids, or objects with $op: replace. (Field: ${t} Nodes: ${JSON.stringify(r)})`);let n=e.$op==="create"?"link":"replace";e[t]=r.map(o=>{if(typeof o=="string"){if(o.startsWith("_:"))return {$tempId:o,$op:n};let{isPrefixed:i,obj:a}=Or(o);return i?{...a,$op:n}:{$id:o,$op:n}}return o});},kr=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]],o=e.$op==="create"?"link":"replace";return e[t]=n.map(i=>{if(typeof i=="string"){if(i.startsWith("_:"))return {$tempId:i,$op:o};let{isPrefixed:a,obj:s}=Or(i);if(a)return {...s,$op:o};if(r.contentType==="FLEX")return i;throw new Error("[Wrong format] Field of contentType REF can't use strings as references unless they follow the format `$thing:$id`")}if(typeof i=="object"&&"$thing"in i||r.contentType==="FLEX")return i;throw new Error("[Wrong format] Field of contentType REF can use prefixed id strings, tempIds or objects indicating their $thing")})};var Ce=(e,t,r)=>{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`);let n=j(r,t),{usedDataFields:o}=de(n,t);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}},qr=(e,t,r)=>{(isArray(t)?t:[t]).forEach(o=>{Ce(e,o,r);});};var Pr=e=>{let t=Object.keys(e).filter(r=>!(r.startsWith("$")||r.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},Nr=(e,t,r)=>{let n=j(r,t),{usedFields:o}=de(n,t);return t.$op?(Ce(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Ce(e,{...t,$op:"update"},r),"update"):(Ce(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Ce(e,{...t,$op:"create"},r),"create"):(Ce(e,{...t,$op:"create"},r),"link"):(Ce(e,{...t,$op:"create"},r),"create")};var jr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let i=Nr(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Rr(o,t)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${Ie()}`}},...o}});e.$root=isArray(e.$root)?n:n[0];};var ct=(e,t)=>{let r=t[it];return isSet(r)?r.has("clean")?(Reflect.set(t,it,r.add("clean")),!0):!1:(Reflect.set(t,it,new Set(["clean"])),!0)};var _r=(e,t,r)=>{if(ct("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let i=o;if(j(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,s)=>({...Me(i),$id:a,$bzId:`${i.$bzId}_${s}`,...De(i)}))}return o});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var dt=(e,t)=>{if(t[z].fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t[z].fieldType==="roleField"){let r=t;if([...new Set(r.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var It=(e,t)=>e.$bzId?e.$bzId:e.$tempId?e.$tempId:e.$id&&!isArray(e.$id)?t?`SN_ONE_${t}_${e.$id}`:`SN_ONE_${e.$id}`:e.$id&&isArray(e.$id)?t?`SN_MANY_${t}_${Ie()}`:`SN_MANY_${Ie()}`:`SM_${Ie()}`;var Vr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);let a=Pr(i),s=It(i);if(r[z].fieldType==="refField"){let c=r;if(!isObject(i)){if(c.contentType==="FLEX")return i;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!i.$thing)throw new Error("[Wrong format] The field $thing is required in refFields");return {...i,$op:a,$bzId:s}}let d=r;if(d.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let h=r;if(h.$things.length===1){let c=dt(t,d),[u]=c;if(i.$thing&&i.$thing!==u.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${u.thing}.`);return {...i,[Te]:h,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:a,$bzId:s}}if(h.$things.length>1){if(i.$thing)return [{...i,[Te]:h,$thing:i.$thing,$thingType:i.$thing in n.entities?"entity":"relation",$op:a,$bzId:s}];if(!i.$thing){if(i.$tempId)throw new Error("[Unsupported] Objects with $tempId and multiple potential players require to explicitly indicate the $thing type.");if(a==="create")throw new Error(`[Wrong format] The field ${t} can be played by multiple things, please specify one on creation.`);return h.$things.map(c=>({...i,[Te]:h,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:a,$bzId:It(i,c)}))}}});isArray(e[t])||o.length>1?e[t]=o:e[t]=o[0],e[t]=isArray(e[t])?o:o[0];};var Hi=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,vi=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Wr=e=>{let r=e.toString().replace(Hi,"").trim().split("=>")[0].split("{")[0].replace(vi,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var Ue=({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:n}=t.default,i=Wr(n).filter(a=>!(a in e));if(i.length)throw new Error(`Virtual field: Missing arguments ${i.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var zr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(o=>{if(o.$op!=="create")return;let i=j(r,o),{unidentifiedFields:a}=de(i,o),{computedFields:s,virtualFields:d}=i,h=listify(o,(l,p)=>p!==void 0?l:void 0),c=h.filter(l=>d?.includes(l));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(l=>!h.includes(l)).forEach(l=>{let p=i.dataFields?.find(y=>y.path===l),$=i.linkFields?.find(y=>y.path===l)?.oppositeLinkFieldsPlayedBy[0],E="roles"in i?Lr(i.roles,(y,F)=>y===l):void 0,g=p||$||E;if(!g)throw new Error(`no field Def for ${l}`);if(!o[l]){let y=Ue({currentThing:o,fieldSchema:g,mandatoryDependencies:!0});o[l]=y;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(o)}`)}),e};var ut=(e,t)=>{let r=j(t,e).hooks;if(r?.pre){let n=`on${Dr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var vr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){if(i.$fields)return i;let{requiredFields:a,enumFields:s,fnValidatedFields:d,dataFields:h}=j(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(c=>{if(!(c in i))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&s.forEach(c=>{if(c in i){let u=h?.find(l=>l.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(i[c]))i[c].some(l=>{if(!u.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${c}".`)});else if(u&&!u.includes(i[c]))throw new Error(`[Validations] Option "${i[c]}" is not a valid option for field "${c}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&d.forEach(c=>{if(c in i)try{let u=h?.find(l=>l.path===c)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(i[c]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${c}] ${u.message}`)}}),isObject(i)&&"$thing"in i){let c=i.$thing,u=i,l=clone(Me(e)),p=clone(Me(u)),f=n.mutation?.context||{},$=clone(Me(i[_e]||{}));ut(u,r).forEach(g=>{if(g.type==="validate"){if(g.severity!=="error")return;try{let y=g.fn(p,l,f,$);if(y===!1)throw new Error(`${g.message}.`);if(y!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(y){throw new Error(`[Validations:thing:${c}] ${y.message}`)}}});}}});};var Kr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if(!lt(i)||i.$fields||i[Mt])return;let a=ut(i,r).filter(u=>u.type==="transform"),s=clone(Me(e)),d=clone(Me(i)),h=n.mutation?.context||{},c=clone(Me(i[_e]||i.$dbNode));a.forEach(u=>{let l=u.fn(d,s,h,c||{});Object.keys(l).length!==0&&(d={...d,...l,...De(i),[Mt]:!0},Object.assign(i,d));});});};var Jr=(e,t,r)=>{let n=dt(t,r),[o]=n;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Te]:r};};var Ve=e=>{if(Array.isArray(e)){for(let t of e)if(Ve(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"&&Ve(e[t]))return !0}return !1};var Xr=(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,i=>{let{value:a,meta:s}=i,d=a;if(isObject(d)){if(s.nodePath?.includes(".$filter")||s.nodePath?.includes(".$playedBy"))return;if(d[ee]=s.nodePath,d.$id){let h=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing},c=j(t,h);if(!c?.name)throw new Error(`Schema not found for ${d.$thing}`);if(d.$path=c.name,Array.isArray(d.$id)||(d.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in d||"$relation"in d||"$thing"in d){let h=j(t,d);if(!h?.name)throw new Error(`Schema not found for ${d.$thing}`);d.$path=h.name;}if(d.$entity?(d.$thing=d.$entity,d.$thingType="entity",delete d.$entity):d.$relation&&(d.$thing=d.$relation,d.$thingType="relation",delete d.$relation),isObject(d)&&"$thing"in d&&d.$thing){let h=d.$entity||d.$relation?d:{[`$${d.$thingType}`]:d.$thing},c=j(t,h);if(d.$filter&&(Object.keys(d.$filter).length===0?d.$filter=void 0:(d.$filter=Oe(d.$filter,d.$thing,t),d.$filterByUnique=qt(d.$filter,c))),d.$fields){d.$fields.some(p=>c?.idFields?.includes(p?.$path||p))||(d.$fields=[...d.$fields,...Array.isArray(c.idFields)?c.idFields:[]],d.$idNotIncluded=!0);let l=d.$fields?.flatMap(p=>{let f=Yr(p,c,t);return Array.isArray(f)?f:[f]}).filter(Boolean);d.$fields=l;}else {let l=kt(c)?.flatMap(p=>{let f=Yr(p,c,t);return Array.isArray(f)?f:[f]}).filter(Boolean);d.$fields=l;}d.$excludedFields&&(d.$fields=d.$fields.filter(u=>ht(c,u)?!0:!d.$excludedFields.includes(u.$path)));}}}))},kt=e=>{let t=e.dataFields?.map(a=>a.path)||[],r=e.linkFields?.map(a=>a.path)||[],n=Object.keys(e.roles||{})||[],o=Object.keys(e.refFields||{})||[];return [...t,...r,...n,...o]},qt=(e,t)=>Object.keys(e||{}).some(n=>{let o=e[n];if(o!==null&&typeof o<"u"){let i=t.idFields?.includes(n),a=t.dataFields?.some(h=>(h.dbPath===n||h.path===n)&&h?.validations?.unique),s=n==="$id"&&!Array.isArray(o);if(i||a||s){if(typeof o!="object"||o===null||Array.isArray(o))return !Array.isArray(o);{let h=Object.keys(o);if(h.length===1&&h[0]==="$eq"){let c=o.$eq;if(typeof c!="object"||c===null||!Array.isArray(c))return !0}return !1}}}return !1}),ht=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),to=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:o,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[ie]:a}},ro=e=>{let{field:t,fieldStr:r,linkField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e,{target:d,oppositeLinkFieldsPlayedBy:h}=n;return h.map(c=>{let u=d==="role"?c.thingType:"relation",l=d==="role"?c.thing:n.relation,p={[`$${u}`]:l},f=j(a,p),$=t?.$fields?.filter(y=>ht(f,y)).length===0,E=[];if(typeof t!="string")if(t.$fields)if($){let y=f.idFields||[];E=[...t.$fields,...y];}else E=t.$fields;else E=kt(f);else E=["id"];t.$excludedFields&&(E=E.filter(y=>ht(f,y)?!0:!t.$excludedFields.includes(y.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$plays:n.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:l,$fields:E,$excludedFields:t.$excludedFields,$fieldType:"link",$target:d,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:g,$idNotIncluded:$,$filterByUnique:qt(t.$filter,f),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},no=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:o,fieldSchema:i}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:r,$dbPath:o,$contentType:i.contentType,$as:t.$as||r,$var:r,$fieldType:"ref",$justId:n,$fields:t.$fields,$id:t.$id,[ie]:i}},io=e=>{let{field:t,fieldStr:r,roleField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e;return n.playedBy.map(d=>{let{thing:h,thingType:c,relation:u}=d,l={[`$${c}`]:h},p=j(a,l),f=t?.$fields?.filter(g=>p?.idFields?.includes(g)||p?.idFields?.includes(g.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(f){let g=p.idFields||[];$=[...t.$fields,...g];}else $=t.$fields;else $=kt(p);else $=["id"];t.$excludedFields&&($=$.filter(g=>ht(p,g)?!0:!t.$excludedFields.includes(g.$path)));let E=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:h,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:o,$id:t.$id,$filter:E,$idNotIncluded:f,$filterByUnique:qt(t.$filter,p),$playedBy:{...d,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Yr=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,o=typeof e=="string",i=t.dataFields?.find(h=>h.path===n),a=t.linkFields?.find(h=>h.path===n),s=t.roles?.[n],d=t.refFields?.[n];if(i){let h=!!i.isVirtual&&!!i.default;return to({field:e,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:h,fieldSchema:i})}else {if(a)return ro({field:e,fieldStr:n,linkField:a,$justId:o,dbPath:a.path,schema:r,fieldSchema:a});if(s)return io({field:e,fieldStr:n,roleField:s,$justId:o,dbPath:n,schema:r,fieldSchema:s});if(d)return no({field:e,fieldStr:n,$justId:o,dbPath:n,isVirtual:!1,fieldSchema:d})}return null},Oe=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce((h,c)=>{let u=a[c],l=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))h[c]=u;else if(["$not","$or","$and"].includes(c))h[c]=Oe(u,t,r);else if(["$eq","$in","$exists"].includes(c))h[c]=u;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let p=t in r.entities?r.entities[t]:r.relations[t],[f,$]=st(p,c);if(f==="idField")h[c]=u;else if(f==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?h[c]=isArray(u)?{$or:Oe(u,t,r)}:Oe(u,t,r):isArray(u)?h[c]={$in:u}:h[c]={$eq:u};else if(f==="linkField"||f==="roleField"){let E=$,[g]=E.$things;l.every(y=>typeof y=="string")?h[c]={$id:l,$thing:g}:l.every(y=>isObject(y))&&(h[c]=isArray(u)?{$or:Oe(u,g,r)}:Oe(u,g,r));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return h},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var Gr=(e,t,r,n)=>{let o=isArray(e[t])?e[t]:[e[t]],i=n.slice(1).join(".");o.forEach(a=>{if(a){if(r?.cardinality==="ONE"&&!a.$op&&!a.$id&&!a.$filter&&!a.$tempId&&e.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${i}.${t}`);if(a.$tempId&&!(a.$op===void 0||a.$op==="link"||a.$op==="create"||a.$op==="update"||a.$op==="replace"))throw new Error(`Invalid op ${a.$op} for tempId. TempIds can be created, or linked when created in another part of the same mutation.`)}});};var ho=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ct("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");t==="$filter"&&e.$filter&&Object.keys(e.$filter).length===0&&(e.$filter=void 0);},po=(e,t)=>{},Pt=(e,t,r)=>{let n={$rootWrap:{$root:e}},o=Ve(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:s,parent:d,key:h,meta:c})=>{if(!(!d||!h)&&isObject(s)){let u=c.nodePath?.split(".")||[];if(u.some(f=>f.startsWith("%")))return;if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let f=["$fields","$dbNode","$filter"],$=u[u.length-1],E=u[u.length-2];if(h==="$root")throw new Error("Root things must specify $entity or $relation");if(!f.includes($)&&!f.includes(E)&&!$.startsWith("%")&&!E.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let l=s,p=u.includes("$filter");"$filter"in l&&l.$filter&&(l.$filter=Oe(l.$filter,l.$thing,t)),Object.keys(l).forEach(f=>{if(ho(l,f),f!=="$root"&&p||f!=="$root"&&(f.startsWith("$")||f.startsWith("%")))return;let $=f!=="$root"?Qt(t,l,f):{[z]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${f} not found in schema`);let{fieldType:E}=$[z],g=["linkField","roleField"].includes(E),y=E==="refField",F=E==="rootField";if(E==="dataField")return po();if((g||y)&&(l[f]===null?g&&Jr(l,f,$):g?Ar(l,f):kr(l,f,$)),F){if(!("$root"in l))throw new Error(`[Internal] Field ${f} is a rootField but the object is not a root`);jr(l,t);}(g||y)&&Gr(l,f,$,u),(g||y)&&(Vr(l,f,$,t),qr(l,l[f],t)),(g||F)&&(_r(l,f,t),zr(l,f,t),(isArray(l[f])?l[f]:[l[f]]).forEach(S=>{let M=j(t,S),{unidentifiedFields:R,usedLinkFields:I,usedFields:x,fields:J}=de(M,S);if(x.forEach(re=>{if(!J.includes(re))throw new Error(`[Schema] Field ${re} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(s)}`);if(I.length>1){let re=M.linkFields?.filter(fe=>I.includes(fe.path));re?.some((fe,A)=>re.some((D,L)=>{if(A!==L&&fe.target!==D.target&&fe.relation===D.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||(Kr(l,f,t,r),vr(l,f,t,r)));});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var en=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(e,r=>traverse(r,t))};var on=async(e,t)=>{let r=c=>{let u=[],l=[],p=g=>{if(g.$id)return g.$id;let y=j(t,g),{idFields:F}=y;if(!F)throw new Error(`no idFields: ${JSON.stringify(g)}`);let[m]=F;if(!m)throw new Error(`no idField: ${JSON.stringify(g)}`);let S=y.dataFields?.find(I=>I.path===m),M=Ue({currentThing:g,fieldSchema:S,mandatoryDependencies:!0}),R=g[m]||g.$id||M;if(!R)throw new Error(`no idValue: ${JSON.stringify(g)}`);return R},f=g=>{if(g.$op==="create"){let y=p(g);if(u.find(F=>F.$id===y&&F.$op==="create"))throw new Error(`Duplicate id ${y} for node ${JSON.stringify(g)}`);u.push({...g,$id:y});return}g.$tempId&&g.$op==="match"||u.push(g);},$=g=>{if(g.$op==="create"){let y=p(g);if(u.find(F=>F.$id===y&&F.$op==="create"))throw new Error(`Duplicate id ${y} for edge ${JSON.stringify(g)}`);l.push({...g,$id:y});return}l.push(g);};return traverse(c,({value:g,parent:y,meta:F})=>{if(!isObject(g))return;let m=g;if(!F.nodePath?.includes(".$filter")&&m.$thing){if(!m.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(m)}`);if(!m.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(m)}`);let S=j(t,m),{dataFields:M,roleFields:R,linkFields:I,refFields:x,usedFields:J}=de(S,m),re=()=>{if(m.$op==="create"||m.$op==="delete")return m.$op;if(m.$op==="update"){let D=J.filter(T=>M?.includes(T)),L=J.filter(T=>R?.includes(T)),b=J.filter(T=>I?.includes(T)),B=J.filter(T=>x?.includes(T));if(D.length>0)return "update";if(L.length>0||b.length>0||B.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(m)}`)}return "match"},fe={...m.$id&&{$id:m.$id},...m.$tempId&&{$tempId:m.$tempId},...m.$filter&&{$filter:m.$filter},$thing:m.$thing,...m.$thingType&&{$thingType:m.$thingType},...shake(pick(m,M||[""])),$op:re(),$bzId:m.$bzId};f(fe);let A=m[Te];if(A?.[z].fieldType==="linkField"){if((m.$op==="link"||m.$op==="unlink")&&(m.$id||m.$filter)){if(m.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...m,$op:"match"});}let D=A.$things.includes(m.$thing),L=D?m.$bzId:`LT_${v4()}`,B=Ir(c,y,F).$bzId;if(!B)throw new Error("No parent id found");let T=()=>m.$op==="delete"?D?"match":"delete":m.$op==="unlink"?D?"unlink":"delete":m.$op==="link"||m.$op==="create"?D?"link":"create":m.$op==="replace"?"replace":"match",w=j(t,{$thing:A.relation,$thingType:"relation"});if(!Object.keys(w.roles).includes(A.plays))throw new Error(`[Wrong format] Field ${A.plays} is not a role of relation ${A.relation}`);let P={$bzId:L,$thing:D?m.$thing:A.relation,$thingType:"relation",...m.$tempId?{$tempId:m.$tempId}:{},$op:T(),...D?{}:{[A.path]:m.$bzId},[A.plays]:B,[Te]:A,[qe]:"linkField"};$(P),(m.$op==="unlink"||T()==="unlink")&&D&&$({$thing:A.relation,$thingType:"relation",$bzId:L,$op:"match",[A.plays]:B,[Te]:A,[qe]:"linkField"});}if(m.$thingType==="relation"){let D=ce(m,(B,T)=>R.includes(B)),L=mapEntries(D,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),b=ce(g,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(D).filter(B=>!B.startsWith("$")).length>0){if(m.$op==="create"||m.$op==="delete"){let B=()=>{if(m.$op==="create")return "link";if(m.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=j(t,m).roles,w=mapEntries(L,(P,q)=>{let O=T[P]?.cardinality;if(!O)throw new Error(`Role ${P} not found in schema`);return Array.isArray(q)?O==="ONE"?q.length>1?[P,q.map(v=>v.$bzId||v)]:[P,q[0].$bzId||q[0]]:[P,q.map(v=>v.$bzId||v)]:[P,q.$bzId||q]}),C={...b,$thing:m.$thing,$thingType:"relation",$op:B(),...w,$bzId:m.$bzId,[qe]:"roleField"};$(C);return}if(m.$op==="match"||m.$op==="update"&&Object.keys(D).length>0){let B=0;Object.entries(D).forEach(([T,w])=>{let C=isArray(w)?w:[w],P=q=>q==="create"||q==="replace"?"link":q;C.forEach(q=>{if(!q)return;let O=P(q.$op);if(O==="replace")throw new Error("Not supported yet: replace on roleFields");if(O==="unlink"&&B>0)throw B+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let v={...b,$thing:m.$thing,$thingType:"relation",$op:O==="delete"?"unlink":O,[T]:q.$bzId,$bzId:m.$bzId,[qe]:"roleField"};$(v);});});}}}}}),[u,l]},[n,o]=r(e),i=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let l=c.findIndex(p=>p.$bzId===u.$bzId);if(l===-1)return [...c,u];if(c[l].$op==="create"&&u.$op==="match")return c;if(c[l].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,l),u,...c.slice(l+1)];if(c[l].$op==="update"&&u.$op==="update")return [...c.slice(0,l),{...c[l],...u},...c.slice(l+1)];if(c[l].$op==="update"&&u.$op==="match"||c[l].$op==="match"&&u.$op==="update")return [...c.slice(0,l),{...c[l],...u,$op:"update"},...c.slice(l+1)];if(c[l].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[l].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[l].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[l].$op}. Current: ${u.$op}`)},[]),a=o.reduce((c,u)=>{let l=c.find(p=>(p.$id&&p.$id===u.$id||p.$bzId&&p.$bzId===u.$bzId)&&p.$thing===u.$thing&&p.$op===u.$op);if(l){let p={...l};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let E=l[$],g=u[$];Array.isArray(E)&&Array.isArray(g)?p[$]=Array.from(new Set([...E,...g])):!Array.isArray(E)&&Array.isArray(g)?E!==void 0?p[$]=Array.from(new Set([E,...g])):p[$]=g:Array.isArray(E)&&!Array.isArray(g)?g!==void 0&&(p[$]=Array.from(new Set([...E,g]))):E!==null&&g!==null&&E!==void 0&&g!==void 0?p[$]=Array.from(new Set([E,g])):E==null&&(p[$]=g);}),[...c.filter($=>!(($.$id&&$.$id===u.$id||$.$bzId&&$.$bzId===u.$bzId)&&$.$thing===u.$thing&&$.$op===u.$op)),p]}return [...c,u]},[]);i.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&a.filter(u=>u.$bzId===c.$bzId||u.$tempId&&u.$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(en(c))}`)}});let s=[...i,...a],d=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),h=Array.from(d).filter(c=>!s.some(u=>u.$tempId===c&&u.$op==="create"));if(h.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${h.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var ze={};function oe(e){return {enumerable:!0,value:e}}function sn(e){return {enumerable:!0,writable:!0,value:e}}var Bo=()=>!0,an=()=>({}),cn=e=>e,Fo=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),bo=(e,t,r,[n,o])=>t.call(r,e.call(r,n,o),o),Ae=(e,t)=>Object.freeze(Object.create(e,t));function ln(e,t,r){return e.reduce((n,o)=>function(...i){return r(n,o,this,i)},t)}function dn(e){return Ae(this,{fn:oe(e)})}var un={},_=dn.bind(un);var hn={},Nt=dn.bind(hn);function pt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function pn(e,t,...r){let n=ln(pt(hn,r).map(i=>i.fn),Bo,Fo),o=ln(pt(un,r).map(i=>i.fn),cn,bo);return Ae(this,{from:oe(e),to:oe(t),guards:oe(n),reducers:oe(o)})}var fn={},$n={},U=pn.bind(fn);pn.bind($n,null);function wo(e,t,r){return jt(t,e,r,this.immediates)||e}function mn(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 To={enter:cn};function ue(...e){let t=pt(fn,e),r=pt($n,e),n={final:oe(e.length===0),transitions:oe(mn(t))};return r.length&&(n.immediates=oe(r),n.enter=oe(wo)),Ae(To,n)}var Mo={enter(e,t,r){let n=this.fn.call(t,t.context,r);return xt.isPrototypeOf(n)?Ae(yn,{machine:oe(n),transitions:oe(this.transitions)}).enter(e,t,r):(n.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},yn={enter(e,t,r){if(t.child=ye(this.machine,n=>{t.onChange(n),t.child==n&&n.machine.state.value.final&&(delete t.child,t.send({type:"done",data:n.context}));},t.context,r),t.child.machine.state.value.final){let n=t.child.context;return delete t.child,jt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function H(e,...t){let r=oe(mn(t));return xt.isPrototypeOf(e)?Ae(yn,{machine:oe(e),transitions:r}):Ae(Mo,{fn:oe(e),transitions:r})}var xt={get state(){return {name:this.current,value:this.states[this.current]}}};function Ee(e,t,r=an){return typeof e!="string"&&(r=t||an,t=e,e=Object.keys(t)[0]),ze._create&&ze._create(e,t),Ae(xt,{context:oe(r),current:oe(e),states:oe(t)})}function jt(e,t,r,n){let{context:o}=e;for(let{to:i,guards:a,reducers:s}of n)if(a(o,r)){e.context=s.call(e,o,r);let d=t.original||t,h=Ae(d,{current:oe(i),original:{value:d}});ze._onEnter&&ze._onEnter(t,i,e.context,o,r);let c=h.state.value;return e.machine=h,e.onChange(e),c.enter(h,e,r)}}function So(e,t){let r=t.type||t,{machine:n}=e,{value:o,name:i}=n.state;return o.transitions.has(r)?jt(e,n,t,o.transitions.get(r))||n:(ze._send&&ze._send(r,i),n)}var Lo={send(e){So(this,e);}};function ye(e,t,r,n){let o=Object.create(Lo,{machine:sn(e),context:sn(e.context(r,n)),onChange:oe(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,n),o}var Fn=(e,t)=>{if(!t)return;let r=Ro(t);return Do(r,e.query)},Ro=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Do=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let o=n;Object.keys(o).forEach(i=>{(o[i]===void 0||o[i]===null||isArray(o[i])&&o[i].length===0)&&(t?.returnNulls?o[i]=null:delete o[i]),o[i]===void 0&&delete o[i];}),Object.getOwnPropertySymbols(o).forEach(i=>{delete o[i];}),t?.noMetadata===!0&&Object.keys(o).forEach(i=>{i.startsWith("$")&&delete o[i];});}}));var bn=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:s})=>{if(isObject(s)){let d=s;if(!d.$thing)return;if(d.$thing){let h=j(e,d),{virtualFields:c}=h,u=d[ee];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(d)}`);let l=getNodeByPath(t,u);if(l.$fieldType==="ref")return;let p=l.$fields.map($=>$.$path),f=l.$excludedFields;c.forEach($=>{if(f?.includes($)||p.length>0&&!p.includes($))return;let E=h.dataFields?.find(g=>g.path===$);if(E?.default){let g=Ue({currentThing:d,fieldSchema:E,mandatoryDependencies:!0});d[$]=g;}else if(d[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),f&&f.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete d[$];});}}})))(r):void 0;var Ze={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Be=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let d=Object.keys(a).reduce((h,c)=>{let u=a[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...h,[c]:void 0,[Ze[c]]:Be(u,t,r)};if(c==="$id")return {...h,$id:void 0,[Ze[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return h;if(c==="$exists")return {...h,$exists:void 0,[Ze[c]]:u};if(c==="$eq")return {...h,$eq:void 0,[Ze[c]]:u};if(c==="$in")return {...h,$in:void 0,[Ze[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let l=t in r.entities?r.entities[t]:r.relations[t],[p,f]=st(l,c);if(p==="idField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return {...h,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(p==="dataField")return {...h,[c]:Be(u,t,r)};if(p==="linkField"||p==="roleField"){let E=f[Re].queryPath;return {...h,[E]:Be(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(d)});return n?i:i[0]},me=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,o])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(o)?o.map(s=>me(s)):[me(o)];i==="!"?r.push(`!(${a.join(" AND ")})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(o))if(n.includes("<-")||n.includes("->")){let i=me(o);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=me(o),a=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=me(o),a=n.replace("$parent.","");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let i=Object.keys(o);if(i.length===1&&i[0].startsWith("$")){let[a]=i,s=o[a];if(a==="$exists")if(s===!0)r.push(`${n} IS NOT NONE`);else if(s===!1)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${s}`);else {let d=a.replace("$","");if(Array.isArray(s))r.push(`${n} ${d} [${s.map(h=>h===null?"NONE":`'${h}'`).join(", ")}]`);else if(isObject(s)){let h=me(s);r.push(`${n} ${d} ${h}`);}else r.push(`${n} ${d} ${s===null?"NONE":`'${s}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(o)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${o.map(a=>a===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${o===null?"NONE":`'${o}'`}`);}}),r.join(" AND ")},He=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:o}=r;return `${n}${o?" DESC":" ASC"}`}).join(", ")}`;var Tn=e=>{let{queries:t,schema:r}=e;return t.map(n=>Po({query:n,schema:r}))},Po=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:d}=t;if(o.length===0)return null;let h=[];h.push("SELECT");let c=Ut({parentQuery:t,queries:o,level:1,schema:r});c&&h.push(c);let u=r.entities[n]||r.relations[n];if(!u)throw new Error(`Schema for ${n} not found`);let p=(u.subTypes?[n,...u.subTypes]:[n]).map(f=>te(f));if(t.$id)if(typeof t.$id=="string")h.push(`FROM ${p.map(f=>`${f}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let f=t.$id,$=p.flatMap(E=>f?.map(g=>`${E}:\u27E8${g}\u27E9`));h.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else h.push(`FROM ${p.join(",")}`);if(i){let f=Be(i,n,r),$=me(f);h.push(`WHERE ${$}`);}return d&&h.push(He(d)),typeof s=="number"&&h.push(`LIMIT ${s}`),typeof a=="number"&&h.push(`START ${a}`),h.join(`
105
+ `)},Ut=e=>{let{queries:t,schema:r,level:n,parentQuery:o}=e,i=[],a=o[ee];return i.push(Q(`"${a}" as \`$$queryPath\``,n)),i.push(Q("record::id(id) as `$id`",n)),i.push(Q("record::tb(id) as `$thing`",n)),t.forEach(s=>{let d=No({query:s,level:n,schema:r});d&&i.push(d);}),i.length===0?null:i.join(`,
106
+ `)},No=e=>{let{query:t,schema:r,level:n}=e;if(t.$fieldType==="data")return xo({query:t,level:n});if(t.$fieldType==="ref")throw new Error("Ref fields are not supported in this context");return t.$fieldType==="link"?jo({query:t,level:n,schema:r}):t.$fieldType==="role"?_o({query:t,level:n,schema:r}):null},xo=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?Q(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?Q(`\`${t.$path}\``,r):Q(`\`${t.$path}\` AS \`${t.$as}\``,r)},jo=e=>{let{query:t,schema:r,level:n}=e,{$fields:o,$filter:i,$offset:a,$limit:s,$sort:d}=t;if(o.length===0)return null;let h=[];h.push(Q("(",n));let c=n+1;h.push(Q("SELECT",c));let u=Ut({parentQuery:t,queries:o,level:c+1,schema:r});u&&h.push(u);let l=t[ie][Re].queryPath;if(h.push(Q(`FROM ${l}`,c)),i){let p=Be(i,t.$thing,r),f=me(p);h.push(`WHERE ${f}`);}return d&&h.push(Q(He(d),c)),typeof s=="number"&&h.push(Q(`LIMIT ${s}`,c)),typeof a=="number"&&h.push(Q(`START ${a}`,c)),h.push(Q(`) AS \`${t.$as}\``,n)),h.join(`
107
+ `)},_o=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let o=[];o.push(Q("(",n));let i=n+1;o.push(Q("SELECT",i));let a=i+1,s=Ut({parentQuery:t,queries:t.$fields,level:a,schema:r});s&&o.push(s);let d=t[ie][Re].queryPath;if(o.push(Q(`FROM ${d}`,i)),t.$filter){let h=Be(t.$filter,t.$playedBy.thing,r),c=me(h);o.push(`WHERE ${c}`);}return o.push(Q(`) AS \`${t.$as}\``,n)),o.join(`
108
+ `)};var se="0.12.5";var Mn=new Set((process.env.LOG_LEVEL||"").split(",").map(e=>e.trim()).filter(e=>!!e)),Uo=(e,...t)=>{(Array.isArray(e)?e.some(n=>Mn.has(n)):Mn.has(e))&&console.log(...t);},ae=(...e)=>Uo("debug",...e);var Sn=async e=>{let{client:t,queries:r,config:n}=e,o=`
109
109
  BEGIN TRANSACTION;
110
110
  ${r.join(";")};
111
111
  COMMIT TRANSACTION;
112
- `;return n.query?.debugger&&ae(`batchedQuery[${se}]`,JSON.stringify({batchedQuery:a})),await t.query(a)};var Qn=e=>{let{res:t,queries:r,schema:n}=e;return t.map((i,s)=>Rn(r[s],i,n))},Rn=(e,t,r)=>{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 Vt(e,t[0],r)}if(t.length>=1)return t.map(n=>Vt(e,n,r))}else throw new Error("res is unexpectedly not an array")},Vt=(e,t,r)=>{let n=t.$thing||t.tb,a=n in r.entities?"entity":n in r.relations?"relation":"error";if(a==="error")throw new Error(`[Internal] The $thing ${n} is not defined in the schema.`);let i={[ee]:t.$$queryPath,$id:t.$id,$thing:$r(n),$thingType:a};return e.$fields.forEach(s=>{let o=s.$as,d=t[o];s.$path==="id"&&e.$idNotIncluded||(i[o]=Vo(s,d,r));}),i},Vo=(e,t,r)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:n}=e[ie];return Ln(t,n)??null}if(e.$fieldType==="ref"){let a=(isArray(t)?t:[t]).map(s=>{if(s.$thing){let o=Y(r,s.$thing),[d]=o.idFields;if(e.$justId)return s.$id;let h=u=>u&&typeof u=="object"&&"id"in u&&"tb"in u?u.id:u;return {...mapEntries(s,(u,l)=>isArray(l)?[u,l.map(p=>h(p))]:[u,h(l)]),[ee]:s.$$queryPath,[d]:s.$id}}return s.$value?Ln(s.$value,"FLEX"):s}),{cardinality:i}=e[ie];return i==="ONE"?a[0]:a}return e.$justId?e.$filterByUnique||e[ie].cardinality==="ONE"?t[0]?.$id??null:t?.map(n=>n.$id)??[]:e.$filterByUnique||e[ie].cardinality==="ONE"?Vt(e,t[0],r):Rn(e,t,r)},Ln=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(a=>new Date(a).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(a=>isDate(a)?new Date(a).toISOString():a);return isArray(e)?n:n[0]}return e};var Dn=e=>{let{queries:t,schema:r}=e;return t.map(n=>zo({query:n,schema:r}))},zo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:a,$filter:i,$offset:s,$limit:o,$sort:d}=t;if(a.length===0)return null;let h=r.entities[n]||r.relations[n];if(!h)throw new Error(`Schema for ${n} not found`);let c=t[ee],u=Wt(c),l=In(a.filter(S=>S.$fieldType==="data")),p=Cn(a.filter(S=>S.$fieldType==="link"||S.$fieldType==="role"),r),f=On(a.filter(S=>S.$fieldType==="ref")),$=[...u,...l,...p,...f].join(`,
113
- `),E=Ho(t,h),g=i?`WHERE id AND (${me(Be(i,n,r))})`:"WHERE id",y=d?ve(d):"",F=typeof o=="number"?`LIMIT ${o}`:"",m=typeof s=="number"?`START ${s}`:"";return `SELECT ${$} ${E} ${g} ${y} ${F} ${m}`},Ho=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(s=>te(s)),a=(s,o)=>`${s}:\`${o}\``,i=s=>n.flatMap(o=>s.map(d=>a(o,d))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${i([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${i(e.$id)}`;throw new Error("Invalid $id")},Wt=e=>[`"${e}" as \`$$queryPath\``,"id && record::id(id) || null as `$id`","id && record::tb(id) || null as `$thing`"],In=e=>e.map(t=>t.$path==="id"?`record::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),Cn=(e,t)=>e.map(r=>{if(!r[ee])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(r)}`);let n=Wt(r[ee]),a=In(r.$fields.filter(p=>p.$fieldType==="data")),i=Cn(r.$fields.filter(p=>p.$fieldType==="link"||p.$fieldType==="role"),t),s=On(r.$fields.filter(p=>p.$fieldType==="ref")),o=[...n,...a,...i,...s].filter(Boolean).join(`,
114
- `),d=`FROM $parent.\`${r[ie].path}\`[*]`,h=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${me(Be(r.$filter,r.$thing,t))})`:"WHERE id",c=r.$sort?ve(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",l=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${o} ${d} ${h} ${c} ${u} ${l} ) AS \`${r.$as}\``}).filter(r=>r),On=e=>e.map(t=>{if(!t[ee])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(t)}`);let r=Wt(t[ee]);if(t.$fields?.some(s=>isObject(s)))throw new Error("[Unsupported]: Can't query nested ref fields yet");let a=[...r,"id && null || $this as `$value`",...t.$justId?"":t.$fields?.map(s=>`\u27E8${s}\u27E9`)||["*"]].join(`,
115
- `),i=`FROM $parent.\`${t[ie].dbPath}\``;return `( SELECT ${a} ${i}) AS \`${t.$as}\``});var zt=U("error","error",_((e,t)=>({...e,error:t.error}))),vo=Ee("build",{build:H(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return Tn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return Dn({queries:e.bql.queries,schema:e.schema})},U("done","run",_((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),zt),run:H(async e=>Sn({client:e.client,queries:$e(e.surql.queries),config:e.config}),U("done","parse",_((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),zt),parse:H(async e=>Qn({res:$e(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),U("done","success",_((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),zt),success:ue(),error:ue()},e=>e),Ko=async e=>new Promise((t,r)=>{ye(vo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),An=async(e,t,r,n)=>Ko({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var ft=e=>{let{$filter:t,$var:r,$thing:n,schema:a,depth:i}=e,s=Go(t,Y(a,n)),{$not:o,...d}=s,h=[];if(vt(o)){let u=Ht(o,r,n,a,i,!0);h.push(...u);}else if(o!==void 0)throw new Error("$not must be a PositiveFilter object");let c=Ht(d,r,n,a,i,!1);return h.push(...c),h.join(`
116
- `)},Ht=(e,t,r,n,a,i)=>{let s=Y(n,r),o=[];for(let[d,h]of Object.entries(e)){if(d.startsWith("$")){let l=d.toLowerCase();if(l==="$and"||l==="$or"){let f=(isArray(h)?h:[h]).map(E=>{if(vt(E))return Ht(E,t,r,n,a+1,i).join(`
112
+ `;return n.query?.debugger&&ae(`batchedQuery[${se}]`,JSON.stringify({batchedQuery:o})),await t.query(o)};var Qn=e=>{let{res:t,queries:r,schema:n}=e;return t.map((i,a)=>Rn(r[a],i,n))},Rn=(e,t,r)=>{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 Vt(e,t[0],r)}if(t.length>=1)return t.map(n=>Vt(e,n,r))}else throw new Error("res is unexpectedly not an array")},Vt=(e,t,r)=>{let n=t.$thing||t.tb,o=n in r.entities?"entity":n in r.relations?"relation":"error";if(o==="error")throw new Error(`[Internal] The $thing ${n} is not defined in the schema.`);let i={[ee]:t.$$queryPath,$id:t.$id,$thing:$r(n),$thingType:o};return e.$fields.forEach(a=>{let s=a.$as,d=t[s];a.$path==="id"&&e.$idNotIncluded||(i[s]=zo(a,d,r));}),i},zo=(e,t,r)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:n}=e[ie];return Ln(t,n)??null}if(e.$fieldType==="ref"){let o=(isArray(t)?t:[t]).map(a=>{if(a.$thing){let s=Y(r,a.$thing),[d]=s.idFields;if(e.$justId)return a.$id;let h=u=>u&&typeof u=="object"&&"id"in u&&"tb"in u?u.id:u;return {...mapEntries(a,(u,l)=>isArray(l)?[u,l.map(p=>h(p))]:[u,h(l)]),[ee]:a.$$queryPath,[d]:a.$id}}return a.$value?Ln(a.$value,"FLEX"):a}),{cardinality:i}=e[ie];return i==="ONE"?o[0]:o}return e.$justId?e.$filterByUnique||e[ie].cardinality==="ONE"?t[0]?.$id??null:t?.map(n=>n.$id)??[]:e.$filterByUnique||e[ie].cardinality==="ONE"?Vt(e,t[0],r):Rn(e,t,r)},Ln=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(o=>new Date(o).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(o=>isDate(o)?new Date(o).toISOString():o);return isArray(e)?n:n[0]}return e};var Dn=e=>{let{queries:t,schema:r}=e;return t.map(n=>vo({query:n,schema:r}))},vo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:d}=t;if(o.length===0)return null;let h=r.entities[n]||r.relations[n];if(!h)throw new Error(`Schema for ${n} not found`);let c=t[ee],u=Wt(c),l=In(o.filter(S=>S.$fieldType==="data")),p=Cn(o.filter(S=>S.$fieldType==="link"||S.$fieldType==="role"),r),f=On(o.filter(S=>S.$fieldType==="ref")),$=[...u,...l,...p,...f].join(`,
113
+ `),E=Ko(t,h),g=i?`WHERE id AND (${me(Be(i,n,r))})`:"WHERE id",y=d?He(d):"",F=typeof s=="number"?`LIMIT ${s}`:"",m=typeof a=="number"?`START ${a}`:"";return `SELECT ${$} ${E} ${g} ${y} ${F} ${m}`},Ko=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(a=>te(a)),o=(a,s)=>`${a}:\`${s}\``,i=a=>n.flatMap(s=>a.map(d=>o(s,d))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${i([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${i(e.$id)}`;throw new Error("Invalid $id")},Wt=e=>[`"${e}" as \`$$queryPath\``,"id && record::id(id) || null as `$id`","id && record::tb(id) || null as `$thing`"],In=e=>e.map(t=>t.$path==="id"?`record::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),Cn=(e,t)=>e.map(r=>{if(!r[ee])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(r)}`);let n=Wt(r[ee]),o=In(r.$fields.filter(p=>p.$fieldType==="data")),i=Cn(r.$fields.filter(p=>p.$fieldType==="link"||p.$fieldType==="role"),t),a=On(r.$fields.filter(p=>p.$fieldType==="ref")),s=[...n,...o,...i,...a].filter(Boolean).join(`,
114
+ `),d=`FROM $parent.\`${r[ie].path}\`[*]`,h=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${me(Be(r.$filter,r.$thing,t))})`:"WHERE id",c=r.$sort?He(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",l=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${s} ${d} ${h} ${c} ${u} ${l} ) AS \`${r.$as}\``}).filter(r=>r),On=e=>e.map(t=>{if(!t[ee])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(t)}`);let r=Wt(t[ee]);if(t.$fields?.some(a=>isObject(a)))throw new Error("[Unsupported]: Can't query nested ref fields yet");let o=[...r,"id && null || $this as `$value`",...t.$justId?"":t.$fields?.map(a=>`\u27E8${a}\u27E9`)||["*"]].join(`,
115
+ `),i=`FROM $parent.\`${t[ie].dbPath}\``;return `( SELECT ${o} ${i}) AS \`${t.$as}\``});var zt=U("error","error",_((e,t)=>({...e,error:t.error}))),Jo=Ee("build",{build:H(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return Tn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return Dn({queries:e.bql.queries,schema:e.schema})},U("done","run",_((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),zt),run:H(async e=>Sn({client:e.client,queries:$e(e.surql.queries),config:e.config}),U("done","parse",_((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),zt),parse:H(async e=>Qn({res:$e(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),U("done","success",_((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),zt),success:ue(),error:ue()},e=>e),Yo=async e=>new Promise((t,r)=>{ye(Jo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),An=async(e,t,r,n)=>Yo({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var ft=e=>{let{$filter:t,$var:r,$thing:n,schema:o,depth:i}=e,a=es(t,Y(o,n)),{$not:s,...d}=a,h=[];if(vt(s)){let u=Ht(s,r,n,o,i,!0);h.push(...u);}else if(s!==void 0)throw new Error("$not must be a PositiveFilter object");let c=Ht(d,r,n,o,i,!1);return h.push(...c),h.join(`
116
+ `)},Ht=(e,t,r,n,o,i)=>{let a=Y(n,r),s=[];for(let[d,h]of Object.entries(e)){if(d.startsWith("$")){let l=d.toLowerCase();if(l==="$and"||l==="$or"){let f=(isArray(h)?h:[h]).map(E=>{if(vt(E))return Ht(E,t,r,n,o+1,i).join(`
117
117
  `);throw new Error(`Invalid subfilter in ${l}: ${JSON.stringify(E)}`)}),$=f.join(l==="$and"?`
118
- `:" } or { ");l==="$or"&&f.length>1?o.push(Q(`{ ${$} };`,a)):o.push(Q($,a));continue}continue}if(s.dataFields?.find(l=>l.dbPath===d||l.path===d)){let l=Jo(d,h,t,a,i);o.push(...l);continue}let u=s.linkFields?.find(l=>l.path===d);if(u){let l=Yo(u,h,t,n,a,i);o.push(...l);continue}if(s.thingType==="relation"){let l=s.roles[d];if(l){let p=Xo(l,h,t,r,n,a,i);o.push(...p);continue}}throw new Error(`"${r}" does not have property "${d}"`)}return o},Jo=(e,t,r,n,a)=>{let i=[];if(isObject(t)&&!isArray(t))for(let[s,o]of Object.entries(t)){let d=s.toLowerCase(),h="";switch(d){case"$eq":h=`$${r} has ${e} ${ge(o)};`;break;case"$ne":h=`not { $${r} has ${e} ${ge(o)}; };`;break;case"$in":{if(!isArray(o))throw new Error("Value for $in operator must be an array");let c=o.map(u=>`$${r} has ${e} ${ge(u)};`);h=rt(c),a&&(h=`not { ${h} };`);break}case"$nin":if(!isArray(o))throw new Error("Value for $nin operator must be an array");for(let c of o){let u=`not { $${r} has ${e} ${ge(c)}; };`;i.push(Q(u,n));}continue;case"$exists":if(o===!0)h=`$${r} has ${e} $${e}_${v4()};`;else if(o===!1)h=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${o}`);break;default:throw new Error(`Unsupported operator "${s}" for data field "${e}"`)}a&&(h=`not { ${h} };`),i.push(Q(h,n));}else if(isArray(t)){let s=t.map(d=>`$${r} has ${e} ${ge(d)};`),o=rt(s);o&&(a&&(o=`not { ${o} };`),i.push(Q(o,n)));}else {let s=`$${r} has ${e} ${ge(t)};`;a&&(s=`not { ${s} };`),i.push(Q(s,n));}return i},Yo=(e,t,r,n,a,i)=>{let s=[],[o]=e.oppositeLinkFieldsPlayedBy,h=Y(n,o.thing).idFields?.[0];if(!h)throw new Error(`"${o.thing}" does not have an id field`);let c=`${o.thing}_${v4()}`,u="";if(e.target==="relation")if(t===null)u=i?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(p=>`(${e.plays}: $${r}) isa ${e.relation}, has ${h} ${ge(p)};`);u=rt(l),i&&(u=`not { ${u} };`);}else u=`(${e.plays}: $${r}) isa ${e.relation}, has ${h} ${ge(t)};`,i&&(u=`not { ${u} };`);else if(t===null)u=i?`$${c} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(p=>`$${c} isa ${o.thing}, has ${h} ${ge(p)}; (${e.plays}: $${r}, ${o.plays}: $${c}) isa ${e.relation};`);u=rt(l),i&&(u=`not { ${u} };`);}else u=`$${c} isa ${o.thing}, has ${h} ${ge(t)}; (${e.plays}: $${r}, ${o.plays}: $${c}) isa ${e.relation};`,i&&(u=`not { ${u} };`);return s.push(Q(u,a)),s},Xo=(e,t,r,n,a,i,s)=>{let o=[],[d]=e.playedBy||[],c=Y(a,d.thing).idFields?.[0];if(!c)throw new Error(`"${d.thing}" does not have an id field`);let u=`${d.thing}_${v4()}`,l=v4(),p=`${r}_${l}`;o.push(Q(`$${p} isa ${n};`,i));let f="";if(t===null)f=`$${p} (${d.plays}: ${u});`,s?o.push(Q(f,i)):o.push(Q(`not { ${f} };`,i));else if(isArray(t)){let $=t.map(E=>`$${u} isa ${d.thing}, has ${c} ${ge(E)}; $${p} (${d.plays}: $${u});`);f=rt($),s?o.push(Q(`not { ${f} };`,i)):o.push(Q(f,i));}else f=`$${u} isa ${d.thing}, has ${c} ${ge(t)}; $${p} (${d.plays}: $${u});`,s?o.push(Q(`not { ${f} };`,i)):o.push(Q(f,i));return o.push(Q(`$${r} is $${p};`,i)),o},rt=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},ge=e=>{if(typeof e=="string")return `'${e}'`;if(typeof e=="number"||typeof e=="boolean")return `${e}`;if(e instanceof Date)return `'${e.toISOString().replace("Z","")}'`;if(isObject(e)){if("$id"in e){let t=e.$id;return isArray(t)?`like "^(${t.join("|")})$"`:ge(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},Go=(e,t)=>{let r={};if(t.dataFields?.forEach(s=>{s.path!==s.dbPath&&(r[s.path]=s.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...a}=e,i=kn(a,r);return n&&vt(n)&&(i.$not=kn(n,r)),i},kn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,a])=>{let i=t[n]||n;r[i]=a;}),r},vt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Kt="___",Pn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>Zo({query:n,schema:r}))},Zo=e=>{let{query:t,schema:r}=e,{$path:n,$thing:a,$filter:i,$fields:s,$sort:o,$offset:d,$limit:h,$id:c}=t;if(!n)throw new Error("Path is not defined");let u=[],l=t[ee];if(u.push("match"),u.push(`$${n} isa ${a};`),i||c){let $=lt(r,t),E={...i,...c?{[$]:c}:{}},g=ft({$filter:E,$var:n,$thing:a,schema:r,depth:0});u.push(`
119
- ${g}`);}let p=Gt({schema:r,$thing:a,$var:n,$sort:o,depth:0});p&&u.push(p.match);let f=`M_${v4()}`;if(u.push(`?queryPath${f} = "${l}";`),u.push("fetch"),u.push(`?queryPath${f} as "queryPath";`),s){let $=s.filter(y=>y.$fieldType==="data");$&&$.length>0&&u.push(...Jt($,n,0));let E=s.filter(y=>y.$fieldType==="link");E&&E.length>0&&u.push(...Xt(E,n,n,0,r));let g=s.filter(y=>y.$fieldType==="role");g&&g.length>0&&u.push(...Yt(g,n,n,0,r));}return p&&u.push(p.sort),typeof d=="number"&&u.push(`
118
+ `:" } or { ");l==="$or"&&f.length>1?s.push(Q(`{ ${$} };`,o)):s.push(Q($,o));continue}continue}if(a.dataFields?.find(l=>l.dbPath===d||l.path===d)){let l=Xo(d,h,t,o,i);s.push(...l);continue}let u=a.linkFields?.find(l=>l.path===d);if(u){let l=Go(u,h,t,n,o,i);s.push(...l);continue}if(a.thingType==="relation"){let l=a.roles[d];if(l){let p=Zo(l,h,t,r,n,o,i);s.push(...p);continue}}throw new Error(`"${r}" does not have property "${d}"`)}return s},Xo=(e,t,r,n,o)=>{let i=[];if(isObject(t)&&!isArray(t))for(let[a,s]of Object.entries(t)){let d=a.toLowerCase(),h="";switch(d){case"$eq":h=`$${r} has ${e} ${ge(s)};`;break;case"$ne":h=`not { $${r} has ${e} ${ge(s)}; };`;break;case"$in":{if(!isArray(s))throw new Error("Value for $in operator must be an array");let c=s.map(u=>`$${r} has ${e} ${ge(u)};`);h=tt(c),o&&(h=`not { ${h} };`);break}case"$nin":if(!isArray(s))throw new Error("Value for $nin operator must be an array");for(let c of s){let u=`not { $${r} has ${e} ${ge(c)}; };`;i.push(Q(u,n));}continue;case"$exists":if(s===!0)h=`$${r} has ${e} $${e}_${v4()};`;else if(s===!1)h=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${s}`);break;default:throw new Error(`Unsupported operator "${a}" for data field "${e}"`)}o&&(h=`not { ${h} };`),i.push(Q(h,n));}else if(isArray(t)){let a=t.map(d=>`$${r} has ${e} ${ge(d)};`),s=tt(a);s&&(o&&(s=`not { ${s} };`),i.push(Q(s,n)));}else {let a=`$${r} has ${e} ${ge(t)};`;o&&(a=`not { ${a} };`),i.push(Q(a,n));}return i},Go=(e,t,r,n,o,i)=>{let a=[],[s]=e.oppositeLinkFieldsPlayedBy,h=Y(n,s.thing).idFields?.[0];if(!h)throw new Error(`"${s.thing}" does not have an id field`);let c=`${s.thing}_${v4()}`,u="";if(e.target==="relation")if(t===null)u=i?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(p=>`(${e.plays}: $${r}) isa ${e.relation}, has ${h} ${ge(p)};`);u=tt(l),i&&(u=`not { ${u} };`);}else u=`(${e.plays}: $${r}) isa ${e.relation}, has ${h} ${ge(t)};`,i&&(u=`not { ${u} };`);else if(t===null)u=i?`$${c} isa ${s.thing}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${s.thing}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(p=>`$${c} isa ${s.thing}, has ${h} ${ge(p)}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation};`);u=tt(l),i&&(u=`not { ${u} };`);}else u=`$${c} isa ${s.thing}, has ${h} ${ge(t)}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation};`,i&&(u=`not { ${u} };`);return a.push(Q(u,o)),a},Zo=(e,t,r,n,o,i,a)=>{let s=[],[d]=e.playedBy||[],c=Y(o,d.thing).idFields?.[0];if(!c)throw new Error(`"${d.thing}" does not have an id field`);let u=`${d.thing}_${v4()}`,l=v4(),p=`${r}_${l}`;s.push(Q(`$${p} isa ${n};`,i));let f="";if(t===null)f=`$${p} (${d.plays}: ${u});`,a?s.push(Q(f,i)):s.push(Q(`not { ${f} };`,i));else if(isArray(t)){let $=t.map(E=>`$${u} isa ${d.thing}, has ${c} ${ge(E)}; $${p} (${d.plays}: $${u});`);f=tt($),a?s.push(Q(`not { ${f} };`,i)):s.push(Q(f,i));}else f=`$${u} isa ${d.thing}, has ${c} ${ge(t)}; $${p} (${d.plays}: $${u});`,a?s.push(Q(`not { ${f} };`,i)):s.push(Q(f,i));return s.push(Q(`$${r} is $${p};`,i)),s},tt=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},ge=e=>{if(typeof e=="string")return `'${e}'`;if(typeof e=="number"||typeof e=="boolean")return `${e}`;if(e instanceof Date)return `'${e.toISOString().replace("Z","")}'`;if(isObject(e)){if("$id"in e){let t=e.$id;return isArray(t)?`like "^(${t.join("|")})$"`:ge(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},es=(e,t)=>{let r={};if(t.dataFields?.forEach(a=>{a.path!==a.dbPath&&(r[a.path]=a.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...o}=e,i=kn(o,r);return n&&vt(n)&&(i.$not=kn(n,r)),i},kn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,o])=>{let i=t[n]||n;r[i]=o;}),r},vt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Kt="___",Pn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>ts({query:n,schema:r}))},ts=e=>{let{query:t,schema:r}=e,{$path:n,$thing:o,$filter:i,$fields:a,$sort:s,$offset:d,$limit:h,$id:c}=t;if(!n)throw new Error("Path is not defined");let u=[],l=t[ee];if(u.push("match"),u.push(`$${n} isa ${o};`),i||c){let $=at(r,t),E={...i,...c?{[$]:c}:{}},g=ft({$filter:E,$var:n,$thing:o,schema:r,depth:0});u.push(`
119
+ ${g}`);}let p=Gt({schema:r,$thing:o,$var:n,$sort:s,depth:0});p&&u.push(p.match);let f=`M_${v4()}`;if(u.push(`?queryPath${f} = "${l}";`),u.push("fetch"),u.push(`?queryPath${f} as "queryPath";`),a){let $=a.filter(y=>y.$fieldType==="data");$&&$.length>0&&u.push(...Jt($,n,0));let E=a.filter(y=>y.$fieldType==="link");E&&E.length>0&&u.push(...Xt(E,n,n,0,r));let g=a.filter(y=>y.$fieldType==="role");g&&g.length>0&&u.push(...Yt(g,n,n,0,r));}return p&&u.push(p.sort),typeof d=="number"&&u.push(`
120
120
  offset ${d};`),typeof h=="number"&&u.push(`
121
121
  limit ${h};`),u.join(`
122
- `)},Jt=(e,t,r)=>{let n=[],a=[],i=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][ie].contentType==="FLEX"&&i.push({path:e[c][ie].dbPath}),a.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=n.join(", "),d=`$metadata:{as:[${a.join(",")}]}`,h=[Q(`$${t} as "${t}.${d}.$dataFields": ${s};`,r)];return i.length>0&&i.forEach(c=>{h.push(Q(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),h},Yt=(e,t,r,n,a)=>{let i=n+1,s=[];for(let o of e){let{$fields:d,$as:h,$justId:c,$idNotIncluded:u,$filterByUnique:l,$thing:p,$sort:f,$offset:$,$limit:E}=o,g=o[ee],y=`$metadata:{as:${h},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${l}}`;s.push(Q(`"${r}.${y}.${o.$var}": {`,n)),s.push(Q("match",i));let F=`${t}${Kt}${o.$var}`;if(s.push(Q(`$${F} isa ${o.$thing};`,i)),s.push(Q(`$${t} (${o.$var}: $${t}${Kt}${o.$var}) isa ${o.$intermediary};`,i)),o.$filter||o.$id){let S=lt(a,o),M=o.$id?{[S]:o.$id}:{},R={...o.$filter,...M};s.push(ft({$filter:R,$var:F,$thing:o.$thing,schema:a,depth:i}));}let m=Gt({schema:a,$thing:p,$var:F,$sort:f,depth:i});if(m&&s.push(m.match),d){let S=`M_${v4()}`;s.push(Q(`
123
- ?queryPath${S} = "${g}";`,i)),s.push(Q("fetch",i)),s.push(Q(`?queryPath${S} as "queryPath";`,i));let M=d?.filter(x=>x.$fieldType==="data");M&&M.length>0&&s.push(...Jt(M,F,i));let R=d?.filter(x=>x.$fieldType==="link");R&&R.length>0&&s.push(...Xt(R,F,`${t}.${o.$var}`,i,a));let I=d?.filter(x=>x.$fieldType==="role");I&&I.length>0&&s.push(...Yt(I,F,`${t}.${o.$var}`,i,a));}m&&s.push(m.sort),typeof $=="number"&&s.push(Q(`offset ${$};`,i)),typeof E=="number"&&s.push(Q(`limit ${E};`,i)),s.push(Q("};",n));}return s},Xt=(e,t,r,n,a)=>{let i=n+1,s=[];for(let o of e){let{$fields:d,$as:h,$justId:c,$idNotIncluded:u,$filterByUnique:l,$playedBy:p,$thing:f,$sort:$,$offset:E,$limit:g}=o,y=o[ee],F=`$metadata:{as:${h},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${l}}`;s.push(Q(`"${r}.${F}.${o.$var}": {`,n)),s.push(Q("match",i));let m=`${t}${Kt}${o.$var}`;if(s.push(Q(`$${m} isa ${o.$thing};`,i)),o.$filter||o.$id){let M=lt(a,o),R=o.$id?{[M]:o.$id}:{},I={...o.$filter,...R};s.push(ft({$filter:I,$var:m,$thing:o.$thing,schema:a,depth:i}));}let S=Gt({schema:a,$thing:f,$var:m,$sort:$,depth:i});if(S&&s.push(S.match),o.$target==="role"?s.push(Q(`$${t}_intermediary (${o.$plays}: $${t}, ${p.plays}: $${m}) isa ${o.$intermediary};`,i)):s.push(Q(`$${m} (${o.$plays}: $${t});`,i)),d){let M=`M_${v4()}`;s.push(Q(`?queryPath${M} = "${y}";`,i)),s.push(Q("fetch",i)),s.push(Q(`?queryPath${M} as "queryPath";`,i));let R=d?.filter(J=>J.$fieldType==="data");R&&R.length>0&&s.push(...Jt(R,m,i));let I=d?.filter(J=>J.$fieldType==="link");I&&I.length>0&&s.push(...Xt(I,m,`${t}.${o.$var}`,i,a));let x=d?.filter(J=>J.$fieldType==="role");x&&x.length>0&&s.push(...Yt(x,m,`${t}.${o.$var}`,i,a));}S&&s.push(S.sort),typeof E=="number"&&s.push(Q(`offset ${E};`,i)),typeof g=="number"&&s.push(Q(`limit ${g};`,i)),s.push(Q("};",n));}return s},es=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Gt=e=>{let{$var:t,$thing:r,schema:n,$sort:a,depth:i}=e,s=Y(n,r),o=[],d=[];if(a?.forEach(h=>{let c=es(h),u=s.dataFields?.find(f=>f.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let l=`${c.field}_${v4()}`;o.push(Q("{",i)),o.push(Q(`$${t} has ${u.dbPath} $${l}_1;`,i+1)),o.push(Q("not {",i+1)),o.push(Q(`$${t} has ${u.dbPath} $${l}_2;`,i+2)),o.push(Q(`$${l}_2 < $${l}_1;`,i+2)),o.push(Q("};",i+1)),o.push(Q(`?${l}_ = $${l}_1;`,i+1)),o.push(Q("} or {",i)),o.push(Q(`not { $${t} has ${u.dbPath} $${l}_1; };`,i+1)),o.push(Q(`?${l}_ = "~";`,i+1)),o.push(Q("};",i)),o.push(Q(`?${l} = ?${l}_;`,i));let p=c.desc?"desc":"asc";d.push(`?${l} ${p}`);}),o.length!==0)return {match:o.join(""),sort:Q(`sort ${d.join(", ")};`,i)}};var xn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:a,rawTqlRes:i}=e;if(t){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((s,o)=>{let d=r[o],h=t[o];return rs(s,d,h,n,a)})},rs=(e,t,r,n,a)=>e.length===0?null:r.$filterByUnique?Nn(e[0],t,n,a):e.map(i=>Nn(i,t,n,a)),Nn=(e,t,r,n)=>{let{dataFields:a,currentSchema:i,linkFields:s,roleFields:o,schemaValue:d}=Zt(e,r),h=er(a,i,n),c=rr(s,r,n),u=tr(o,r,n),l=t?.$fields?.every(f=>!i?.idFields?.includes(typeof f=="string"?f:f.$path));return {...c,...u,...d,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?h.id:t.$id}:{},...l?Object.fromEntries(Object.entries(h).filter(([f])=>!i?.idFields?.includes(f))):h}},Zt=(e,t)=>{let r=Object.keys(e),n=r.find(p=>p.endsWith(".$dataFields")),a=r.filter(p=>p.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");a?.length>0&&a.forEach(p=>{let f=p.replace(/\.\$multiVal$/,""),$=e[p][0][f].attribute;e[n][f]=$;});let i=e[n],s=n.split(".")[n.split(".").length-2];if(i.$metaData=s,i.length===0)throw new Error("No dataFields");let o=i.type,d={$thing:o.label,$thingType:o.root,[ee]:e.queryPath.value},h={[`$${d.$thingType}`]:d.$thing},c=j(t,h),u=r.filter(p=>{let f=$e(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===f)}).map(p=>{let f=$e(p.split(".").pop()),$=$e(c.linkFields?.find(E=>E.path===f));return {$linkFields:e[p],$key:f,$metaData:p.split(".")[p.split(".").length-2],$cardinality:$.cardinality}}),l=r.filter(p=>{let f=p.split(".").pop();return f&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[f]}).map(p=>{let f=$e(p.split(".").pop());return {$roleFields:e[p],$key:f,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[f].cardinality}});return {dataFields:i,schemaValue:d,currentSchema:c,linkFields:u,roleFields:l}},er=(e,t,r)=>{let{$metaData:n}=e,{as:a}=ns(n),i=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).map(([s,o])=>{let d=t.dataFields?.find(l=>l.path===s||l.dbPath===s),h=s==="id",c=Array.isArray(a)?a.find(l=>l[s])?.[s]:s,u;if(d?.cardinality==="ONE"){if(u=o[0]?o[0].value:r.query?.returnNulls?null:void 0,d.contentType==="DATE"||d.contentType==="FLEX"&&o[0].type.value_type==="datetime"?u=u&&`${u}Z`:d.contentType==="JSON"&&(u=u&&JSON.parse(u)),h)return [[c,u],["$id",u]].filter(([l,p])=>p!==void 0)}else if(d?.cardinality==="MANY"){if(!isArray(o))throw new Error("Typedb fetch has changed its format");if(o.length===0)return r.query?.returnNulls?[[c,null]]:[];d.contentType==="DATE"?u=o.map(l=>`${l.value}Z`):d.contentType==="FLEX"?u=o.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):d.contentType==="JSON"?u=o.map(l=>l.value&&JSON.parse(l.value)):u=o.map(l=>l.value);}return [[c,u]].filter(([l,p])=>p!==void 0)}).flat();return Object.fromEntries([...i])},tr=(e,t,r)=>{let n={};return e.forEach(a=>{let{$roleFields:i,$metaData:s,$cardinality:o}=a,{as:d,justId:h,idNotIncluded:c,filterByUnique:u}=jn(s);if(d===null)return;let l=i.map(p=>{let{dataFields:f,currentSchema:$,linkFields:E,roleFields:g,schemaValue:y}=Zt(p,t),F=er(f,$,r);if(h==="T")return F.id;{let m=rr(E,t,r),S=tr(g,t,r),M={...F};return c==="true"&&$?.idFields?.forEach(R=>delete M[R]),{...M,...m,...S,...y}}});l.length>0?n[d]=o==="MANY"&&u==="false"?l:l[0]:r.query?.returnNulls&&(n[d]=null);}),n},rr=(e,t,r)=>{let n={};return e.forEach(a=>{let{$linkFields:i,$metaData:s,$cardinality:o}=a,{as:d,justId:h,idNotIncluded:c,filterByUnique:u}=jn(s);if(d===null)return;let l=i.map(p=>{let{dataFields:f,currentSchema:$,linkFields:E,roleFields:g,schemaValue:y}=Zt(p,t),F=er(f,$,r);if(h==="T")return F.id;{let m=rr(E,t,r),S=tr(g,t,r),M={...F};return c==="true"&&$.idFields?.forEach(R=>delete M[R]),{...M,...m,...S,...y}}});n[d]=l.length>0?o==="MANY"&&u==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},jn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,a=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),s=e.match(r),o=e.match(n),d=e.match(a);return {as:i?i[1]:null,justId:s?s[1]:null,idNotIncluded:o?o[1]:null,filterByUnique:d?d[1]:null}},ns=e=>{try{let r=(a=>{let i=a.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,o,d)=>/^{.*}$/.test(d)?`:${d}`:`:${o}"${d}"`),i=i.replace(/\[([^\]]+)\]/g,(s,o)=>`[${o.split(",").map(d=>d.trim().startsWith("{")&&d.trim().endsWith("}")?d.trim():`"${d.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var mt=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,a=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!a)throw new Error("Client not found");n=await a.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:a,session:n});}return {client:a,session:n}};var _n=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,a=new TypeDBOptions;a.infer=!0;let{session:i}=await mt(r,n),s=await i.transaction(TransactionType.READ,a),[o,d]=await tryit(parallel)(t.length,t,async h=>await s.query.fetch(h).collect());if(o){await s.rollback();let h=o;throw new Error(`Error running TQL query: ${h.errors}`)}return await s.close(),d};var cs=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ds=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,us=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,nr=U("error","error",_((e,t)=>({...e,error:t.error}))),hs=Ee("build",{build:H(async e=>Pn({queries:e.bql.queries,schema:e.schema}),U("done","run",_(ds)),nr),run:H(async e=>_n({dbHandles:e.handles,tqlRequest:$e(e.tql.queries),config:e.config}),U("done","parse",_(us)),nr),parse:H(async e=>xn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:$e(e.tql.res)}),U("done","success",_(cs)),nr),success:ue(),error:ue()},e=>e),ps=async e=>new Promise((t,r)=>{ye(hs,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Un=async(e,t,r,n,a)=>ps({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:a,error:null});var fs=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,ir=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,yt=U("error","error",_((e,t)=>({...e,error:t.error}))),$s=Ee("enrich",{enrich:H(async e=>(ae(`originalBQLQuery[${se}]`,JSON.stringify(e.bql.raw)),Xr(e.bql.raw,e.schema)),U("done","adapter",_(fs)),yt),adapter:H(async e=>{let t={};e.bql.queries?.forEach((o,d)=>{let h=e.bql.raw[d],c=Y(e.schema,o.$thing),{id:u}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[u]){let p=e.handles.typeDB?.get(u)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[u]){let p=e.handles.surrealDB?.get(u)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let l=t[u];l.rawBql.push(h),l.bqlQueries.push(o),l.indices.push(d);});let r=Object.values(t),n=r.map(o=>{if(o.db==="typeDB")return Un(o.rawBql,o.bqlQueries,e.schema,e.config,e.handles);if(o.db==="surrealDB")return An(o.bqlQueries,e.schema,e.config,o.client);throw new Error(`Unsupported DB "${JSON.stringify(o,null,2)}"`)}),a=await Promise.all(n),i=r.flatMap((o,d)=>{let h=a[d];return o.indices.map((c,u)=>({index:c,result:h[u]}))});return i.sort((o,d)=>o.index<d.index?-1:o.index>d.index?1:0),i.map(({result:o})=>o)},U("done","postHooks",_(ir)),yt),postHooks:H(async e=>bn(e.schema,$e(e.bql.queries),$e(e.bql.res)),U("done","clean",_(ir)),yt),clean:H(async e=>Fn(e.config,$e(e.bql.res)),U("done","success",_(ir)),yt),success:ue(),error:ue()},e=>e),ms=async e=>new Promise((t,r)=>{ye($s,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Ke=async(e,t,r,n)=>ms({bql:{raw:e},schema:t,config:r,handles:n,error:null});var or="___",gs=Symbol.for("grandChildOfCreate"),Vn=async(e,t,r,n)=>{let a=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],i=(L,b)=>Object.keys(L).filter(B=>!B.startsWith("$")&&!a.includes(B)&&L[B]!==void 0?b?!j(t,L).dataFields?.find(w=>w.path===B):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let s=[];if(traverse(e,({parent:L,key:b,value:B})=>{L&&b&&!b.includes("$")&&!a.includes(b)&&isObject(L)?(Array.isArray(L[b])?L[b]:[L[b]]).forEach(w=>{if(isObject(w)){if(L.$op!=="create")s.includes(w.$op)||s.push(w.$op);else if(w.$op==="delete"||w.$op==="unlink")throw new Error(`Cannot ${w.$op} under a create`)}}):!L&&isObject(B)&&(s.includes(B.$op)||s.push(B.$op));}),!s.includes("delete")&&!s.includes("unlink")&&!s.includes("replace")&&!s.includes("update")&&!s.includes("link"))return;let d=(L=>{let b=(B,T)=>{let w=[],C={},P=["$op","$bzId","$parentKey"],q=["$relation","$entity","$id",...P];for(let O in B)if(!P.includes(O)&&!(q.includes(O)&&!T))if(!O.includes("$")&&(isObject(B[O])||Array.isArray(B[O]))){let v=Es(B[O]);if(Array.isArray(v)&&v.length>0)v.forEach(Te=>{let Fe={$path:O,...b(Te),...Te.$filter&&{$as:Te.$bzId}};w.find(X=>X.$path===Fe.$path&&!X.$filter)||(w=[...w,Fe]);});else {let Te={$path:O,...b(v),...!v.$filter&&{$as:v.$bzId}};w=[...w,Te];}}else C[O]=B[O];return {...C,$fields:w}};return L.map(B=>b(B,!0))})(Array.isArray(e)?e:[e]),c=(await Ke(d,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,u=(L,b)=>{let B=L.$id||L.id||L.$bzId;if(L.$objectPath){let{$objectPath:T}=L,w=T?.beforePath||"root",C=Array.isArray(T.ids)?`[${T.ids}]`:T.ids;return {beforePath:`${w}.${C}___${T.key}`,ids:B,key:b}}else return {beforePath:"root",ids:B,key:b}},l=(L,b)=>{let B=L?.beforePath||"root";if(typeof B!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let T=(Array.isArray(L?.ids)?`[${L?.ids}]`:L?.ids);return `${B}.${T}___${L?.key}`},p=L=>{if(L.includes("[")&&L.includes("]")){let[b,B,T]=L.split(/[[\]]/);return B.split(",").map(C=>`${b}${C}${T}`)}else return [L]},f={};(L=>produce(L,b=>traverse(b,({key:B,parent:T})=>{if(T&&B&&T.$id&&!B.includes("$")){let w=u(T,B),C=l(w);if(Array.isArray(T[B])){let P=[];T[B].forEach(q=>{isObject(q)?(q.$objectPath=w,P.push(q.$id.toString())):q&&P.push(q.toString());}),f[C]={$objectPath:w,$ids:P};}else {let P=T[B];isObject(P)?(f[C]={$objectPath:w,$ids:[P.$id.toString()]},P.$objectPath=w):P?f[C]={$objectPath:w,$ids:[P.toString()]}:P===null&&(f[C]=null);}}})))(c||{});let E=L=>produce(L,b=>traverse(b,({key:B,value:T,parent:w})=>{w&&B&&!B.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(w)&&(Array.isArray(w[B])?w[B].forEach(C=>{typeof C!="string"&&(C.$objectPath=u(w,B),C.$parentIsCreate=w.$op==="create",C[gs]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[B])&&(w[B].$parentIsCreate=w.$op==="create",w[B][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[B].$objectPath=u(w,B)));})),g=E(e),y=L=>{let b=[];return L.forEach(T=>{if(!T.$id&&!T.id&&!T.$tempId)if(T.$filter){let w=l({...T.$objectPath,key:T.$bzId}),C=f[w];C&&(Array.isArray(C.$ids)?C.$ids:[C.$ids]).forEach(q=>{let O={...T,$id:q,$bzId:`T4_${v4()}`,$filterBzId:T.$bzId};b.push(O);});}else {let w=l(T.$objectPath),C=f[w];C?C?.$ids?.forEach(P=>{let q={...T,$id:P,$bzId:`T4_${v4()}`};b.push(q);}):b.push(T);}else b.push(T);}),b.map(T=>{let w={...T};return i(w,!0).forEach(C=>{let P=Array.isArray(w[C])?w[C]:[w[C]],q=y(P);w[C]=q;}),w})},F=y(Array.isArray(g)?g:[g]),m=E(F),M=(L=>{let b=B=>{let T=X=>{let Z=[],K=[],N=[];return X.forEach(V=>{let le=i(V,!0);if(le.length>0){let k=!1;le.forEach(W=>{(Array.isArray(V[W])?V[W]:[V[W]]).filter(ne=>!ne.$id&&!ne.id&&typeof V=="object").length&&(k=!0);}),k?Z.push(V):K.push(V);}else V.$id?N.push({...V,$bzId:V.$tempId||V.$bzId}):N.push({...V,$bzId:V.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:Z,operationWithoutMultiples:K,otherOps:N}},{operationWithMultiples:w,operationWithoutMultiples:C,otherOps:P}=T(B),q=X=>{let K=(()=>{let W={};for(let he in X){let G=j(t,X);!he.startsWith("$")&&G.dataFields?.find(ne=>ne.path===he)&&(W[he]=X[he]);}return W})(),N=Object.keys(X),V=i(X,!0),le=[],k=(W,he)=>{if(W===V.length){let ne={...he};N.forEach(pe=>{pe.startsWith("$")&&(ne[pe]=X[pe]);}),le.push({...ne,...K});return}let G={...he,[V[W]]:X[V[W]],...Ie(he),...K};k(W+1,G),k(W+1,he);};return k(0,{...Ie(X)}),le},O=[];return w.forEach(X=>{let Z=q(X),K=[];Z.forEach(N=>{let V=i(N,!0);if(N.$op==="create")K.push(N);else if(N.$id){let le=l(N.$objectPath),k=[];if(V.forEach(W=>{let he=`${le.includes("undefined")?"root":le}.${N.$id}${or}${W}`,G=f[he];N[W].filter(pe=>pe.$op==="unlink"||pe.$op==="delete"||pe.$op==="update").length>0?G?.$ids&&k.push({key:W,ids:G.$ids}):k.push({key:W,ids:[""]});}),k.length===V.length&&!K.find(W=>W.$id===N.$id))K.push(N);else {let W={...N,$bzId:N.$tempId||`T4_${v4()}`};V.forEach(G=>{let ne=N[G].filter(pe=>pe.$id);ne.length>0?W[G]=ne:W[G]=void 0;}),i(W,!0).length>0&&K.push(W);}}else if(N.$objectPath){let le=l(N.$objectPath),k=f[le]?.$ids||[];k.forEach(W=>{let he=[];V.forEach(G=>{let ne=`${le}.${W}${or}${G}`,pe=f[ne];pe&&he.push({key:G,ids:pe.$ids});}),V.length===0?k.filter(ne=>!K.find(pe=>pe.$id===ne)).forEach(ne=>{K.push({...N,$id:ne,$bzId:N.$tempId||`PQT2_${v4()}`});}):he.length===V.length&&!K.find(G=>G.$id===W)&&(V.forEach(G=>{let ne=`${l(N.$objectPath)}.${W}${or}${G}`,pe=f[ne]?.$ids||[],yi=N[G].find(xe=>!xe.$id),pr=[...pe.map(xe=>({...yi,$id:xe,$objectPath:{beforePath:N.$objectPath.beforePath,ids:xe,key:G}})),...N[G].filter(xe=>xe.$id)];pr.length>0&&(N[G]=pr);}),K.push({...N,$id:W,$bzId:N.$tempId||`PQ3_${v4()}`}));});}else K.push(N);}),K.forEach(N=>{O.push(N);});}),[...O,...C,...P].filter(X=>i(X).length>0?!0:X.$op!=="update").map(X=>{let Z={...X};return i(Z,!0).forEach(K=>{let N=Array.isArray(Z[K])?Z[K]:[Z[K]],V=b(N);Z[K]=V;}),Z})};return b(L)})(Array.isArray(m)?m:[m]),R=L=>L.map(b=>{let B=i(b,!0),T={...b};return B.forEach(w=>{let C=Array.isArray(b[w])?b[w]:[b[w]],P=[],q=[],O=[],v={},Te=Rt(t,b,w);C.filter(k=>k).forEach(k=>{k.$op==="replace"&&k.$id?(v=k,Array.isArray(k.$id)?q=[...q,...k.$id]:q.push(k.$id)):k.$op==="create"&&Te==="ONE"&&k.id?(v=k,Array.isArray(k.id)?O=[...q,...k.id]:O.push(k.id)):P.push(k);});let Fe=l(v.$objectPath),Z=p(Fe).map(k=>f[k]),K=[];Z.filter(k=>k!=null).forEach(k=>{K=[...K,...k?.$ids||[]];});let N=K.filter(k=>!q.includes(k)),V=q.filter(k=>!K.includes(k)),le=Ie(v);N.length>0&&P.push({...v,$op:"unlink",$id:N,$bzId:v.$tempId||`T4_${v4()}`,id:void 0,...le}),V.length>0&&V.forEach(k=>{P.push({...v,$op:"link",$id:k,$bzId:v.$tempId||`T5_${v4()}`,...le});}),O.length>0&&O.forEach(k=>{P.push({...v,$op:"create",id:k,$bzId:v.$tempId||`T6_${v4()}`,...le});}),T[w]=R(P);}),T}),I=E(R(E(M)));(L=>produce(L,b=>traverse(b,B=>{let{key:T,value:w,parent:C,meta:P}=B;T&&C&&!T?.includes("$")&&T!=="$filter"&&!P.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(C)&&(Array.isArray(w)?w:[w]).forEach(O=>{let v=O.$filter?{...O.$objectPath,key:O.$filterBzId}:O.$objectPath,Te=l(v),Fe=f[Te],X=(N,V)=>N.every(le=>V.includes(le)),Z=O.$id?Array.isArray(O.$id)?X(O.$id,Fe&&Fe.$ids?Fe.$ids:[]):Fe?.$ids?.includes(O.$id):Fe,K=Rt(t,C,O.$objectPath.key);if(O.$op==="link"&&Z&&K==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${l(O.$objectPath)}" because it is already occupied.`);if(O.$op)switch(O.$op){case"delete":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${O.$id}" because it is not linked to $id:"${C.$id}"`);break;case"update":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${O.$id}" because it is not linked to $id:"${C.$id}"`);break;case"unlink":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${O.$id}" because it is not linked to $id:"${C.$id}"`);break;case"link":if(Z)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${O.$id}" because it is already linked to $id:"${C.$id}"`);break;}});})))(I);let re=(L=>produce(L,b=>traverse(b,B=>{let{value:T,meta:w}=B;isObject(T)&&(T[Symbol.for("path")]=w.nodePath,delete T.$objectPath,delete T.$parentIsCreate);})))(I);return [...Array.isArray(re)?re:[re]].sort((L,b)=>L.$op==="create"&&b.$op!=="create"?-1:L.$op!=="create"&&b.$op==="create"?1:0)},Es=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Wn=(e,t)=>produce(e,n=>Et(t,n)),Et=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(a=>Et(e,a,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([a])=>{a.startsWith("$")||a.startsWith("%")||Fs(e,t,a,n);});},Fs=(e,t,r,n)=>{let a=t[r];if(!a)return;let i=n.dataFields?.find(d=>d.path===r);if(i){i.contentType==="JSON"&&a!=null&&(t[r]=JSON.stringify(a));return}let s=n.linkFields?.find(d=>d.path===r);if(s){let d=s.oppositeLinkFieldsPlayedBy[0]?.thing;Et(e,a,d);return}if(!n.refFields[r]&&n.thingType==="relation"){let d=n.roles[r];if(!d)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[h]=d.playedBy||[];if(!h)throw new Error(`Role ${d.path} in ${n} is not played by anything`);Et(e,a,h.thing);}};var Kn=async(e,t,r,n)=>{let a=Array.isArray(e)?e:[e],i=a.map(d=>sr(d,!0)),o=(await Ke(i,t,r,n)).bql.res;return a.map((d,h)=>{let c=Y(t,d.$thing);return Yn({mut:d,node:o[h],schema:t,thing:c})})},Jn=new Set(["$op","$bzId","$parentKey"]),ws=new Set(["$relation","$entity","$id",...Jn]),sr=(e,t)=>{let r={};e.$fields?.forEach(a=>{typeof a=="string"?r[a]=a:r[a.$path]=a;});let n={};for(let a in e){if(Jn.has(a)||ws.has(a)&&!t)continue;let i=e[a];a.startsWith("$")?n[a]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[a]={$path:a,...sr(i[0],!1)}):isObject(i)&&(r[a]={$path:a,...sr(i,!1)});}return n.$fields=Object.values(r),n},Yn=e=>{let{mut:t,node:r,schema:n,thing:a}=e,i=Gn(a),s=Ms(r);if(Array.isArray(t))return t.map(d=>{let h=s[d.$id];return h?zn({mut:d,node:h,schema:n,thing:a,...i}):d});let o=s[t.$id];return zn({mut:t,node:o,schema:n,thing:a,...i})},zn=e=>{let{mut:t,node:r,schema:n,thing:a,dataFieldMap:i,linkFieldMap:s,roleFieldMap:o}=e,{$fields:d,...h}=t;if(!r)return h;let c=Xn({$fields:t.$fields,node:r,schema:n,thing:a,dataFieldMap:i,linkFieldMap:s,roleFieldMap:o}),u={...h,[_e]:c};for(let l in t){if(l.startsWith("$"))continue;let p=t[l];if(i[l]||!p||typeof p!="object"){u[l]=p;continue}let $=s[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${a.name}" does not have field "${l}"`);let E=Y(n,$);u[l]=Yn({mut:p,schema:n,node:r[l],thing:E});}return u},Xn=e=>{let{$fields:t,node:r,schema:n,thing:a,dataFieldMap:i,linkFieldMap:s,roleFieldMap:o}=e,d=t||Ts(a),h={$id:r.$id};return d.forEach(c=>{let u=typeof c!="string",l=u?c.$path:c,p=r[l];if(i[l]){h[l]=p;return}let $=s[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${a.name}" does not have field "${l}"`);if(!u){p&&(h[l]=Array.isArray(p)?p.map(Hn):Hn(p));return}let E=Y(n,$),g=Gn(E);h[l]=Array.isArray(p)?p.map(y=>vn({...g,$fields:c.$fields,value:y,schema:n,thing:E})):vn({...g,$fields:c.$fields,value:p,schema:n,thing:E});}),h},Ts=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},Hn=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},vn=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 Xn({...e,node:t})},Gn=e=>{let t=Object.fromEntries(e.dataFields?.map(a=>[a.path,a])||[]),r=Object.fromEntries(e.linkFields?.map(a=>[a.path,a])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},Ms=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 ar=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 ei=async(e,t,r)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!r)throw new Error("No schema provided");let n=l=>{let p=l.$op,f=`$${l.$bzId}`,$=j(r,l),{idFields:E,defaultDBConnector:g}=$,y=g?.path||l.$thing,F=l.$id,m=E?.[0],S=listify(l,(A,D)=>{if(A.startsWith("$")||A.startsWith("%")||A===m||D===void 0||D===null)return "";let L=$.dataFields?.find(T=>T.path===A);if(!L?.path)return "";let B=L.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(L.contentType))return `has ${B} '${D}'`;if(["NUMBER","BOOLEAN"].includes(L.contentType))return `has ${B} ${D}`;if(L.contentType==="DATE"){if(Number.isNaN(D.valueOf()))throw new Error("Invalid format, Nan Date");return D instanceof Date?`has ${B} ${D.toISOString().replace("Z","")}`:`has ${B} ${new Date(D).toISOString().replace("Z","")}`}if(L.contentType==="FLEX"){let T=`bza${be()}`,w=isArray(D)?D.map(C=>ar(C)):ar(D);if(Array.isArray(w))throw new Error("Array in FLEX fields not supported yet");return `has ${B} $${T}; $${T} '${T}' isa ${B}, has ${w.type}Attribute ${w.value}`}throw new Error(`Unsupported contentType ${L.contentType}`)}).filter(A=>A),M=`${f}-atts`,R=listify(l,A=>{if(A.startsWith("$")||A.startsWith("%")||A===m)return "";let D=$.dataFields?.find(B=>B.path===A);if(!D?.path)return "";let b=D.dbPath;return `{${M} isa ${b};}`}).filter(A=>A),I=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,x=F?[`has ${m} ${I}`]:[],J=[...x,...S].filter(A=>A).join(","),re=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${f} isa ${[y,...x].filter(A=>A).join(",")};`;if(p==="update"){if(!R.length)throw new Error("update without attributes");return `${f} isa ${[y,...x].filter(A=>A).join(",")}, has ${M};
124
- ${R.join(" or ")};`}return ""},fe=()=>p==="update"||p==="link"||p==="match"?`${f} isa ${[y,...x].filter(A=>A).join(",")};`:"";if(ct(l))return {op:p,deletionMatch:re(),insertionMatch:fe(),insertion:p==="create"?`${f} isa ${[y,J].filter(A=>A).join(",")};`:p==="update"&&S.length?`${f} ${S.join(",")};`:"",deletion:p==="delete"?`${f} isa ${y};`:p==="update"&&R.length?`${f} has ${M};`:""};throw new Error("in attributes")},a=l=>{let p=l.$op,f=j(r,l),$=`$${l.$bzId}`,E=l.$id,g=f.defaultDBConnector?.path||l.$thing,y="roles"in f?listify(f.roles,D=>D):[],F="roles"in f?mapEntries(f.roles,(D,L)=>[D,L.dbConnector?.path||D]):{},m=listify(l,(D,L)=>{if(!y.includes(D))return null;if(!("roles"in f))throw new Error("This should have roles! ");let b=F[D];return Array.isArray(L)?L.map(B=>({path:b,id:B})):{path:b,id:L}}).filter(D=>D).flat(),S=m.map(D=>{if(!D?.path)throw new Error("Object without path");return `${D.path}: $${D.id}`}),M=m.length>0?`( ${S.join(" , ")} )`:"",R=l[qe];if(!R)throw new Error("[internal error] Symbol edgeType not defined");let I=M?`${$} ${M} ${R==="linkField"||p==="delete"||p==="unlink"?`isa ${g}`:""}`:"",x=`${$} ${R==="linkField"||p==="delete"?`isa ${g}`:""}`,J=()=>I?p==="link"?`${I};`:p==="create"?`${I}, has id '${E}';`:"":"",re=()=>I&&p==="match"?`${I};`:"",fe=()=>I?p==="delete"?`${I};`:p==="match"?`${I};`:"":"",A=()=>I?p==="delete"?`${x};`:p==="unlink"?`${$} ${M};`:"":"";return {deletionMatch:fe(),insertionMatch:re(),deletion:A(),insertion:J(),op:""}},i=(l,p)=>{let f=p==="edges"?a:n;if(Array.isArray(l))return l.map(m=>{let{preDeletionBatch:S,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x}=f(m);return shake({preDeletionBatch:S,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x},J=>!J)}).filter(m=>m);let{preDeletionBatch:$,insertionMatch:E,deletionMatch:g,insertion:y,deletion:F}=f(l);return shake({preDeletionBatch:$,insertionMatch:E,deletionMatch:g,insertion:y,deletion:F},m=>!m)},s=i(e),o=Array.isArray(s)?s:[s],d=i(t,"edges"),h=Array.isArray(d)?d:[d],c=[...o,...h];return shake({insertionMatches:c.map(l=>l.insertionMatch).join(" ").trim(),deletionMatches:c.map(l=>l.deletionMatch).join(" ").trim(),insertions:c.map(l=>l.insertion).join(" ").trim(),deletions:c.map(l=>l.deletion).join(" ").trim()},l=>!l)};var ti=async(e,t,r,n,a)=>{let i=[...t,...r],s=i.map(o=>{let d=e.insertions?.find(u=>u.get(`${o.$bzId}`))?.get(`${o.$bzId}`),h=o.$thing||o.$relation||o.$entity,c=h?Y(n,h):void 0;if(o.$op==="create"||o.$op==="update"||o.$op==="link"){if(o.$op!=="update"&&!d&&o.$id)return {$id:o.$id,$error:"Does not exist or it's not linked to the parent"};let u=d?.asThing().iid,l=Object.entries(o).filter(([f,$])=>!f.startsWith("$")).reduce((f,[$,E])=>{if(c?.dataFields?.find(y=>y.path===$)?.contentType==="JSON")return f[$]=JSON.parse(E),f;if(o.$thingType==="relation"){let y=i.filter(F=>F.$id&&F.$bzId===E);return y.length===1?(f[$]=y[0].$id,f):(f[$]=E,f)}return f[$]=E,f},{});if(a.mutation?.noMetadata)return l;let p=o.$tempId&&!o.$tempId.startsWith("_:")?{$tempId:`_:${o.$tempId}`}:{};return {$dbId:u,...o,...l,[o.path]:o.$id,...p}}if(o.$op==="delete"||o.$op==="unlink")return o;if(o.$op!=="match")throw new Error(`Unsupported op ${o.$op}`)}).filter(o=>o);return clone(s)};var ri=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:n}=await mt(t,r),a=await n.transaction(TransactionType.WRITE),i=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{i&&await a.query.delete(i);let o=s&&a.query.insert(s),d=o?await o.collect():void 0;return await a.commit(),{insertions:d}}catch(o){throw new Error(`Transaction failed: ${o.message}`)}finally{await a.close();}};var Ds=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Is=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),Cs=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),cr=U("error","error",_((e,t)=>({...e,error:t.error}))),Os=Ee("buildMutation",{buildMutation:H(async e=>ei(e.bql.things,e.bql.edges,e.schema),U("done","runMutation",_(Is)),cr),runMutation:H(async e=>ri(e.tql.mutation,e.handles,e.config),U("done","parseMutation",_(Cs)),cr),parseMutation:H(async e=>ti(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),U("done","success",_(Ds)),cr),success:ue(),error:ue()},e=>e),As=async e=>new Promise((t,r)=>{ye(Os,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ni=async(e,t,r,n,a,i,s)=>As({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:a,config:i,handles:s,error:null});var ii=async(e,t)=>{let r=o=>{let{$filter:d,$thing:h,$bzId:c,$op:u,$id:l,$tempId:p}=o,f=Y(t,h),{usedDataFields:$}=de(f,o),{idFields:E}=f,g=l||o[E[0]],y=(isArray(h)?h:[h]).map(te),F=ce(o,b=>b.startsWith("$")),m=ce(o,b=>!b.startsWith("$")),S=JSON.stringify(m),M=Object.entries(F).map(([b,B])=>b=="$tempId"?`'$tempId': '_:${B}'`:`'${b}': '${B}'`).join(","),R=o[st],I=$.filter(b=>!E.includes(b)).map(b=>{let B=f.dataFields?.find(w=>w.path===b||w.dbPath===b);if(!B)throw new Error(`Data field schema not found for ${b}`);let T=o[b];return T===null?`${b} = NONE`:`${b} = ${je(T,B.contentType)}`}).filter(Boolean),x=`$\u27E8${p||c}\u27E9`,J=R?.bzId?`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:g?isArray(g)?y.flatMap(b=>g.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${g}\u27E9`).join(", "):!0,re=(()=>{if(R?.bzId){let b=`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return g?isArray(g)?`${b}[? $this.id() IN [${g.map(B=>`'${B}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${g}'] ]`:b}else return g?isArray(g)?y.flatMap(b=>g.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${g}\u27E9`).join(", "):y.join(", ")})(),fe=d?`WHERE ${me(Be(d,h,t))}`:"",A=I.length>0?`SET ${I.join(", ")}`:"",D=`VALUE (CREATE ONLY Delta SET input = ${S}, meta = {${M}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,L="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(o.$op==="match")return p?"":`LET ${x} = (SELECT VALUE id FROM ${re} ${fe});`;if(o.$op==="create"){if(isArray(g))throw new Error("Cannot create multiple things at once");let b=te(h);return `LET ${x} = (CREATE ONLY ${b}:\u27E8${g}\u27E9 ${A} RETURN ${D});`}if(o.$op==="update")return `LET ${x} = IF (${J}) THEN (UPDATE ${re} ${A} ${fe} RETURN ${D}) END;`;if(o.$op==="delete")return `LET ${x} = IF (${J}) THEN (DELETE ${re} ${fe} RETURN ${L}) END;`;throw new Error(`Unsupported operation ${o.$op}`)},n=o=>{let{$thing:d,$bzId:h,$op:c,$tempId:u}=o,l=Y(t,d),{usedRoleFields:p}=de(l,o),f=`$\u27E8${u||h}\u27E9`,$="roles"in l?p.flatMap(y=>{let F=l.roles[y];if(!F)throw new Error(`Role field schema not found for ${y}`);let{cardinality:m}=F,S=isArray(o[y])?o[y].map(M=>`$\u27E8${M}\u27E9`):[`$\u27E8${o[y]}\u27E9`];if(m==="ONE"){if(S.length>1){let M=`array::filter(array::flatten([${S}]), |$v| !!$v)`;switch(c){case"link":case"replace":return `${y} = ((array::len(${M})==1) && ${M}[0]) || ${M}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case"link":case"replace":return `${y} = ((type::is::array(${S[0]}) && array::len(${S[0]})==1) && ${S[0]}[0]) || ${S[0]}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}else if(m==="MANY"){let M=`array::flatten([${S}])`;switch(c){case"link":return `${y} += ${M}`;case"unlink":return `${y} -= ${M}`;case"replace":return `${y} = ${M}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${m}`)}):[],E=$.length>0?`${$.join(", ")}`:"",g=E?`SET ${E}`:"";return `IF ${f} THEN (UPDATE ${f} ${g} RETURN VALUE id) END; ${f};`},a=o=>{let{$thing:d,$op:h}=o,c=Y(t,d),u=te(d),{usedRoleFields:l}=de(c,o);if(!["create","delete"].includes(h))throw new Error("Arcs can only be created or deleted");let[p,f]=l,$=isArray(o[p])?o[p]:[o[p]],E=isArray(o[f])?o[f]:[o[f]];if(h==="create"){if(l.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let g=ce(o,x=>!x.startsWith("$")),F=`(CREATE ONLY Delta SET input = ${JSON.stringify(g)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,S=c.roles[p].cardinality==="MANY",R=c.roles[f].cardinality==="MANY";return [`
122
+ `)},Jt=(e,t,r)=>{let n=[],o=[],i=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][ie].contentType==="FLEX"&&i.push({path:e[c][ie].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let a=n.join(", "),d=`$metadata:{as:[${o.join(",")}]}`,h=[Q(`$${t} as "${t}.${d}.$dataFields": ${a};`,r)];return i.length>0&&i.forEach(c=>{h.push(Q(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),h},Yt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:d,$as:h,$justId:c,$idNotIncluded:u,$filterByUnique:l,$thing:p,$sort:f,$offset:$,$limit:E}=s,g=s[ee],y=`$metadata:{as:${h},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${l}}`;a.push(Q(`"${r}.${y}.${s.$var}": {`,n)),a.push(Q("match",i));let F=`${t}${Kt}${s.$var}`;if(a.push(Q(`$${F} isa ${s.$thing};`,i)),a.push(Q(`$${t} (${s.$var}: $${t}${Kt}${s.$var}) isa ${s.$intermediary};`,i)),s.$filter||s.$id){let S=at(o,s),M=s.$id?{[S]:s.$id}:{},R={...s.$filter,...M};a.push(ft({$filter:R,$var:F,$thing:s.$thing,schema:o,depth:i}));}let m=Gt({schema:o,$thing:p,$var:F,$sort:f,depth:i});if(m&&a.push(m.match),d){let S=`M_${v4()}`;a.push(Q(`
123
+ ?queryPath${S} = "${g}";`,i)),a.push(Q("fetch",i)),a.push(Q(`?queryPath${S} as "queryPath";`,i));let M=d?.filter(x=>x.$fieldType==="data");M&&M.length>0&&a.push(...Jt(M,F,i));let R=d?.filter(x=>x.$fieldType==="link");R&&R.length>0&&a.push(...Xt(R,F,`${t}.${s.$var}`,i,o));let I=d?.filter(x=>x.$fieldType==="role");I&&I.length>0&&a.push(...Yt(I,F,`${t}.${s.$var}`,i,o));}m&&a.push(m.sort),typeof $=="number"&&a.push(Q(`offset ${$};`,i)),typeof E=="number"&&a.push(Q(`limit ${E};`,i)),a.push(Q("};",n));}return a},Xt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:d,$as:h,$justId:c,$idNotIncluded:u,$filterByUnique:l,$playedBy:p,$thing:f,$sort:$,$offset:E,$limit:g}=s,y=s[ee],F=`$metadata:{as:${h},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${l}}`;a.push(Q(`"${r}.${F}.${s.$var}": {`,n)),a.push(Q("match",i));let m=`${t}${Kt}${s.$var}`;if(a.push(Q(`$${m} isa ${s.$thing};`,i)),s.$filter||s.$id){let M=at(o,s),R=s.$id?{[M]:s.$id}:{},I={...s.$filter,...R};a.push(ft({$filter:I,$var:m,$thing:s.$thing,schema:o,depth:i}));}let S=Gt({schema:o,$thing:f,$var:m,$sort:$,depth:i});if(S&&a.push(S.match),s.$target==="role"?a.push(Q(`$${t}_intermediary (${s.$plays}: $${t}, ${p.plays}: $${m}) isa ${s.$intermediary};`,i)):a.push(Q(`$${m} (${s.$plays}: $${t});`,i)),d){let M=`M_${v4()}`;a.push(Q(`?queryPath${M} = "${y}";`,i)),a.push(Q("fetch",i)),a.push(Q(`?queryPath${M} as "queryPath";`,i));let R=d?.filter(J=>J.$fieldType==="data");R&&R.length>0&&a.push(...Jt(R,m,i));let I=d?.filter(J=>J.$fieldType==="link");I&&I.length>0&&a.push(...Xt(I,m,`${t}.${s.$var}`,i,o));let x=d?.filter(J=>J.$fieldType==="role");x&&x.length>0&&a.push(...Yt(x,m,`${t}.${s.$var}`,i,o));}S&&a.push(S.sort),typeof E=="number"&&a.push(Q(`offset ${E};`,i)),typeof g=="number"&&a.push(Q(`limit ${g};`,i)),a.push(Q("};",n));}return a},rs=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Gt=e=>{let{$var:t,$thing:r,schema:n,$sort:o,depth:i}=e,a=Y(n,r),s=[],d=[];if(o?.forEach(h=>{let c=rs(h),u=a.dataFields?.find(f=>f.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let l=`${c.field}_${v4()}`;s.push(Q("{",i)),s.push(Q(`$${t} has ${u.dbPath} $${l}_1;`,i+1)),s.push(Q("not {",i+1)),s.push(Q(`$${t} has ${u.dbPath} $${l}_2;`,i+2)),s.push(Q(`$${l}_2 < $${l}_1;`,i+2)),s.push(Q("};",i+1)),s.push(Q(`?${l}_ = $${l}_1;`,i+1)),s.push(Q("} or {",i)),s.push(Q(`not { $${t} has ${u.dbPath} $${l}_1; };`,i+1)),s.push(Q(`?${l}_ = "~";`,i+1)),s.push(Q("};",i)),s.push(Q(`?${l} = ?${l}_;`,i));let p=c.desc?"desc":"asc";d.push(`?${l} ${p}`);}),s.length!==0)return {match:s.join(""),sort:Q(`sort ${d.join(", ")};`,i)}};var xn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:o,rawTqlRes:i}=e;if(t){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((a,s)=>{let d=r[s],h=t[s];return is(a,d,h,n,o)})},is=(e,t,r,n,o)=>e.length===0?null:r.$filterByUnique?Nn(e[0],t,n,o):e.map(i=>Nn(i,t,n,o)),Nn=(e,t,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:a,roleFields:s,schemaValue:d}=Zt(e,r),h=er(o,i,n),c=rr(a,r,n),u=tr(s,r,n),l=t?.$fields?.every(f=>!i?.idFields?.includes(typeof f=="string"?f:f.$path));return {...c,...u,...d,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?h.id:t.$id}:{},...l?Object.fromEntries(Object.entries(h).filter(([f])=>!i?.idFields?.includes(f))):h}},Zt=(e,t)=>{let r=Object.keys(e),n=r.find(p=>p.endsWith(".$dataFields")),o=r.filter(p=>p.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");o?.length>0&&o.forEach(p=>{let f=p.replace(/\.\$multiVal$/,""),$=e[p][0][f].attribute;e[n][f]=$;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let s=i.type,d={$thing:s.label,$thingType:s.root,[ee]:e.queryPath.value},h={[`$${d.$thingType}`]:d.$thing},c=j(t,h),u=r.filter(p=>{let f=$e(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===f)}).map(p=>{let f=$e(p.split(".").pop()),$=$e(c.linkFields?.find(E=>E.path===f));return {$linkFields:e[p],$key:f,$metaData:p.split(".")[p.split(".").length-2],$cardinality:$.cardinality}}),l=r.filter(p=>{let f=p.split(".").pop();return f&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[f]}).map(p=>{let f=$e(p.split(".").pop());return {$roleFields:e[p],$key:f,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[f].cardinality}});return {dataFields:i,schemaValue:d,currentSchema:c,linkFields:u,roleFields:l}},er=(e,t,r)=>{let{$metaData:n}=e,{as:o}=os(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).map(([a,s])=>{let d=t.dataFields?.find(l=>l.path===a||l.dbPath===a),h=a==="id",c=Array.isArray(o)?o.find(l=>l[a])?.[a]:a,u;if(d?.cardinality==="ONE"){if(u=s[0]?s[0].value:r.query?.returnNulls?null:void 0,d.contentType==="DATE"||d.contentType==="FLEX"&&s[0].type.value_type==="datetime"?u=u&&`${u}Z`:d.contentType==="JSON"&&(u=u&&JSON.parse(u)),h)return [[c,u],["$id",u]].filter(([l,p])=>p!==void 0)}else if(d?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];d.contentType==="DATE"?u=s.map(l=>`${l.value}Z`):d.contentType==="FLEX"?u=s.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):d.contentType==="JSON"?u=s.map(l=>l.value&&JSON.parse(l.value)):u=s.map(l=>l.value);}return [[c,u]].filter(([l,p])=>p!==void 0)}).flat();return Object.fromEntries([...i])},tr=(e,t,r)=>{let n={};return e.forEach(o=>{let{$roleFields:i,$metaData:a,$cardinality:s}=o,{as:d,justId:h,idNotIncluded:c,filterByUnique:u}=jn(a);if(d===null)return;let l=i.map(p=>{let{dataFields:f,currentSchema:$,linkFields:E,roleFields:g,schemaValue:y}=Zt(p,t),F=er(f,$,r);if(h==="T")return F.id;{let m=rr(E,t,r),S=tr(g,t,r),M={...F};return c==="true"&&$?.idFields?.forEach(R=>delete M[R]),{...M,...m,...S,...y}}});l.length>0?n[d]=s==="MANY"&&u==="false"?l:l[0]:r.query?.returnNulls&&(n[d]=null);}),n},rr=(e,t,r)=>{let n={};return e.forEach(o=>{let{$linkFields:i,$metaData:a,$cardinality:s}=o,{as:d,justId:h,idNotIncluded:c,filterByUnique:u}=jn(a);if(d===null)return;let l=i.map(p=>{let{dataFields:f,currentSchema:$,linkFields:E,roleFields:g,schemaValue:y}=Zt(p,t),F=er(f,$,r);if(h==="T")return F.id;{let m=rr(E,t,r),S=tr(g,t,r),M={...F};return c==="true"&&$.idFields?.forEach(R=>delete M[R]),{...M,...m,...S,...y}}});n[d]=l.length>0?s==="MANY"&&u==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},jn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),s=e.match(n),d=e.match(o);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:d?d[1]:null}},os=e=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,s,d)=>/^{.*}$/.test(d)?`:${d}`:`:${s}"${d}"`),i=i.replace(/\[([^\]]+)\]/g,(a,s)=>`[${s.split(",").map(d=>d.trim().startsWith("{")&&d.trim().endsWith("}")?d.trim():`"${d.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var mt=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!o)throw new Error("Client not found");n=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:n});}return {client:o,session:n}};var _n=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,o=new TypeDBOptions;o.infer=!0;let{session:i}=await mt(r,n),a=await i.transaction(TransactionType.READ,o),[s,d]=await tryit(parallel)(t.length,t,async h=>await a.query.fetch(h).collect());if(s){await a.rollback();let h=s;throw new Error(`Error running TQL query: ${h.errors}`)}return await a.close(),d};var us=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,hs=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,ps=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,nr=U("error","error",_((e,t)=>({...e,error:t.error}))),fs=Ee("build",{build:H(async e=>Pn({queries:e.bql.queries,schema:e.schema}),U("done","run",_(hs)),nr),run:H(async e=>_n({dbHandles:e.handles,tqlRequest:$e(e.tql.queries),config:e.config}),U("done","parse",_(ps)),nr),parse:H(async e=>xn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:$e(e.tql.res)}),U("done","success",_(us)),nr),success:ue(),error:ue()},e=>e),$s=async e=>new Promise((t,r)=>{ye(fs,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Un=async(e,t,r,n,o)=>$s({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:o,error:null});var ms=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,ir=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,yt=U("error","error",_((e,t)=>({...e,error:t.error}))),ys=Ee("enrich",{enrich:H(async e=>(ae(`originalBQLQuery[${se}]`,JSON.stringify(e.bql.raw)),Xr(e.bql.raw,e.schema)),U("done","adapter",_(ms)),yt),adapter:H(async e=>{let t={};e.bql.queries?.forEach((s,d)=>{let h=e.bql.raw[d],c=Y(e.schema,s.$thing),{id:u}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[u]){let p=e.handles.typeDB?.get(u)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[u]){let p=e.handles.surrealDB?.get(u)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let l=t[u];l.rawBql.push(h),l.bqlQueries.push(s),l.indices.push(d);});let r=Object.values(t),n=r.map(s=>{if(s.db==="typeDB")return Un(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return An(s.bqlQueries,e.schema,e.config,s.client);throw new Error(`Unsupported DB "${JSON.stringify(s,null,2)}"`)}),o=await Promise.all(n),i=r.flatMap((s,d)=>{let h=o[d];return s.indices.map((c,u)=>({index:c,result:h[u]}))});return i.sort((s,d)=>s.index<d.index?-1:s.index>d.index?1:0),i.map(({result:s})=>s)},U("done","postHooks",_(ir)),yt),postHooks:H(async e=>bn(e.schema,$e(e.bql.queries),$e(e.bql.res)),U("done","clean",_(ir)),yt),clean:H(async e=>Fn(e.config,$e(e.bql.res)),U("done","success",_(ir)),yt),success:ue(),error:ue()},e=>e),gs=async e=>new Promise((t,r)=>{ye(ys,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ve=async(e,t,r,n)=>gs({bql:{raw:e},schema:t,config:r,handles:n,error:null});var or="___",Bs=Symbol.for("grandChildOfCreate"),Vn=async(e,t,r,n)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],i=(L,b)=>Object.keys(L).filter(B=>!B.startsWith("$")&&!o.includes(B)&&L[B]!==void 0?b?!j(t,L).dataFields?.find(w=>w.path===B):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let a=[];if(traverse(e,({parent:L,key:b,value:B})=>{L&&b&&!b.includes("$")&&!o.includes(b)&&isObject(L)?(Array.isArray(L[b])?L[b]:[L[b]]).forEach(w=>{if(isObject(w)){if(L.$op!=="create")a.includes(w.$op)||a.push(w.$op);else if(w.$op==="delete"||w.$op==="unlink")throw new Error(`Cannot ${w.$op} under a create`)}}):!L&&isObject(B)&&(a.includes(B.$op)||a.push(B.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let d=(L=>{let b=(B,T)=>{let w=[],C={},P=["$op","$bzId","$parentKey"],q=["$relation","$entity","$id",...P];for(let O in B)if(!P.includes(O)&&!(q.includes(O)&&!T))if(!O.includes("$")&&(isObject(B[O])||Array.isArray(B[O]))){let v=Fs(B[O]);if(Array.isArray(v)&&v.length>0)v.forEach(we=>{let Fe={$path:O,...b(we),...we.$filter&&{$as:we.$bzId}};w.find(X=>X.$path===Fe.$path&&!X.$filter)||(w=[...w,Fe]);});else {let we={$path:O,...b(v),...!v.$filter&&{$as:v.$bzId}};w=[...w,we];}}else C[O]=B[O];return {...C,$fields:w}};return L.map(B=>b(B,!0))})(Array.isArray(e)?e:[e]),c=(await ve(d,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,u=(L,b)=>{let B=L.$id||L.id||L.$bzId;if(L.$objectPath){let{$objectPath:T}=L,w=T?.beforePath||"root",C=Array.isArray(T.ids)?`[${T.ids}]`:T.ids;return {beforePath:`${w}.${C}___${T.key}`,ids:B,key:b}}else return {beforePath:"root",ids:B,key:b}},l=(L,b)=>{let B=L?.beforePath||"root";if(typeof B!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let T=(Array.isArray(L?.ids)?`[${L?.ids}]`:L?.ids);return `${B}.${T}___${L?.key}`},p=L=>{if(L.includes("[")&&L.includes("]")){let[b,B,T]=L.split(/[[\]]/);return B.split(",").map(C=>`${b}${C}${T}`)}else return [L]},f={};(L=>produce(L,b=>traverse(b,({key:B,parent:T})=>{if(T&&B&&T.$id&&!B.includes("$")){let w=u(T,B),C=l(w);if(Array.isArray(T[B])){let P=[];T[B].forEach(q=>{isObject(q)?(q.$objectPath=w,P.push(q.$id.toString())):q&&P.push(q.toString());}),f[C]={$objectPath:w,$ids:P};}else {let P=T[B];isObject(P)?(f[C]={$objectPath:w,$ids:[P.$id.toString()]},P.$objectPath=w):P?f[C]={$objectPath:w,$ids:[P.toString()]}:P===null&&(f[C]=null);}}})))(c||{});let E=L=>produce(L,b=>traverse(b,({key:B,value:T,parent:w})=>{w&&B&&!B.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(w)&&(Array.isArray(w[B])?w[B].forEach(C=>{typeof C!="string"&&(C.$objectPath=u(w,B),C.$parentIsCreate=w.$op==="create",C[Bs]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[B])&&(w[B].$parentIsCreate=w.$op==="create",w[B][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[B].$objectPath=u(w,B)));})),g=E(e),y=L=>{let b=[];return L.forEach(T=>{if(!T.$id&&!T.id&&!T.$tempId)if(T.$filter){let w=l({...T.$objectPath,key:T.$bzId}),C=f[w];C&&(Array.isArray(C.$ids)?C.$ids:[C.$ids]).forEach(q=>{let O={...T,$id:q,$bzId:`T4_${v4()}`,$filterBzId:T.$bzId};b.push(O);});}else {let w=l(T.$objectPath),C=f[w];C?C?.$ids?.forEach(P=>{let q={...T,$id:P,$bzId:`T4_${v4()}`};b.push(q);}):b.push(T);}else b.push(T);}),b.map(T=>{let w={...T};return i(w,!0).forEach(C=>{let P=Array.isArray(w[C])?w[C]:[w[C]],q=y(P);w[C]=q;}),w})},F=y(Array.isArray(g)?g:[g]),m=E(F),M=(L=>{let b=B=>{let T=X=>{let Z=[],K=[],N=[];return X.forEach(V=>{let le=i(V,!0);if(le.length>0){let k=!1;le.forEach(W=>{(Array.isArray(V[W])?V[W]:[V[W]]).filter(ne=>!ne.$id&&!ne.id&&typeof V=="object").length&&(k=!0);}),k?Z.push(V):K.push(V);}else V.$id?N.push({...V,$bzId:V.$tempId||V.$bzId}):N.push({...V,$bzId:V.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:Z,operationWithoutMultiples:K,otherOps:N}},{operationWithMultiples:w,operationWithoutMultiples:C,otherOps:P}=T(B),q=X=>{let K=(()=>{let W={};for(let he in X){let G=j(t,X);!he.startsWith("$")&&G.dataFields?.find(ne=>ne.path===he)&&(W[he]=X[he]);}return W})(),N=Object.keys(X),V=i(X,!0),le=[],k=(W,he)=>{if(W===V.length){let ne={...he};N.forEach(pe=>{pe.startsWith("$")&&(ne[pe]=X[pe]);}),le.push({...ne,...K});return}let G={...he,[V[W]]:X[V[W]],...De(he),...K};k(W+1,G),k(W+1,he);};return k(0,{...De(X)}),le},O=[];return w.forEach(X=>{let Z=q(X),K=[];Z.forEach(N=>{let V=i(N,!0);if(N.$op==="create")K.push(N);else if(N.$id){let le=l(N.$objectPath),k=[];if(V.forEach(W=>{let he=`${le.includes("undefined")?"root":le}.${N.$id}${or}${W}`,G=f[he];N[W].filter(pe=>pe.$op==="unlink"||pe.$op==="delete"||pe.$op==="update").length>0?G?.$ids&&k.push({key:W,ids:G.$ids}):k.push({key:W,ids:[""]});}),k.length===V.length&&!K.find(W=>W.$id===N.$id))K.push(N);else {let W={...N,$bzId:N.$tempId||`T4_${v4()}`};V.forEach(G=>{let ne=N[G].filter(pe=>pe.$id);ne.length>0?W[G]=ne:W[G]=void 0;}),i(W,!0).length>0&&K.push(W);}}else if(N.$objectPath){let le=l(N.$objectPath),k=f[le]?.$ids||[];k.forEach(W=>{let he=[];V.forEach(G=>{let ne=`${le}.${W}${or}${G}`,pe=f[ne];pe&&he.push({key:G,ids:pe.$ids});}),V.length===0?k.filter(ne=>!K.find(pe=>pe.$id===ne)).forEach(ne=>{K.push({...N,$id:ne,$bzId:N.$tempId||`PQT2_${v4()}`});}):he.length===V.length&&!K.find(G=>G.$id===W)&&(V.forEach(G=>{let ne=`${l(N.$objectPath)}.${W}${or}${G}`,pe=f[ne]?.$ids||[],yi=N[G].find(xe=>!xe.$id),pr=[...pe.map(xe=>({...yi,$id:xe,$objectPath:{beforePath:N.$objectPath.beforePath,ids:xe,key:G}})),...N[G].filter(xe=>xe.$id)];pr.length>0&&(N[G]=pr);}),K.push({...N,$id:W,$bzId:N.$tempId||`PQ3_${v4()}`}));});}else K.push(N);}),K.forEach(N=>{O.push(N);});}),[...O,...C,...P].filter(X=>i(X).length>0?!0:X.$op!=="update").map(X=>{let Z={...X};return i(Z,!0).forEach(K=>{let N=Array.isArray(Z[K])?Z[K]:[Z[K]],V=b(N);Z[K]=V;}),Z})};return b(L)})(Array.isArray(m)?m:[m]),R=L=>L.map(b=>{let B=i(b,!0),T={...b};return B.forEach(w=>{let C=Array.isArray(b[w])?b[w]:[b[w]],P=[],q=[],O=[],v={},we=Rt(t,b,w);C.filter(k=>k).forEach(k=>{k.$op==="replace"&&k.$id?(v=k,Array.isArray(k.$id)?q=[...q,...k.$id]:q.push(k.$id)):k.$op==="create"&&we==="ONE"&&k.id?(v=k,Array.isArray(k.id)?O=[...q,...k.id]:O.push(k.id)):P.push(k);});let Fe=l(v.$objectPath),Z=p(Fe).map(k=>f[k]),K=[];Z.filter(k=>k!=null).forEach(k=>{K=[...K,...k?.$ids||[]];});let N=K.filter(k=>!q.includes(k)),V=q.filter(k=>!K.includes(k)),le=De(v);N.length>0&&P.push({...v,$op:"unlink",$id:N,$bzId:v.$tempId||`T4_${v4()}`,id:void 0,...le}),V.length>0&&V.forEach(k=>{P.push({...v,$op:"link",$id:k,$bzId:v.$tempId||`T5_${v4()}`,...le});}),O.length>0&&O.forEach(k=>{P.push({...v,$op:"create",id:k,$bzId:v.$tempId||`T6_${v4()}`,...le});}),T[w]=R(P);}),T}),I=E(R(E(M)));(L=>produce(L,b=>traverse(b,B=>{let{key:T,value:w,parent:C,meta:P}=B;T&&C&&!T?.includes("$")&&T!=="$filter"&&!P.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(C)&&(Array.isArray(w)?w:[w]).forEach(O=>{let v=O.$filter?{...O.$objectPath,key:O.$filterBzId}:O.$objectPath,we=l(v),Fe=f[we],X=(N,V)=>N.every(le=>V.includes(le)),Z=O.$id?Array.isArray(O.$id)?X(O.$id,Fe&&Fe.$ids?Fe.$ids:[]):Fe?.$ids?.includes(O.$id):Fe,K=Rt(t,C,O.$objectPath.key);if(O.$op==="link"&&Z&&K==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${l(O.$objectPath)}" because it is already occupied.`);if(O.$op)switch(O.$op){case"delete":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${O.$id}" because it is not linked to $id:"${C.$id}"`);break;case"update":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${O.$id}" because it is not linked to $id:"${C.$id}"`);break;case"unlink":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${O.$id}" because it is not linked to $id:"${C.$id}"`);break;case"link":if(Z)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${O.$id}" because it is already linked to $id:"${C.$id}"`);break;}});})))(I);let re=(L=>produce(L,b=>traverse(b,B=>{let{value:T,meta:w}=B;isObject(T)&&(T[Symbol.for("path")]=w.nodePath,delete T.$objectPath,delete T.$parentIsCreate);})))(I);return [...Array.isArray(re)?re:[re]].sort((L,b)=>L.$op==="create"&&b.$op!=="create"?-1:L.$op!=="create"&&b.$op==="create"?1:0)},Fs=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Wn=(e,t)=>produce(e,n=>Et(t,n)),Et=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>Et(e,o,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||o.startsWith("%")||ws(e,t,o,n);});},ws=(e,t,r,n)=>{let o=t[r];if(!o)return;let i=n.dataFields?.find(d=>d.path===r);if(i){i.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let a=n.linkFields?.find(d=>d.path===r);if(a){let d=a.oppositeLinkFieldsPlayedBy[0]?.thing;Et(e,o,d);return}if(!n.refFields[r]&&n.thingType==="relation"){let d=n.roles[r];if(!d)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[h]=d.playedBy||[];if(!h)throw new Error(`Role ${d.path} in ${n} is not played by anything`);Et(e,o,h.thing);}};var Kn=async(e,t,r,n)=>{let o=Array.isArray(e)?e:[e],i=o.map(d=>sr(d,!0)),s=(await ve(i,t,r,n)).bql.res;return o.map((d,h)=>{let c=Y(t,d.$thing);return Yn({mut:d,node:s[h],schema:t,thing:c})})},Jn=new Set(["$op","$bzId","$parentKey"]),Ms=new Set(["$relation","$entity","$id",...Jn]),sr=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let n={};for(let o in e){if(Jn.has(o)||Ms.has(o)&&!t)continue;let i=e[o];o.startsWith("$")?n[o]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[o]={$path:o,...sr(i[0],!1)}):isObject(i)&&(r[o]={$path:o,...sr(i,!1)});}return n.$fields=Object.values(r),n},Yn=e=>{let{mut:t,node:r,schema:n,thing:o}=e,i=Gn(o),a=Ls(r);if(Array.isArray(t))return t.map(d=>{let h=a[d.$id];return h?zn({mut:d,node:h,schema:n,thing:o,...i}):d});let s=a[t.$id];return zn({mut:t,node:s,schema:n,thing:o,...i})},zn=e=>{let{mut:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,{$fields:d,...h}=t;if(!r)return h;let c=Xn({$fields:t.$fields,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}),u={...h,[_e]:c};for(let l in t){if(l.startsWith("$"))continue;let p=t[l];if(i[l]||!p||typeof p!="object"){u[l]=p;continue}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${l}"`);let E=Y(n,$);u[l]=Yn({mut:p,schema:n,node:r[l],thing:E});}return u},Xn=e=>{let{$fields:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,d=t||Ss(o),h={$id:r.$id};return d.forEach(c=>{let u=typeof c!="string",l=u?c.$path:c,p=r[l];if(i[l]){h[l]=p;return}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${l}"`);if(!u){p&&(h[l]=Array.isArray(p)?p.map(Hn):Hn(p));return}let E=Y(n,$),g=Gn(E);h[l]=Array.isArray(p)?p.map(y=>vn({...g,$fields:c.$fields,value:y,schema:n,thing:E})):vn({...g,$fields:c.$fields,value:p,schema:n,thing:E});}),h},Ss=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},Hn=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},vn=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 Xn({...e,node:t})},Gn=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},Ls=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 ar=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 ei=async(e,t,r)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!r)throw new Error("No schema provided");let n=l=>{let p=l.$op,f=`$${l.$bzId}`,$=j(r,l),{idFields:E,defaultDBConnector:g}=$,y=g?.path||l.$thing,F=l.$id,m=E?.[0],S=listify(l,(A,D)=>{if(A.startsWith("$")||A.startsWith("%")||A===m||D===void 0||D===null)return "";let L=$.dataFields?.find(T=>T.path===A);if(!L?.path)return "";let B=L.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(L.contentType))return `has ${B} '${D}'`;if(["NUMBER","BOOLEAN"].includes(L.contentType))return `has ${B} ${D}`;if(L.contentType==="DATE"){if(Number.isNaN(D.valueOf()))throw new Error("Invalid format, Nan Date");return D instanceof Date?`has ${B} ${D.toISOString().replace("Z","")}`:`has ${B} ${new Date(D).toISOString().replace("Z","")}`}if(L.contentType==="FLEX"){let T=`bza${Ie()}`,w=isArray(D)?D.map(C=>ar(C)):ar(D);if(Array.isArray(w))throw new Error("Array in FLEX fields not supported yet");return `has ${B} $${T}; $${T} '${T}' isa ${B}, has ${w.type}Attribute ${w.value}`}throw new Error(`Unsupported contentType ${L.contentType}`)}).filter(A=>A),M=`${f}-atts`,R=listify(l,A=>{if(A.startsWith("$")||A.startsWith("%")||A===m)return "";let D=$.dataFields?.find(B=>B.path===A);if(!D?.path)return "";let b=D.dbPath;return `{${M} isa ${b};}`}).filter(A=>A),I=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,x=F?[`has ${m} ${I}`]:[],J=[...x,...S].filter(A=>A).join(","),re=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${f} isa ${[y,...x].filter(A=>A).join(",")};`;if(p==="update"){if(!R.length)throw new Error("update without attributes");return `${f} isa ${[y,...x].filter(A=>A).join(",")}, has ${M};
124
+ ${R.join(" or ")};`}return ""},fe=()=>p==="update"||p==="link"||p==="match"?`${f} isa ${[y,...x].filter(A=>A).join(",")};`:"";if(lt(l))return {op:p,deletionMatch:re(),insertionMatch:fe(),insertion:p==="create"?`${f} isa ${[y,J].filter(A=>A).join(",")};`:p==="update"&&S.length?`${f} ${S.join(",")};`:"",deletion:p==="delete"?`${f} isa ${y};`:p==="update"&&R.length?`${f} has ${M};`:""};throw new Error("in attributes")},o=l=>{let p=l.$op,f=j(r,l),$=`$${l.$bzId}`,E=l.$id,g=f.defaultDBConnector?.path||l.$thing,y="roles"in f?listify(f.roles,D=>D):[],F="roles"in f?mapEntries(f.roles,(D,L)=>[D,L.dbConnector?.path||D]):{},m=listify(l,(D,L)=>{if(!y.includes(D))return null;if(!("roles"in f))throw new Error("This should have roles! ");let b=F[D];return Array.isArray(L)?L.map(B=>({path:b,id:B})):{path:b,id:L}}).filter(D=>D).flat(),S=m.map(D=>{if(!D?.path)throw new Error("Object without path");return `${D.path}: $${D.id}`}),M=m.length>0?`( ${S.join(" , ")} )`:"",R=l[qe];if(!R)throw new Error("[internal error] Symbol edgeType not defined");let I=M?`${$} ${M} ${R==="linkField"||p==="delete"||p==="unlink"?`isa ${g}`:""}`:"",x=`${$} ${R==="linkField"||p==="delete"?`isa ${g}`:""}`,J=()=>I?p==="link"?`${I};`:p==="create"?`${I}, has id '${E}';`:"":"",re=()=>I&&p==="match"?`${I};`:"",fe=()=>I?p==="delete"?`${I};`:p==="match"?`${I};`:"":"",A=()=>I?p==="delete"?`${x};`:p==="unlink"?`${$} ${M};`:"":"";return {deletionMatch:fe(),insertionMatch:re(),deletion:A(),insertion:J(),op:""}},i=(l,p)=>{let f=p==="edges"?o:n;if(Array.isArray(l))return l.map(m=>{let{preDeletionBatch:S,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x}=f(m);return shake({preDeletionBatch:S,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x},J=>!J)}).filter(m=>m);let{preDeletionBatch:$,insertionMatch:E,deletionMatch:g,insertion:y,deletion:F}=f(l);return shake({preDeletionBatch:$,insertionMatch:E,deletionMatch:g,insertion:y,deletion:F},m=>!m)},a=i(e),s=Array.isArray(a)?a:[a],d=i(t,"edges"),h=Array.isArray(d)?d:[d],c=[...s,...h];return shake({insertionMatches:c.map(l=>l.insertionMatch).join(" ").trim(),deletionMatches:c.map(l=>l.deletionMatch).join(" ").trim(),insertions:c.map(l=>l.insertion).join(" ").trim(),deletions:c.map(l=>l.deletion).join(" ").trim()},l=>!l)};var ti=async(e,t,r,n,o)=>{let i=[...t,...r],a=i.map(s=>{let d=e.insertions?.find(u=>u.get(`${s.$bzId}`))?.get(`${s.$bzId}`),h=s.$thing||s.$relation||s.$entity,c=h?Y(n,h):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!d&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let u=d?.asThing().iid,l=Object.entries(s).filter(([f,$])=>!f.startsWith("$")).reduce((f,[$,E])=>{if(c?.dataFields?.find(y=>y.path===$)?.contentType==="JSON")return f[$]=JSON.parse(E),f;if(s.$thingType==="relation"){let y=i.filter(F=>F.$id&&F.$bzId===E);return y.length===1?(f[$]=y[0].$id,f):(f[$]=E,f)}return f[$]=E,f},{});if(o.mutation?.noMetadata)return l;let p=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:u,...s,...l,[s.path]:s.$id,...p}}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(a)};var ri=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:n}=await mt(t,r),o=await n.transaction(TransactionType.WRITE),i=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{i&&await o.query.delete(i);let s=a&&o.query.insert(a),d=s?await s.collect():void 0;return await o.commit(),{insertions:d}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var Cs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Os=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),As=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),cr=U("error","error",_((e,t)=>({...e,error:t.error}))),ks=Ee("buildMutation",{buildMutation:H(async e=>ei(e.bql.things,e.bql.edges,e.schema),U("done","runMutation",_(Os)),cr),runMutation:H(async e=>ri(e.tql.mutation,e.handles,e.config),U("done","parseMutation",_(As)),cr),parseMutation:H(async e=>ti(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),U("done","success",_(Cs)),cr),success:ue(),error:ue()},e=>e),qs=async e=>new Promise((t,r)=>{ye(ks,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ni=async(e,t,r,n,o,i,a)=>qs({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:o,config:i,handles:a,error:null});var ii=async(e,t)=>{let r=s=>{let{$filter:d,$thing:h,$bzId:c,$op:u,$id:l,$tempId:p}=s,f=Y(t,h),{usedDataFields:$}=de(f,s),{idFields:E}=f,g=l||s[E[0]],y=(isArray(h)?h:[h]).map(te),F=ce(s,b=>b.startsWith("$")),m=ce(s,b=>!b.startsWith("$")),S=JSON.stringify(m),M=Object.entries(F).map(([b,B])=>b=="$tempId"?`'$tempId': '_:${B}'`:`'${b}': '${B}'`).join(","),R=s[ot],I=$.filter(b=>!E.includes(b)).map(b=>{let B=f.dataFields?.find(w=>w.path===b||w.dbPath===b);if(!B)throw new Error(`Data field schema not found for ${b}`);let T=s[b];return T===null?`${b} = NONE`:`${b} = ${je(T,B.contentType)}`}).filter(Boolean),x=`$\u27E8${p||c}\u27E9`,J=R?.bzId?`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:g?isArray(g)?y.flatMap(b=>g.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${g}\u27E9`).join(", "):!0,re=(()=>{if(R?.bzId){let b=`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return g?isArray(g)?`${b}[? $this.id() IN [${g.map(B=>`'${B}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${g}'] ]`:b}else return g?isArray(g)?y.flatMap(b=>g.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${g}\u27E9`).join(", "):y.join(", ")})(),fe=d?`WHERE ${me(Be(d,h,t))}`:"",A=I.length>0?`SET ${I.join(", ")}`:"",D=`VALUE (CREATE ONLY Delta SET input = ${S}, meta = {${M}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,L="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(s.$op==="match")return p?"":`LET ${x} = (SELECT VALUE id FROM ${re} ${fe});`;if(s.$op==="create"){if(isArray(g))throw new Error("Cannot create multiple things at once");let b=te(h);return `LET ${x} = (CREATE ONLY ${b}:\u27E8${g}\u27E9 ${A} RETURN ${D});`}if(s.$op==="update")return `LET ${x} = IF (${J}) THEN (UPDATE ${re} ${A} ${fe} RETURN ${D}) END;`;if(s.$op==="delete")return `LET ${x} = IF (${J}) THEN (DELETE ${re} ${fe} RETURN ${L}) END;`;throw new Error(`Unsupported operation ${s.$op}`)},n=s=>{let{$thing:d,$bzId:h,$op:c,$tempId:u}=s,l=Y(t,d),{usedRoleFields:p}=de(l,s),f=`$\u27E8${u||h}\u27E9`,$="roles"in l?p.flatMap(y=>{let F=l.roles[y];if(!F)throw new Error(`Role field schema not found for ${y}`);let{cardinality:m}=F,S=isArray(s[y])?s[y].map(M=>`$\u27E8${M}\u27E9`):[`$\u27E8${s[y]}\u27E9`];if(m==="ONE"){if(S.length>1){let M=`array::filter(array::flatten([${S}]), |$v| !!$v)`;switch(c){case"link":case"replace":return `${y} = ((array::len(${M})==1) && ${M}[0]) || ${M}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case"link":case"replace":return `${y} = ((type::is::array(${S[0]}) && array::len(${S[0]})==1) && ${S[0]}[0]) || ${S[0]}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}else if(m==="MANY"){let M=`array::flatten([${S}])`;switch(c){case"link":return `${y} += ${M}`;case"unlink":return `${y} -= ${M}`;case"replace":return `${y} = ${M}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${m}`)}):[],E=$.length>0?`${$.join(", ")}`:"",g=E?`SET ${E}`:"";return `IF ${f} THEN (UPDATE ${f} ${g} RETURN VALUE id) END; ${f};`},o=s=>{let{$thing:d,$op:h}=s,c=Y(t,d),u=te(d),{usedRoleFields:l}=de(c,s);if(!["create","delete"].includes(h))throw new Error("Arcs can only be created or deleted");let[p,f]=l,$=isArray(s[p])?s[p]:[s[p]],E=isArray(s[f])?s[f]:[s[f]];if(h==="create"){if(l.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let g=ce(s,x=>!x.startsWith("$")),F=`(CREATE ONLY Delta SET input = ${JSON.stringify(g)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,S=c.roles[p].cardinality==="MANY",R=c.roles[f].cardinality==="MANY";return [`
125
125
  ${S?"":`IF array::len(array::filter(array::flatten([$\u27E8${$}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${p} is cardinality one and can link a single thing." + <string>$\u27E8${$}\u27E9; };`}
126
126
  ${R?"":`IF array::len(array::filter(array::flatten([$\u27E8${E}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${f} is cardinality one and can link a single thing." + <string>$\u27E8${E}\u27E9; };`}
127
127
  FOR $node1 IN array::flatten([$\u27E8${$}\u27E9]) {
@@ -135,7 +135,7 @@ limit ${h};`),u.join(`
135
135
  }
136
136
  }
137
137
  }
138
- }`]}if(h==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${p}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${f}) CONTAINSANY $\u27E8${E}\u27E9 RETURN BEFORE`},i=o=>{let{$thing:d,$bzId:h,$op:c,$tempId:u}=o,l=Y(t,d),{usedRefFields:p}=de(l,o),f=`$\u27E8${u||h}\u27E9`,$=p.flatMap(y=>{let F=l.refFields[y];if(!F)throw new Error(`ReferenceField schema not found for ${y}`);let{cardinality:m,contentType:S}=F;if(S==="REF"){let M=isArray(o[y])?o[y]:[`${o[y]}`];if(m==="ONE"){if(M.length>1){let R=`array::filter(array::flatten([${M}]), |$v| !!$v)`;switch(c){case"link":case"replace":return `${y} = ((array::len(${R})==1) && ${R}[0]) || ${R}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case"link":case"replace":return `${y} = ((type::is::array(${M[0]}) && array::len(${M[0]})==1) && ${M[0]}[0]) || ${M[0]}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}else if(m==="MANY"){let R=`array::flatten([${M}])`;switch(c){case"link":return `${y} += ${R}`;case"unlink":return `${y} -= ${R}`;case"replace":return `${y} = ${R}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${m}`)}if(S==="FLEX")return `${y} = ${m==="ONE"?`array::flatten([${o[y]}])[0]`:`array::flatten([${o[y]}])`}`}),E=$.length>0?`${$.join(", ")}`:"",g=E?`SET ${E}`:"";return `IF ${f} THEN (UPDATE ${f} ${g} RETURN VALUE id) END; ${f};`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(a),...e.references.map(i)]};var oi=async(e,t)=>{let r=`
138
+ }`]}if(h==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${p}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${f}) CONTAINSANY $\u27E8${E}\u27E9 RETURN BEFORE`},i=s=>{let{$thing:d,$bzId:h,$op:c,$tempId:u}=s,l=Y(t,d),{usedRefFields:p}=de(l,s),f=`$\u27E8${u||h}\u27E9`,$=p.flatMap(y=>{let F=l.refFields[y];if(!F)throw new Error(`ReferenceField schema not found for ${y}`);let{cardinality:m,contentType:S}=F;if(S==="REF"){let M=isArray(s[y])?s[y]:[`${s[y]}`];if(m==="ONE"){if(M.length>1){let R=`array::filter(array::flatten([${M}]), |$v| !!$v)`;switch(c){case"link":case"replace":return `${y} = ((array::len(${R})==1) && ${R}[0]) || ${R}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case"link":case"replace":return `${y} = ((type::is::array(${M[0]}) && array::len(${M[0]})==1) && ${M[0]}[0]) || ${M[0]}`;case"unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}else if(m==="MANY"){let R=`array::flatten([${M}])`;switch(c){case"link":return `${y} += ${R}`;case"unlink":return `${y} -= ${R}`;case"replace":return `${y} = ${R}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${m}`)}if(S==="FLEX")return `${y} = ${m==="ONE"?`array::flatten([${s[y]}])[0]`:`array::flatten([${s[y]}])`}`}),E=$.length>0?`${$.join(", ")}`:"",g=E?`SET ${E}`:"";return `IF ${f} THEN (UPDATE ${f} ${g} RETURN VALUE id) END; ${f};`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(o),...e.references.map(i)]};var oi=async(e,t)=>{let r=`
139
139
  BEGIN TRANSACTION;
140
140
  ${t.join(";")};
141
141
  LET $DELTAS = SELECT * FROM Delta;
@@ -145,12 +145,12 @@ limit ${h};`),u.join(`
145
145
  LET $LOGS = SELECT * FROM LOG;
146
146
  RETURN $LOGS;
147
147
  COMMIT TRANSACTION;
148
- `;ae(`>>> batchedMutation[${se}]`,JSON.stringify({batchedMutation:r}));try{return (await e.query(r)).filter(Boolean)}catch(n){let i=(await e.query_raw(r)).filter(s=>s.result!=="The query was not executed due to a failed transaction"&&s.result!=="There was an error when starting a new datastore transaction"&&s.status==="ERR");throw i.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(i)}`):n}};var ci=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(a=>{if(isArray(a))return a.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return ai(i,r)});if(!isObject(a)||!("meta"in a))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(a)}`);return ai(a,r)})},ai=(e,t)=>{let r=mapEntries(e.after||{},(i,s)=>[i,i==="id"?s.id:isArray(s)&&s.length===0?void 0:s]),n=ce(e.input||{},(i,s)=>s===null),a={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(a,i=>!i.startsWith("$")):a};var qs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ps=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},Ns=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},dr=U("error","error",_((e,t)=>({...e,error:t.error}))),xs=Ee("buildMutation",{buildMutation:H(async e=>(ae(`>>> surqlMachine/buildMutation[${se}]`,JSON.stringify(e.bql.flat)),ii(e.bql.flat,e.schema)),U("done","runMutation",_(Ps)),dr),runMutation:H(async e=>(ae(`>>> surqlMachine/runMutation[${se}]`,JSON.stringify(e.surql.mutations)),oi(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations)),U("done","parseMutation",_(Ns)),dr),parseMutation:H(async e=>(ae(`>>> surqlMachine/parseMutation[${se}]`,JSON.stringify(e.surql.res)),ci({res:e.surql.res,config:e.config,schema:e.schema})),U("done","success",_(qs)),dr),success:ue(),error:ue()},e=>e),js=async e=>new Promise((t,r)=>{ye(xs,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ui=async(e,t,r,n,a,i)=>js({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:a,handles:i,error:null});var hi=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(s,o)=>{if(!s?.$thing)return;let{$op:d,$bzId:h,$tempId:c}=s,u=t.relations[s.$thing]||t.entities[s.$thing];if(!u)throw new Error(`[Internal] No schema found for ${s.$thing}`);let l=o?.bzId?o:{bzId:"",edgeField:"root"},{usedDataFields:p,usedLinkFields:f,usedRoleFields:$,usedRefFields:E}=de(u,s);if(["create","update","delete","link","unlink","match","replace"].includes(d)){let y={...ce(s,F=>![...$,...f,...E].includes(F)),...d==="link"||d==="unlink"||d==="replace"||d==="update"&&p.length===0?{$op:"match"}:{},...d==="link"||d==="replace"?{}:{[st]:l}};r.things.push(y);}let g={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let y=ce(s,F=>isSymbol(F)||F.startsWith("$"));$.forEach(F=>{isArray(s[F])?s[F].forEach(S=>n(S,{bzId:h,edgeField:F,tempId:c})):n(s[F],{bzId:h,edgeField:F,tempId:c});let m=(isArray(s[F])?s[F]:[s[F]]).filter(Boolean);Object.entries(g).forEach(([S,M])=>{let R=m.filter(I=>M.includes(I.$op)).map(I=>I.$bzId);R.length>0&&r.edges.push({...y,[F]:R,$op:S});});});}f&&f.forEach(y=>{isArray(s[y])?s[y].forEach(S=>n(S,{bzId:h,edgeField:y,tempId:c})):n(s[y],{bzId:h,edgeField:y,tempId:c});let F=u.linkFields?.find(S=>S.path===y),m=isArray(s[y])?s[y]:[s[y]];F.target==="relation"&&Object.entries(g).forEach(([S,M])=>{m.filter(I=>M.includes(I.$op)).forEach(I=>{let x=ce(I,J=>isSymbol(J)||J.startsWith("$"));r.edges.push({...x,[F.plays]:h,$op:S});});}),F.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([M,R])=>{let I=m.filter(x=>R.includes(x.$op));I.length!==0&&I.forEach(x=>{let J={$thing:F.relation,$thingType:"relation",$bzId:`arc_${x.$bzId}`,[F.plays]:h,[F.oppositeLinkFieldsPlayedBy[0].plays]:x.$bzId,$op:M};r.arcs.push(J);});});}),E&&E.forEach(y=>{isArray(s[y])?s[y].forEach(M=>n(M,{bzId:h,edgeField:y,tempId:c})):n(s[y],{bzId:h,edgeField:y,tempId:c});let F=(isArray(s[y])?s[y]:[s[y]]).filter(M=>M!=null),m=ce(s,M=>isSymbol(M)||M.startsWith("$")),S=F.map(M=>M.$op?`$\u27E8${M.$bzId}\u27E9`:je(M,"FLEX"));S.length>0&&r.references.push({...m,[y]:S,$op:"replace"});});};(Array.isArray(e)?e:[e]).forEach(s=>n(s));let i=[...r.edges].sort((s,o)=>{let d=["unlink","link"];return d.indexOf(s.$op)-d.indexOf(o.$op)});return {...r,edges:i}};var pi=ue,Ye=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,_s=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Us=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Vs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ws=async e=>(ae(`>>> mutationMachine/enrich[${se}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?Pt(e.bql.enriched,e.schema,e.config):Pt(e.bql.raw,e.schema,e.config)),zs=async e=>(ae(`>>> mutationMachine/preQuery[${se}]`,JSON.stringify(e.bql.enriched)),Vn(e.bql.enriched,e.schema,e.config,e.handles)),Hs=async e=>(ae(`>>> mutationMachine/preQueryDependencies[${se}]`,JSON.stringify(e.bql.enriched)),Kn(e.bql.enriched,e.schema,e.config,e.handles)),vs=async e=>(ae(`>>> mutationMachine/parseBQL[${se}]`,JSON.stringify(e.bql.enriched)),on(e.bql.enriched,e.schema)),Ks=async e=>(ae(`>>> mutationMachine/flattenBQL[${se}]`,JSON.stringify(e.bql.enriched)),hi(e.bql.enriched,e.schema)),Js=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},Ys=e=>We(e.bql.enriched),Ne=U("error","error",_((e,t)=>({...e,error:t.error}))),Xs=Ee("stringify",{stringify:H(async e=>(ae(`>>> mutationMachine/stringify[${se}]`,JSON.stringify(e.bql.raw)),Wn(e.bql.raw,e.schema)),U("done","enrich",_(Ye)),Ne),enrich:H(Ws,U("done","preQuery",Nt(Js),_(Ye)),U("done","parseBQL",_(Ye)),Ne),preQuery:H(zs,U("done","preHookDependencies",Nt(Ys),_(Ye)),U("done","parseBQL",_(Ye)),Ne),preHookDependencies:H(Hs,U("done","enrich",_(Ye)),Ne),parseBQL:H(vs,U("done","flattenBQL",_(_s)),Ne),flattenBQL:H(Ks,U("done","adapter",_(Us)),Ne),adapter:H(async e=>{ae(`>>> mutationMachine/adapter[${se}]`,JSON.stringify({enriched:e.bql.enriched,flat:e.bql.flat}));let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return ni(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ui(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},U("done","success",_(Vs)),Ne),success:pi(),error:pi()},e=>e),Gs=async e=>new Promise((t,r)=>{ye(Xs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),fi=async(e,t,r,n)=>Gs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var Ft=class{url;username;password;namespace;database;constructor(t){this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database;}async run(t){let r=new Zs;try{return await r.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1}),await t(r)}finally{await r.close();}}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}};enableMapSet();var hr=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 n=>{if(n.provider==="surrealDB"){let a=new Ft({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});t.surrealDB.set(n.id,{client:a,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[a,i]=await tryit(TypeDB.coreDriver)(n.url);if(a){let s=`[BORM:${n.provider}:${n.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:s});}catch(s){let o=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let a=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,s]=await tryit(TypeDB.cloudDriver)(n.addresses,a);if(i){let o=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(o)}try{let o=await s.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:s,session:o});}catch(o){let d=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(d)}}}));let r=Rr(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()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await Fr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...wt.query,...this.config.query,...r}},a=Array.isArray(t),i=a?t:[t],[s,o]=await tryit(Ke)(i,this.schema,n,this.dbHandles);if(s){let h=new Error(s.error);throw h.stack=s.error.stack,h}let d=o.bql.res;return a?d:d[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...wt.mutation,...this.config.mutation,...r}},[a,i]=await tryit(fi)(t,this.schema,n,this.dbHandles);if(a){let o=new Error(a.error.message);throw o.stack=a.error.stack,o}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Ih=hr;//! TO-DO Rule: Everything that can be changed or defined by the user should use $ prefix, but the rest is metadata and should be packed in symbols, depending on their origin. extension inside the schema and schema or query inside the query. Probably no more categories are necessary
148
+ `;ae(`>>> batchedMutation[${se}]`,JSON.stringify({batchedMutation:r}));try{return (await e.query(r)).filter(Boolean)}catch(n){let i=(await e.query_raw(r)).filter(a=>a.result!=="The query was not executed due to a failed transaction"&&a.result!=="There was an error when starting a new datastore transaction"&&a.status==="ERR");throw i.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(i)}`):n}};var ci=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(o=>{if(isArray(o))return o.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return ai(i,r)});if(!isObject(o)||!("meta"in o))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(o)}`);return ai(o,r)})},ai=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=ce(e.input||{},(i,a)=>a===null),o={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(o,i=>!i.startsWith("$")):o};var Ns=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),xs=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},js=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},dr=U("error","error",_((e,t)=>({...e,error:t.error}))),_s=Ee("buildMutation",{buildMutation:H(async e=>(ae(`>>> surqlMachine/buildMutation[${se}]`,JSON.stringify(e.bql.flat)),ii(e.bql.flat,e.schema)),U("done","runMutation",_(xs)),dr),runMutation:H(async e=>(ae(`>>> surqlMachine/runMutation[${se}]`,JSON.stringify(e.surql.mutations)),oi(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations)),U("done","parseMutation",_(js)),dr),parseMutation:H(async e=>(ae(`>>> surqlMachine/parseMutation[${se}]`,JSON.stringify(e.surql.res)),ci({res:e.surql.res,config:e.config,schema:e.schema})),U("done","success",_(Ns)),dr),success:ue(),error:ue()},e=>e),Us=async e=>new Promise((t,r)=>{ye(_s,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ui=async(e,t,r,n,o,i)=>Us({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:o,handles:i,error:null});var hi=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(a,s)=>{if(!a?.$thing)return;let{$op:d,$bzId:h,$tempId:c}=a,u=t.relations[a.$thing]||t.entities[a.$thing];if(!u)throw new Error(`[Internal] No schema found for ${a.$thing}`);let l=s?.bzId?s:{bzId:"",edgeField:"root"},{usedDataFields:p,usedLinkFields:f,usedRoleFields:$,usedRefFields:E}=de(u,a);if(["create","update","delete","link","unlink","match","replace"].includes(d)){let y={...ce(a,F=>![...$,...f,...E].includes(F)),...d==="link"||d==="unlink"||d==="replace"||d==="update"&&p.length===0?{$op:"match"}:{},...d==="link"||d==="replace"?{}:{[ot]:l}};r.things.push(y);}let g={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let y=ce(a,F=>isSymbol(F)||F.startsWith("$"));$.forEach(F=>{isArray(a[F])?a[F].forEach(S=>n(S,{bzId:h,edgeField:F,tempId:c})):n(a[F],{bzId:h,edgeField:F,tempId:c});let m=(isArray(a[F])?a[F]:[a[F]]).filter(Boolean);Object.entries(g).forEach(([S,M])=>{let R=m.filter(I=>M.includes(I.$op)).map(I=>I.$bzId);R.length>0&&r.edges.push({...y,[F]:R,$op:S});});});}f&&f.forEach(y=>{isArray(a[y])?a[y].forEach(S=>n(S,{bzId:h,edgeField:y,tempId:c})):n(a[y],{bzId:h,edgeField:y,tempId:c});let F=u.linkFields?.find(S=>S.path===y),m=isArray(a[y])?a[y]:[a[y]];F.target==="relation"&&Object.entries(g).forEach(([S,M])=>{m.filter(I=>M.includes(I.$op)).forEach(I=>{let x=ce(I,J=>isSymbol(J)||J.startsWith("$"));r.edges.push({...x,[F.plays]:h,$op:S});});}),F.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([M,R])=>{let I=m.filter(x=>R.includes(x.$op));I.length!==0&&I.forEach(x=>{let J={$thing:F.relation,$thingType:"relation",$bzId:`arc_${x.$bzId}`,[F.plays]:h,[F.oppositeLinkFieldsPlayedBy[0].plays]:x.$bzId,$op:M};r.arcs.push(J);});});}),E&&E.forEach(y=>{isArray(a[y])?a[y].forEach(M=>n(M,{bzId:h,edgeField:y,tempId:c})):n(a[y],{bzId:h,edgeField:y,tempId:c});let F=(isArray(a[y])?a[y]:[a[y]]).filter(M=>M!=null),m=ce(a,M=>isSymbol(M)||M.startsWith("$")),S=F.map(M=>M.$op?`$\u27E8${M.$bzId}\u27E9`:je(M,"FLEX"));S.length>0&&r.references.push({...m,[y]:S,$op:"replace"});});};(Array.isArray(e)?e:[e]).forEach(a=>n(a));let i=[...r.edges].sort((a,s)=>{let d=["unlink","link"];return d.indexOf(a.$op)-d.indexOf(s.$op)});return {...r,edges:i}};var pi=ue,Je=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Vs=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Ws=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),zs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Hs=async e=>(ae(`>>> mutationMachine/enrich[${se}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?Pt(e.bql.enriched,e.schema,e.config):Pt(e.bql.raw,e.schema,e.config)),vs=async e=>(ae(`>>> mutationMachine/preQuery[${se}]`,JSON.stringify(e.bql.enriched)),Vn(e.bql.enriched,e.schema,e.config,e.handles)),Ks=async e=>(ae(`>>> mutationMachine/preQueryDependencies[${se}]`,JSON.stringify(e.bql.enriched)),Kn(e.bql.enriched,e.schema,e.config,e.handles)),Js=async e=>(ae(`>>> mutationMachine/parseBQL[${se}]`,JSON.stringify(e.bql.enriched)),on(e.bql.enriched,e.schema)),Ys=async e=>(ae(`>>> mutationMachine/flattenBQL[${se}]`,JSON.stringify(e.bql.enriched)),hi(e.bql.enriched,e.schema)),Xs=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},Gs=e=>Ve(e.bql.enriched),Ne=U("error","error",_((e,t)=>({...e,error:t.error}))),Zs=Ee("stringify",{stringify:H(async e=>(ae(`>>> mutationMachine/stringify[${se}]`,JSON.stringify(e.bql.raw)),Wn(e.bql.raw,e.schema)),U("done","enrich",_(Je)),Ne),enrich:H(Hs,U("done","preQuery",Nt(Xs),_(Je)),U("done","parseBQL",_(Je)),Ne),preQuery:H(vs,U("done","preHookDependencies",Nt(Gs),_(Je)),U("done","parseBQL",_(Je)),Ne),preHookDependencies:H(Ks,U("done","enrich",_(Je)),Ne),parseBQL:H(Js,U("done","flattenBQL",_(Vs)),Ne),flattenBQL:H(Ys,U("done","adapter",_(Ws)),Ne),adapter:H(async e=>{ae(`>>> mutationMachine/adapter[${se}]`,JSON.stringify({enriched:e.bql.enriched,flat:e.bql.flat}));let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return ni(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ui(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},U("done","success",_(zs)),Ne),success:pi(),error:pi()},e=>e),ea=async e=>new Promise((t,r)=>{ye(Zs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),fi=async(e,t,r,n)=>ea({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var Ft=class{url;username;password;namespace;database;constructor(t){this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database;}async run(t){let r=new ta;try{return await r.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1}),await t(r)}finally{await r.close();}}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}};enableMapSet();var hr=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 n=>{if(n.provider==="surrealDB"){let o=new Ft({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});t.surrealDB.set(n.id,{client:o,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[o,i]=await tryit(TypeDB.coreDriver)(n.url);if(o){let a=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let s=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(n.provider==="typeDBCluster"&&n.dbName){let o=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,o);if(i){let s=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:s});}catch(s){let d=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(d)}}}));let r=Qr(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()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await Br(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...wt.query,...this.config.query,...r}},o=Array.isArray(t),i=o?t:[t],[a,s]=await tryit(ve)(i,this.schema,n,this.dbHandles);if(a){let h=new Error(a.error);throw h.stack=a.error.stack,h}let d=s.bql.res;return o?d:d[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...wt.mutation,...this.config.mutation,...r}},[o,i]=await tryit(fi)(t,this.schema,n,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Ch=hr;//! TO-DO Rule: Everything that can be changed or defined by the user should use $ prefix, but the rest is metadata and should be packed in symbols, depending on their origin. extension inside the schema and schema or query inside the query. Probably no more categories are necessary
149
149
  //! Todo: delete when this works with the new $thing and $thingType fields
150
150
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
151
151
  //! reads all the insertions and gets the first match. This means each id must be unique
152
152
  //!old
153
153
 
154
- export { Ih as default };
154
+ export { Ch as default };
155
155
  //# sourceMappingURL=index.mjs.map
156
156
  //# sourceMappingURL=index.mjs.map