@blitznocode/blitz-orm 0.11.23 → 0.11.24

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
@@ -8,7 +8,7 @@ import 'acorn';
8
8
  import { v4 } from 'uuid';
9
9
  import Ps from 'surrealdb';
10
10
 
11
- var Tt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var di=e=>{let t=[],r=new Map;return e.forEach(n=>{let{dbPath:s,contentType:i}=n,a=`${s}-${i}`;r.has(a)||(r.set(a,!0),t.push(n));}),t},ui=(e="default",t)=>{let r="",n=[];r+=`
11
+ var Tt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var ci=e=>{let t=[],r=new Map;return e.forEach(n=>{let{dbPath:s,contentType:i}=n,a=`${s}-${i}`;r.has(a)||(r.set(a,!0),t.push(n));}),t},di=(e="default",t)=>{let r="",n=[];r+=`
12
12
  `,Object.keys(t.entities).filter(o=>t.entities[o].defaultDBConnector.id===e).forEach(o=>{let c=t.entities[o],{dataFields:p,linkFields:u,name:d}=c;if(r+=`${d} sub ${"extends"in c?c.extends:"entity"},
13
13
  `,p&&p.length>0&&p.forEach(l=>{l.inherited||(l.isIdField?r+=` owns ${l.dbPath} @key,
14
14
  `:r+=` owns ${l.dbPath},
@@ -24,7 +24,7 @@ var Tt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
24
24
  `),r+=`
25
25
  `;});let s=`define
26
26
 
27
- `;return di(n).forEach(o=>{if(o.contentType==="TEXT"||o.contentType==="ID"||o.contentType==="JSON")s+=`${o.dbPath} sub attribute, value string;
27
+ `;return ci(n).forEach(o=>{if(o.contentType==="TEXT"||o.contentType==="ID"||o.contentType==="JSON")s+=`${o.dbPath} sub attribute, value string;
28
28
  `;else if(o.contentType==="EMAIL")s+=`${o.dbPath} sub attribute, value string,
29
29
  `,s+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';
30
30
  `;else if(o.contentType==="DATE")s+=`${o.dbPath} sub attribute, value datetime;
@@ -47,29 +47,29 @@ flexAttribute sub attribute, abstract, value string,
47
47
  owns doubleAttribute,
48
48
  owns booleanAttribute,
49
49
  owns datetimeAttribute;
50
- `},ur=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let s=ui(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:o}]=t.dbConnectors;await(await a.databases.get(o)).delete(),await a.databases.create(o);let u=await(await a.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await u.query.define(s),await u.commit(),await u.close(),s};var hr=e=>e.replace(/`/g,""),hi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],ee=e=>hi.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var wt=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 fr={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"},Ze=(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"?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`$<datetime>"${e}"`;case"FLEX":{let r=isArray(e)?e.map(n=>wt(n)):wt(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 $i=" ",Ce=e=>$i.repeat(e),et=(e,t)=>e.split(`
50
+ `},ur=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let s=di(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:o}]=t.dbConnectors;await(await a.databases.get(o)).delete(),await a.databases.create(o);let u=await(await a.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await u.query.define(s),await u.commit(),await u.close(),s};var hr=e=>e.replace(/`/g,""),ui=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],ee=e=>ui.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var wt=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 fr={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"},Ze=(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"?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`$<datetime>"${e}"`;case"FLEX":{let r=isArray(e)?e.map(n=>wt(n)):wt(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 fi=" ",Ce=e=>fi.repeat(e),et=(e,t)=>e.split(`
51
51
  `).map(r=>r.trim()?`${Ce(t)}${r}`:r).join(`
52
- `),mi=e=>{let t=`USE NS test;
52
+ `),$i=e=>{let t=`USE NS test;
53
53
  USE DB test;
54
54
 
55
55
  BEGIN TRANSACTION;
56
56
  `,r=`-- ENTITIES
57
57
  ${$r(e.entities)}`,n=`
58
58
  -- RELATIONS
59
- ${$r(e.relations)}`,s=Ti();return `${t}${r}${n}${s}COMMIT TRANSACTION;`},$r=e=>Object.entries(e).map(([t,r])=>yi(ee(t),r,1)).join(`
59
+ ${$r(e.relations)}`,s=Fi();return `${t}${r}${n}${s}COMMIT TRANSACTION;`},$r=e=>Object.entries(e).map(([t,r])=>mi(ee(t),r,1)).join(`
60
60
 
61
- `),yi=(e,t,r)=>{let n=`${Ce(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,s=et(`-- DATA FIELDS
62
- ${gi(t.dataFields??[],e,r)}`,r+1),i=et(`
61
+ `),mi=(e,t,r)=>{let n=`${Ce(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,s=et(`-- DATA FIELDS
62
+ ${yi(t.dataFields??[],e,r)}`,r+1),i=et(`
63
63
  -- LINK FIELDS
64
- ${Ei(t.linkFields??[],e,r)}`,r+1),a="roles"in t?et(`
64
+ ${gi(t.linkFields??[],e,r)}`,r+1),a="roles"in t?et(`
65
65
  -- ROLES
66
- ${Bi(t.roles,e,r)}`,r+1):"";return `${n}
67
- ${s}${i}${a}`},gi=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let s=Fi(n.contentType,n.validations),i=`${Ce(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 ${s};`}).filter(Boolean).join(`
68
- `),Ei=(e,t,r)=>e.map(n=>{let s=n.cardinality==="MANY"?`option<array<record<${n.$things.map(ee).join("|")}>>>`:`option<record<${n.$things.map(ee).join("|")}>>`,i=`${Ce(r)}DEFINE FIELD ${ee(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(h=>h.target==="relation"&&h.relation===n.relation),c=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!c||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let p=n.cardinality==="ONE"?`record<${ee(n.relation)}>`:`array<record<${ee(n.relation)}>>`,u=ee(n.pathToRelation||""),d=`${u}.${c}`,l=n.cardinality==="ONE"?`${i} VALUE <future> {RETURN SELECT VALUE ${d} FROM ONLY $this};`:`${i} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${d} || []) FROM ONLY $this)};`,f=a?.path?"":`${Ce(r+1)}DEFINE FIELD ${u} ON TABLE ${t} TYPE option<${p}>;`;return [l,f].join(`
66
+ ${Ei(t.roles,e,r)}`,r+1):"";return `${n}
67
+ ${s}${i}${a}`},yi=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let s=bi(n.contentType,n.validations),i=`${Ce(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 ${s};`}).filter(Boolean).join(`
68
+ `),gi=(e,t,r)=>e.map(n=>{let s=n.cardinality==="MANY"?`option<array<record<${n.$things.map(ee).join("|")}>>>`:`option<record<${n.$things.map(ee).join("|")}>>`,i=`${Ce(r)}DEFINE FIELD ${ee(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(h=>h.target==="relation"&&h.relation===n.relation),c=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!c||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let p=n.cardinality==="ONE"?`record<${ee(n.relation)}>`:`array<record<${ee(n.relation)}>>`,u=ee(n.pathToRelation||""),d=`${u}.${c}`,l=n.cardinality==="ONE"?`${i} VALUE <future> {RETURN SELECT VALUE ${d} FROM ONLY $this};`:`${i} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${d} || []) FROM ONLY $this)};`,f=a?.path?"":`${Ce(r+1)}DEFINE FIELD ${u} ON TABLE ${t} TYPE option<${p}>;`;return [l,f].join(`
69
69
  `)}if(n.target==="relation")return `${`${Ce(r)}DEFINE FIELD ${ee(n.path)} ON TABLE ${t} TYPE ${s};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
70
- `),Bi=(e,t,r)=>Object.entries(e).map(([n,s])=>{let i=s.cardinality==="MANY"?`array<record<${s.$things.map(ee).join("|")}>>`:`record<${s.$things.map(ee).join("|")}>`,a=`${Ce(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,o=bi(n,t,s,r);return `${a}
70
+ `),Ei=(e,t,r)=>Object.entries(e).map(([n,s])=>{let i=s.cardinality==="MANY"?`array<record<${s.$things.map(ee).join("|")}>>`:`record<${s.$things.map(ee).join("|")}>`,a=`${Ce(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,o=Bi(n,t,s,r);return `${a}
71
71
  ${o}`}).join(`
72
- `),bi=(e,t,r,n)=>{let s=`update_${e}`,i=r.playedBy?.find(F=>F.target==="relation"),a=i?.pathToRelation,o=r.playedBy?.find(F=>F.target==="role"),c=o?.pathToRelation,p=i??o;if(!p)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let u=ee(a??c),d=(F,y)=>F.map(({path:R,cardinality:L})=>`${R} ${y==="remove"?L==="ONE"?"=":"-=":L==="ONE"?"=":"+="} ${y==="remove"?L==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),l=r.impactedLinkFields?.map(F=>({path:F.path,cardinality:F.cardinality}))||[],h=[{path:u,cardinality:p.cardinality},...l],$=d(h,"remove"),g=d(h,"add"),m=`
72
+ `),Bi=(e,t,r,n)=>{let s=`update_${e}`,i=r.playedBy?.find(F=>F.target==="relation"),a=i?.pathToRelation,o=r.playedBy?.find(F=>F.target==="role"),c=o?.pathToRelation,p=i??o;if(!p)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let u=ee(a??c),d=(F,y)=>F.map(({path:R,cardinality:L})=>`${R} ${y==="remove"?L==="ONE"?"=":"-=":L==="ONE"?"=":"+="} ${y==="remove"?L==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),l=r.impactedLinkFields?.map(F=>({path:F.path,cardinality:F.cardinality}))||[],h=[{path:u,cardinality:p.cardinality},...l],$=d(h,"remove"),g=d(h,"add"),m=`
73
73
  IF ($before.${e}) THEN {UPDATE $before.${e} SET ${$}} END;
74
74
  IF ($after.${e}) THEN {UPDATE $after.${e} SET ${g}} END;`,b=`
75
75
  LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
@@ -78,7 +78,7 @@ ${o}`}).join(`
78
78
  IF ($link.${u}) THEN {UPDATE $link.${u} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
79
79
  UPDATE $link SET ${g};
80
80
  };`;return et(`DEFINE EVENT ${s} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?m:b}
81
- };`,n+1)},Fi=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>Ze(n,e)).join("|")}`:fr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},Ti=()=>`
81
+ };`,n+1)},bi=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>Ze(n,e)).join("|")}`:fr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},Fi=()=>`
82
82
  -- BORM TOOLS
83
83
  DEFINE FUNCTION fn::get_mutated_edges(
84
84
  $before_relation: option<array|record>,
@@ -100,26 +100,26 @@ ${o}`}).join(`
100
100
  DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
101
101
  RETURN (type::is::array($var) AND $var) OR [$var]
102
102
  };
103
- `,mr=e=>mi(e);var yr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([c])=>[c,await ur(c,e,t,r)]))).map(c=>[c[0],c[1]]),o=(await Promise.all([...r.surrealDB||[]].map(async([c])=>[c,mr(t)]))).map(c=>[c[0],c[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(o)}})();var oe=Symbol.for("queryPath"),tt=Symbol.for("stepPrint"),Ie=Symbol.for("edgeType"),Fe=Symbol.for("edgeSchema"),Ne=Symbol.for("dbNode"),Mt=Symbol.for("isTransformed"),rt=Symbol.for("parent"),se=Symbol.for("fieldSchema"),we=Symbol.for("sharedMetadata"),Le=Symbol.for("suqlMetadata");var gr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Er=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let s=r.relations[e.relation].subTypes||[],i=[e.relation,...s],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[o]=e.oppositeLinkFieldsPlayedBy,c=r.entities[o.thing]?.subTypes||r.relations[o.thing]?.subTypes||[],p=[o.thing,...c],u=`->\u27E8${t}_${o.plays}\u27E9->(\u27E8${p.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${a}${u}`:n==="refs"?e.cardinality==="MANY"?`$parent.[\`${o.plays}\`]`:`$parent.\`${o.plays}\``:`${a}${u}`}else throw new Error("Unsupported linkField target")};var Fr=(e,t,r)=>r?t:`${e}\xB7${t}`;var wr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],de=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,s])=>{let[i,a]=tryit(()=>t(n,s))();return i?!1:a}))},Mr=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:a,value:o,meta:c})=>{if(c.depth===2&&(a&&(o.dataFields=o.dataFields?.map(p=>({...p,...o.idFields?.includes(p.path)?{isIdField:!0}:{isIdField:!1},cardinality:p.cardinality||"ONE",dbPath:"dbPath"in p?p.dbPath:Fr(a,p.path,p.shared)}))),o.extends)){if(!o.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${c.nodePath}`);let p=i.entities[o.extends]||i.relations[o.extends],u=[o.extends,...p.allExtends||[]];if(o.allExtends=u,u.forEach(d=>{if(i.entities[d])i.entities[d].subTypes=[a,...i.entities[d].subTypes||[]];else if(i.relations[d])i.relations[d].subTypes=[a,...i.relations[d].subTypes||[]];else throw new Error(`[Schema] ${a} is extending a thing that does not exist in the schema: ${d}`)}),o.idFields=p.idFields?Array.from(new Set((o.idFields||[]).concat(p.idFields))):o.idFields,o.dataFields=p.dataFields?(o.dataFields||[]).concat(p.dataFields.map(d=>{let l=o.extends,f=e.entities[l]||e.relations[l];for(;!f.dataFields?.find(h=>h.path===d.path);)l="extends"in f?f.extends:void 0,f=e.entities[l]||e.relations[l];return {...d,inherited:!0,dbPath:"dbPath"in d?d.dbPath:Fr(l,d.path,d.shared),[we]:{inheritanceOrigin:d[we]?.inheritanceOrigin||o.extends}}})):o.dataFields,"roles"in p){let d=o,l=p;if(l.roles){let f=mapEntries(l.roles,(h,$)=>[h,{...$,inherited:!0,[we]:{inheritanceOrigin:$[we]?.inheritanceOrigin||o.extends}}]);d.roles={...d.roles||{},...f};}}o.linkFields=p.linkFields?(o.linkFields||[]).concat(p.linkFields.map(d=>({...d,inherited:!0,[we]:{inheritanceOrigin:d[we]?.inheritanceOrigin||o.extends}}))):o.linkFields,p?.hooks?.pre&&(o.hooks=o.hooks||{},o.hooks.pre=o.hooks.pre||[],o.hooks.pre=[...p?.hooks?.pre||[],...o?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));traverse(e,({key:i,value:a,meta:o})=>{if(i==="linkFields"){let p=(()=>{if(!o.nodePath)throw new Error("No path");let[d,l]=o.nodePath.split(".");return {thing:l,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),u=Array.isArray(a)?a.map(d=>({...d,...p})):[{...a,...p}];r.push(...u);}});let s=produce(n,i=>traverse(i,({value:a,key:o,meta:c})=>{if(c.depth===2&&a.idFields&&!a.id){a.name=o;let p=()=>{if(c.nodePath?.split(".")[0]==="entities")return "entity";if(c.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=p();let u=Object.keys(t).find(d=>t[d]?.get(a.defaultDBConnector.id));if(a.db=u,a.dbContext=gr[u],a.dbProviderConfig=u==="surrealDB"?t[u]?.get(a.defaultDBConnector.id)?.providerConfig:void 0,a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"linkFields"in a&&a.linkFields){let d=a;d.linkFields?.forEach(l=>{l.fieldType="linkField";let f=n.relations[l.relation];if(!l.isVirtual){if(!f)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(f.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: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.$things=[l.relation,...f.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){if(l.oppositeLinkFieldsPlayedBy=r.filter(h=>h.relation===l.relation&&h.plays!==l.plays&&h.target==="role"),l.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.pathToRelation=d.linkFields?.find(h=>h.target==="relation"&&h.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(h=>[h.thing,...K(n,h.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(h=>h.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(a.db==="surrealDB"){let h=f?.roles?.[l.plays][we]?.inheritanceOrigin??l.relation,$=Er({linkField:l,originalRelation:h,withExtensionsSchema:n,linkMode:a.dbProviderConfig.linkMode});l[Le]={queryPath:$};}});}if("roles"in a){let d=a;Object.entries(d.roles).forEach(([l,f])=>{f.fieldType="roleField";let h=r.filter(y=>y.relation===o&&y.plays===l)||[];f.playedBy=h.map(y=>({...y,pathToRelation:y.target==="relation"?y.path:d.linkFields?.find(R=>R.target==="relation"&&R.relation===o&&R.plays===l)?.path??y.relation.toLocaleLowerCase()}));let $=r.filter(y=>y.target==="relation"&&y.plays===l&&d.allExtends?.includes(y.relation));f.impactedLinkFields=$,f.path=l;let g=[...new Set(h.flatMap(y=>[...K(n,y.thing).subTypes||[],y.thing]).flat().filter(Boolean))];f.$things=g;let m=f[we]?.inheritanceOrigin||a.name,b=g.flatMap(y=>{let L=K(e,y)?.subTypes||[];return [y,...L]}),F=()=>{if(a.dbProviderConfig.linkMode==="edges")return `->\`${m}_${l}\`->(\`${b.join("`,`")}\`)`;if(a.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.[\`${l}\`]`;if(f.cardinality==="ONE")return `$parent.\`${l}\``}throw new Error("Unsupported linkMode")};if(a.db==="surrealDB"){let y=F();f[Le]={queryPath:y};}});}}if(a&&typeof a=="object"&&"playedBy"in a){let p=[...new Set(a.playedBy.map(u=>u.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${o}, path:${c.nodePath}, played by: ${p.join(", ")}`),a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${o}, path:${c.nodePath}`)}if(c.depth===4){let[p,u]=c.nodePath?.split(".")||[],d=i[p][u];!isArray(a)&&typeof a=="object"&&(a.validations&&(a.validations.required&&d.requiredFields.push(a.path),a.validations.enum&&d.enumFields.push(a.path),a.validations.fn&&d.fnValidatedFields.push(a.path)),a.default?a.isVirtual?d.virtualFields.push(a.path):d.computedFields.push(a.path):a.isVirtual&&d.virtualFields.push(a.path));}}));return console.log("schema and enrichedSchema",JSON.stringify(e),JSON.stringify(s)),s},K=(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`)},N=(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)}`)},it=(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 s="roles"in e?e.roles[t]:void 0;if(s)return ["roleField",s];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},ot=(e,t)=>{let r=N(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},Sr=(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=N(e,t),s=n.linkFields?.find(o=>o.path===r);if(s)return s;let i=n.dataFields?.find(o=>o.path===r);if(i)return i;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},Rt=(e,t,r)=>Qt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],n=e.linkFields?.map(h=>h.path)||[],s="roles"in e?listify(e.roles,h=>h):[],i=[...r||[],...n||[],...s||[]],o=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!t)return {fields:i,dataFields:r,roleFields:s,linkFields:n};let c=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!i.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!i.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),p=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],u=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...s||[],...n||[]].includes(h)):[],d=[...c,...p].filter(h=>!h?.startsWith("%")).filter(h=>!o.includes(h)).filter(h=>h),l=t.$filter?de(t.$filter,(h,$)=>p.includes(h)):{},f=t.$filter?de(t.$filter,(h,$)=>u.includes(h)):{};return {fields:i,dataFields:r,roleFields:s,linkFields:n,usedFields:c,usedLinkFields:n.filter(h=>c.includes(h)),usedRoleFields:s.filter(h=>c.includes(h)),usedDataFields:r.filter(h=>c.includes(h)),unidentifiedFields:d,...p.length?{localFilters:l}:{},...u.length?{nestedFilters:f}:{}}};var Lr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Qr=(e,t,r)=>{let s=(r.nodePath||"").split("."),i=isArray(t)?s.slice(0,-2).join("."):s.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},Qe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var st=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Te=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,s])=>{r[n]=isDraft(s)?current(s):s;}),r}else return e},pe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Ae=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var xe=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Dr=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(!n.every(s=>typeof s=="object"))if(n.every(s=>typeof s=="string")){let s=xe(t,r),[i]=s,a=e.$op==="create"?"link":"replace",o=i.thing,c=i.thingType,p={$op:a,$thing:o,$thingType:c},u=n.filter(l=>l.startsWith("_:")),d=n.filter(l=>!l.startsWith("_:"));u.length&&!d.length?e[t]=u.map(l=>({...p,$tempId:l,$bzId:l})):u.length&&d.length?e[t]=[...u.map(l=>({...p,$tempId:l,$bzId:l})),{...p,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...p,$id:e[t],$bzId:`S_${nanoid()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(n)} Parent: ${JSON.stringify(e,null,2)})`)};var Oe=(e,t,r)=>{let n=N(r,t),{usedDataFields:s}=ue(n,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&s.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&s.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var at=(e,t,r)=>{let n=N(r,t),{usedFields:s}=ue(n,t);return t.$op?(Oe(e,t,r),t.$op):t.$id||t.$filter?s.length>0?(Oe(e,{...t,$op:"update"},r),"update"):(Oe(e,{...t,$op:"link"},r),"link"):t.$tempId?s.length>0?(Oe(e,{...t,$op:"create"},r),"create"):(Oe(e,{...t,$op:"create"},r),"link"):(Oe(e,{...t,$op:"create"},r),"create")};var Ir=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(s=>{let i=at(s,s,t);return {...{...s.$thing?{}:{$thing:s.$entity||s.$relation},...s.$thingType?{}:{$thingType:Sr(s,t)},...s.$op?{}:{$op:i},...s.$bzId?{}:{$bzId:`R_${Ae()}`}},...s}});e.$root=isArray(e.$root)?n:n[0];};var lt=(e,t)=>{let r=t[tt];return isSet(r)?r.has("clean")?(Reflect.set(t,tt,r.add("clean")),!0):!1:(Reflect.set(t,tt,new Set(["clean"])),!0)};var Ar=(e,t,r)=>{if(lt("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(s=>{if(isObject(s)&&"$id"in s&&isArray(s.$id)){let i=s;if(N(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,o)=>({...Te(i),$id:a,$bzId:`${i.$bzId}_${o}`,...Qe(i)}))}return s});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Or=(e,t,r,n)=>{let s=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=xe(t,r),[o]=a,c=at(e,{...i,$thing:o.thing,$thingType:o.thingType},n),u=i.$bzId?i.$bzId:i.$tempId?i.$tempId:i.$id&&!isArray(i.$id)?`SN_ONE_${o.thing}_${i.$id}`:i.$id&&isArray(i.$id)?`SN_MANY_${o.thing}_${Ae()}`:`SM_${Ae()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[Fe]:r,$thing:o.thing,$thingType:o.thingType,$op:c,$bzId:u}});e[t]=isArray(e[t])?s:s[0];};var Ai=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Oi=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,qr=e=>{let r=e.toString().replace(Ai,"").trim().split("=>")[0].split("{")[0].replace(Oi,"").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 je=({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=qr(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 Pr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(s=>{let i=N(r,s),{unidentifiedFields:a}=ue(i,s),{computedFields:o,virtualFields:c}=i,p=listify(s,(l,f)=>f!==void 0?l:void 0),u=p.filter(l=>c?.includes(l));if(u.length>0)throw new Error(`Virtual fields can't be sent to DB: "${u.join(",")}"`);if(o.filter(l=>!p.includes(l)).forEach(l=>{let f=i.dataFields?.find(b=>b.path===l),$=i.linkFields?.find(b=>b.path===l)?.oppositeLinkFieldsPlayedBy[0],g="roles"in i?wr(i.roles,(b,F)=>b===l):void 0,m=f||$||g;if(!m)throw new Error(`no field Def for ${l}`);if(s.$op==="create"&&!s[l]){let b=je({currentThing:s,fieldSchema:m,mandatoryDependencies:!0});s[l]=b;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(s)}`)}),e};var dt=(e,t)=>{let r=N(t,e).hooks;if(r?.pre){let n=`on${Lr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var Nr=(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:o,fnValidatedFields:c,dataFields:p}=N(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(u=>{if(!(u in i))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&o.forEach(u=>{if(u in i){let d=p?.find(l=>l.path===u)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(i[u]))i[u].some(l=>{if(!d.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(d&&!d.includes(i[u]))throw new Error(`[Validations] Option "${i[u]}" is not a valid option for field "${u}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&c.forEach(u=>{if(u in i)try{let d=p?.find(l=>l.path===u)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(i[u]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${u}] ${d.message}`)}}),isObject(i)&&"$thing"in i){let u=i.$thing,d=i,l=clone(Te(e)),f=clone(Te(d)),h=n.mutation?.context||{},$=clone(Te(i[Ne]||{}));dt(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let b=m.fn(f,l,h,$);if(b===!1)throw new Error(`${m.message}.`);if(b!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(b){throw new Error(`[Validations:thing:${u}] ${b.message}`)}}});}}});};var jr=(e,t,r,n)=>{let s=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(st(i)){if(i.$fields||i[Mt])return i;let a=dt(i,r).filter(d=>d.type==="transform"),o=clone(Te(e)),c=clone(Te(i)),p=n.mutation?.context||{},u=clone(Te(i[Ne]||i.$dbNode));return a.forEach(d=>{let l=d.fn(c,o,p,u||{});Object.keys(l).length!==0&&(i={...c,...l,...Qe(i),[Mt]:!0});}),i}});e[t]=isArray(e[t])?s:s[0];};var _r=(e,t,r)=>{let n=xe(t,r),[s]=n;e[t]={$thing:s.thing,$thingType:s.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Fe]:r};};var _e=e=>{if(Array.isArray(e)){for(let t of e)if(_e(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"&&_e(e[t]))return !0}return !1};var Wr=(e,t)=>{for(let s of e)if(!("$entity"in s)&&!("$relation"in s)&&(!("$thing"in s)||!("$thingType"in s)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,s=>traverse(s,i=>{let{value:a,meta:o}=i,c=a;if(isObject(c)){if(c.$id){if(o.nodePath?.includes(".$filter"))return;let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},u=N(t,p);if(!u?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=u.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),u?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let p=N(t,c);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=p.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c&&c.$thing){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[oe]=o.nodePath;let u=N(t,p);if(c.$filter&&(Object.keys(c.$filter).length===0?c.$filter=void 0:(c.$filter=Re(c.$filter,c.$thing,t),c.$filterByUnique=Ot(c.$filter,u))),c.$fields){c.$fields.some(f=>u?.idFields?.includes(f?.$path||f))||(c.$fields=[...c.$fields,...Array.isArray(u.idFields)?u.idFields:[]],c.$idNotIncluded=!0);let l=c.$fields?.flatMap(f=>{let h=Ur(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}else {let l=At(u)?.flatMap(f=>{let h=Ur(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}c.$excludedFields&&(c.$fields=c.$fields.filter(d=>ut(u,d)?!0:!c.$excludedFields.includes(d.$path)));}}}))},At=e=>{let t=e.dataFields?.map(i=>i.path)||[],r=e.linkFields?.map(i=>i.path)||[],n=Object.keys(e.roles||{})||[];return [...t,...r,...n]},Ot=(e,t)=>Object.keys(e||{}).some(n=>{let s=e[n];if(s!==null&&typeof s<"u"){let i=t.idFields?.includes(n),a=t.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique),o=n==="$id"&&!Array.isArray(s);if(i||a||o){if(typeof s!="object"||s===null||Array.isArray(s))return !Array.isArray(s);{let p=Object.keys(s);if(p.length===1&&p[0]==="$eq"){let u=s.$eq;if(typeof u!="object"||u===null||!Array.isArray(u))return !0}return !1}}}return !1}),ut=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),_i=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:s,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:s,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[se]:a}},Ui=e=>{let{field:t,fieldStr:r,linkField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e,{target:c,oppositeLinkFieldsPlayedBy:p}=n;return p.map(u=>{let d=c==="role"?u.thingType:"relation",l=c==="role"?u.thing:n.relation,f={[`$${d}`]:l},h=N(a,f),$=t?.$fields?.filter(b=>ut(h,b)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let b=h.idFields||[];g=[...t.$fields,...b];}else g=t.$fields;else g=At(h);else g=["id"];t.$excludedFields&&(g=g.filter(b=>ut(h,b)?!0:!t.$excludedFields.includes(b.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:d,$plays:n.plays,$playedBy:{...u,oppositeLinkFieldsPlayedBy:void 0},$path:u.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:l,$fields:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:c,$intermediary:u.relation,$justId:s,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Ot(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[se]:o}})},Wi=e=>{let{field:t,fieldStr:r,roleField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e;return n.playedBy.map(c=>{let{thing:p,thingType:u,relation:d}=c,l={[`$${u}`]:p},f=N(a,l),h=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=At(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>ut(f,m)?!0:!t.$excludedFields.includes(m.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:s,$id:t.$id,$filter:g,$idNotIncluded:h,$filterByUnique:Ot(t.$filter,f),$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[se]:o}})},Ur=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,s=typeof e=="string",i=t.dataFields?.find(c=>c.path===n),a=t.linkFields?.find(c=>c.path===n),o=t.roles?.[n];if(i){let c=!!i.isVirtual&&!!i.default;return _i({field:e,fieldStr:n,$justId:s,dbPath:i.dbPath,isVirtual:c,fieldSchema:i})}else {if(a)return Ui({field:e,fieldStr:n,linkField:a,$justId:s,dbPath:a.path,schema:r,fieldSchema:a});if(o)return Wi({field:e,fieldStr:n,roleField:o,$justId:s,dbPath:n,schema:r,fieldSchema:o})}return null},Re=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce((p,u)=>{let d=a[u],l=isArray(d)?d:[d];if(u.startsWith("$"))if(["$id","$thing"].includes(u))p[u]=d;else if(["$not","$or","$and"].includes(u))p[u]=Re(d,t,r);else if(["$eq","$in","$exists"].includes(u))p[u]=d;else throw new Error(`[Internal] Unknown filter operator ${u}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[h,$]=it(f,u);if(h==="idField")p[u]=d;else if(h==="dataField")isObject(d)||isArray(d)&&d.some(isObject)?p[u]=isArray(d)?{$or:Re(d,t,r)}:Re(d,t,r):isArray(d)?p[u]={$in:d}:p[u]={$eq:d};else if(h==="linkField"||h==="roleField"){let g=$,[m]=g.$things;l.every(b=>typeof b=="string")?p[u]={$id:l,$thing:m}:l.every(b=>isObject(b))&&(p[u]=isArray(d)?{$or:Re(d,m,r)}:Re(d,m,r));}else throw new Error(`Field ${u} not found in schema of ${t}`)}return p},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var Ji=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(lt("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);},Yi=(e,t)=>{},Pt=(e,t,r)=>{let n={$rootWrap:{$root:e}},s=_e(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:o,parent:c,key:p,meta:u})=>{if(!(!c||!p)&&isObject(o)){let d=u.nodePath?.split(".")||[];if(!("$root"in o)){if(!("$thing"in o||"$entity"in o||"$relation"in o)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],g=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(g)&&!$.startsWith("%")&&!g.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(o)?current(o):o)}`)}}let l=o,f=d.includes("$filter");"$filter"in l&&l.$filter&&(l.$filter=Re(l.$filter,l.$thing,t)),Object.keys(l).forEach(h=>{if(Ji(l,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?Qt(t,l,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Yi();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(l[h]===null?_r(l,h,$):Dr(l,h,$)),$.fieldType==="rootField"){if(!("$root"in l))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Ir(l,t);}let g=isArray(l[h])?l[h]:[l[h]],m=d.slice(1).join(".");g.forEach(F=>{if(F){if($?.cardinality==="ONE"&&!F.$op&&!F.$id&&!F.$filter&&!F.$tempId&&l.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(F.$tempId&&!(F.$op===void 0||F.$op==="link"||F.$op==="create"||F.$op==="update"))throw new Error(`Invalid op ${F.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&Or(l,h,$,t),Ar(l,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&Pr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(F=>{let y=N(t,F),{unidentifiedFields:R,usedLinkFields:L,usedFields:D,fields:C}=ue(y,F);if(D.forEach(_=>{if(!C.includes(_))throw new Error(`[Schema] Field ${_} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(o)}`);if(L.length>1){let _=y.linkFields?.filter(J=>L.includes(J.path));_?.some((J,he)=>_.some((v,I)=>{if(he!==I&&J.target!==v.target&&J.relation===v.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),s||(jr(l,h,t,r),Nr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var Vr=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 Kr=async(e,t)=>{let r=u=>{let d=[],l=[],f=m=>{if(m.$id)return m.$id;let b=N(t,m),{idFields:F}=b;if(!F)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[y]=F;if(!y)throw new Error(`no idField: ${JSON.stringify(m)}`);let R=b.dataFields?.find(C=>C.path===y),L=je({currentThing:m,fieldSchema:R,mandatoryDependencies:!0}),D=m[y]||m.$id||L;if(!D)throw new Error(`no idValue: ${JSON.stringify(m)}`);return D},h=m=>{if(m.$op==="create"){let b=f(m);if(d.find(F=>F.$id===b&&F.$op==="create"))throw new Error(`Duplicate id ${b} for node ${JSON.stringify(m)}`);d.push({...m,$id:b});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let b=f(m);if(d.find(F=>F.$id===b&&F.$op==="create"))throw new Error(`Duplicate id ${b} for edge ${JSON.stringify(m)}`);l.push({...m,$id:b});return}l.push(m);};return traverse(u,({value:m,parent:b,meta:F})=>{if(!isObject(m))return;let y=m;if(!F.nodePath?.includes(".$filter")&&y.$thing){if(!y.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(y)}`);if(!y.$bzId)throw new Error("[internal error] BzId not found");let R=N(t,y),{dataFields:L,roleFields:D,linkFields:C,usedFields:_}=ue(R,y),J=()=>{if(y.$op==="create"||y.$op==="delete")return y.$op;if(y.$op==="update"){let I=_.filter(B=>L?.includes(B)),k=_.filter(B=>D?.includes(B)),E=_.filter(B=>C?.includes(B));if(I.length>0)return "update";if(k.length>0||E.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(y)}`)}return "match"},he={...y.$id&&{$id:y.$id},...y.$tempId&&{$tempId:y.$tempId},...y.$filter&&{$filter:y.$filter},$thing:y.$thing,...y.$thingType&&{$thingType:y.$thingType},...shake(pick(y,L||[""])),$op:J(),$bzId:y.$bzId};h(he);let v=y[Fe];if(v?.fieldType==="linkField"){if((y.$op==="link"||y.$op==="unlink")&&(y.$id||y.$filter)){if(y.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...y,$op:"match"});}let I=v.relation===y.$thing,k=I?y.$bzId:`LT_${v4()}`,B=Qr(u,b,F).$bzId;if(!B)throw new Error("No parent id found");let T=()=>y.$op==="delete"?I?"match":"delete":y.$op==="unlink"?I?"unlink":"delete":y.$op==="link"||y.$op==="create"?I?"link":"create":y.$op==="replace"?"replace":"match",S=N(t,{$thing:v.relation,$thingType:"relation"});if(!Object.keys(S.roles).includes(v.plays))throw new Error(`[Wrong format] Field ${v.plays} is not a role of relation ${v.relation}`);let Q={$bzId:k,$thing:v.relation,$thingType:"relation",...y.$tempId?{$tempId:y.$tempId}:{},$op:T(),...I?{}:{[v.path]:y.$bzId},[v.plays]:B,[Fe]:v,[Ie]:"linkField"};$(Q),(y.$op==="unlink"||T()==="unlink")&&I&&$({$thing:v.relation,$thingType:"relation",$bzId:k,$op:"match",[v.plays]:B,[Fe]:v,[Ie]:"linkField"});}if(y.$thingType==="relation"){let I=de(y,(B,T)=>D.includes(B)),k=mapEntries(I,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),E=de(m,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(I).filter(B=>!B.startsWith("$")).length>0){if(y.$op==="create"||y.$op==="delete"){let B=()=>{if(y.$op==="create")return "link";if(y.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=N(t,y).roles,S=mapEntries(k,(Q,A)=>{let U=T[Q]?.cardinality;if(!U)throw new Error(`Role ${Q} not found in schema`);if(Array.isArray(A)){if(U==="ONE"){if(A.length>1)throw new Error(`[Error] Role ${Q} is not a MANY relation`);return [Q,A[0].$bzId||A[0]]}return [Q,A.map(q=>q.$bzId||q)]}return [Q,A.$bzId||A]}),w={...E,$thing:y.$thing,$thingType:"relation",$op:B(),...S,$bzId:y.$bzId,[Ie]:"roleField"};$(w);return}if(y.$op==="match"||y.$op==="update"&&Object.keys(I).length>0){let B=0;Object.entries(I).forEach(([T,S])=>{let w=isArray(S)?S:[S],Q=A=>A==="create"||A==="replace"?"link":A;w.forEach(A=>{if(!A)return;let U=Q(A.$op);if(U==="replace")throw new Error("Not supported yet: replace on roleFields");if(U==="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 q={...E,$thing:y.$thing,$thingType:"relation",$op:U==="delete"?"unlink":U,[T]:A.$bzId,$bzId:y.$bzId,[Ie]:"roleField"};$(q);});});}}}}}),[d,l]},[n,s]=r(e),i=n.reduce((u,d)=>{if(!d.$bzId)return [...u,d];let l=u.findIndex(f=>f.$bzId===d.$bzId);if(l===-1)return [...u,d];if(u[l].$op==="create"&&d.$op==="match")return u;if(u[l].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...u.slice(0,l),d,...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d},...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="match"||u[l].$op==="match"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d,$op:"update"},...u.slice(l+1)];if(u[l].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(u[l].$filter)===JSON.stringify(d.$filter))return u;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${u[l].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${u[l].$op}. Current: ${d.$op}`)},[]),a=s.reduce((u,d)=>{let l=u.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(l){let f={...l};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=l[$],m=d[$];Array.isArray(g)&&Array.isArray(m)?f[$]=Array.from(new Set([...g,...m])):!Array.isArray(g)&&Array.isArray(m)?g!==void 0?f[$]=Array.from(new Set([g,...m])):f[$]=m:Array.isArray(g)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...g,m]))):g!==null&&m!==null&&g!==void 0&&m!==void 0?f[$]=Array.from(new Set([g,m])):g==null&&(f[$]=m);}),[...u.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...u,d]},[]);i.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&a.filter(d=>d.$bzId===u.$bzId||d.$tempId&&d.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Vr(u))}`)}});let o=[...i,...a],c=new Set(o.filter(u=>u.$tempId).map(u=>u.$tempId)),p=Array.from(c).filter(u=>!o.some(d=>d.$tempId===u&&d.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var We={};function re(e){return {enumerable:!0,value:e}}function Jr(e){return {enumerable:!0,writable:!0,value:e}}var no=()=>!0,Yr=()=>({}),Xr=e=>e,io=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),oo=(e,t,r,[n,s])=>t.call(r,e.call(r,n,s),s),De=(e,t)=>Object.freeze(Object.create(e,t));function Gr(e,t,r){return e.reduce((n,s)=>function(...i){return r(n,s,this,i)},t)}function Zr(e){return De(this,{fn:re(e)})}var en={},x=Zr.bind(en);var tn={},kt=Zr.bind(tn);function ht(e,t){return t.filter(r=>e.isPrototypeOf(r))}function rn(e,t,...r){let n=Gr(ht(tn,r).map(i=>i.fn),no,io),s=Gr(ht(en,r).map(i=>i.fn),Xr,oo);return De(this,{from:re(e),to:re(t),guards:re(n),reducers:re(s)})}var nn={},on={},j=rn.bind(nn);rn.bind(on,null);function so(e,t,r){return xt(t,e,r,this.immediates)||e}function sn(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 ao={enter:Xr};function ae(...e){let t=ht(nn,e),r=ht(on,e),n={final:re(e.length===0),transitions:re(sn(t))};return r.length&&(n.immediates=re(r),n.enter=re(so)),De(ao,n)}var lo={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Nt.isPrototypeOf(n)?De(an,{machine:re(n),transitions:re(this.transitions)}).enter(e,t,r):(n.then(s=>t.send({type:"done",data:s})).catch(s=>t.send({type:"error",error:s})),e)}},an={enter(e,t,r){if(t.child=$e(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,xt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function z(e,...t){let r=re(sn(t));return Nt.isPrototypeOf(e)?De(an,{machine:re(e),transitions:r}):De(lo,{fn:re(e),transitions:r})}var Nt={get state(){return {name:this.current,value:this.states[this.current]}}};function ye(e,t,r=Yr){return typeof e!="string"&&(r=t||Yr,t=e,e=Object.keys(t)[0]),We._create&&We._create(e,t),De(Nt,{context:re(r),current:re(e),states:re(t)})}function xt(e,t,r,n){let{context:s}=e;for(let{to:i,guards:a,reducers:o}of n)if(a(s,r)){e.context=o.call(e,s,r);let c=t.original||t,p=De(c,{current:re(i),original:{value:c}});We._onEnter&&We._onEnter(t,i,e.context,s,r);let u=p.state.value;return e.machine=p,e.onChange(e),u.enter(p,e,r)}}function co(e,t){let r=t.type||t,{machine:n}=e,{value:s,name:i}=n.state;return s.transitions.has(r)?xt(e,n,t,s.transitions.get(r))||n:(We._send&&We._send(r,i),n)}var uo={send(e){co(this,e);}};function $e(e,t,r,n){let s=Object.create(uo,{machine:Jr(e),context:Jr(e.context(r,n)),onChange:re(t)});return s.send=s.send.bind(s),s.machine=s.machine.state.value.enter(s.machine,s,n),s}var un=(e,t)=>{if(!t)return;let r=po(t);return fo(r,e.query)},po=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),fo=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let s=n;Object.keys(s).forEach(i=>{(s[i]===void 0||s[i]===null||isArray(s[i])&&s[i].length===0)&&(t?.returnNulls?s[i]=null:delete s[i]),s[i]===void 0&&delete s[i];}),Object.getOwnPropertySymbols(s).forEach(i=>{delete s[i];}),t?.noMetadata===!0&&Object.keys(s).forEach(i=>{i.startsWith("$")&&delete s[i];});}}));var hn=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:o})=>{if(isObject(o)){let c=o;if(!c.$thing)return;if(c.$thing){let p=N(e,c),{virtualFields:u}=p,d=c[oe];if(!d)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(t,d),f=l.$fields.map($=>$.$path),h=l.$excludedFields;u.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let g=p.dataFields?.find(m=>m.path===$);if(g?.default){let m=je({currentThing:c,fieldSchema:g,mandatoryDependencies:!0});c[$]=m;}else if(c[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete c[$];});}}})))(r):void 0;var Ke={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},ge=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let c=Object.keys(a).reduce((p,u)=>{let d=a[u];if(u.startsWith("$")){if(["$or","$and","$not"].includes(u))return {...p,[u]:void 0,[Ke[u]]:ge(d,t,r)};if(u==="$id")return {...p,$id:void 0,[Ke[u]]:{$IN:isArray(d)?d:[d]}};if(u==="$thing")return p;if(u==="$exists")return {...p,$exists:void 0,[Ke[u]]:d};if(u==="$eq")return {...p,$eq:void 0,[Ke[u]]:d};if(u==="$in")return {...p,$in:void 0,[Ke[u]]:d};throw new Error(`Unknown filter operator ${u}`)}let l=t in r.entities?r.entities[t]:r.relations[t],[f,h]=it(l,u);if(f==="idField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return {...p,"record::id(id)":{$IN:isArray(d)?d:[d]}}}if(f==="dataField")return {...p,[u]:ge(d,t,r)};if(f==="linkField"||f==="roleField"){let g=h[Le].queryPath;return {...p,[g]:ge(d,t,r)}}throw new Error(`Field ${u} not found in schema, Defined in $filter`)},{});return shake(c)});return n?i:i[0]},fe=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,s])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(s)?s.map(o=>fe(o)):[fe(s)];i==="!"?r.push(`!(${a.join(" AND ")})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(s))if(n.includes("<-")||n.includes("->")){let i=fe(s);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=fe(s),a=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=fe(s),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(s);if(i.length===1&&i[0].startsWith("$")){let[a]=i,o=s[a];if(a==="$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 c=a.replace("$","");if(Array.isArray(o))r.push(`${n} ${c} [${o.map(p=>p===null?"NONE":`'${p}'`).join(", ")}]`);else if(isObject(o)){let p=fe(o);r.push(`${n} ${c} ${p}`);}else r.push(`${n} ${c} ${o===null?"NONE":`'${o}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(s)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${s.map(a=>a===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${s===null?"NONE":`'${s}'`}`);}}),r.join(" AND ")},Ve=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:s}=r;return `${n}${s?" DESC":" ASC"}`}).join(", ")}`;var fn=e=>{let{queries:t,schema:r}=e;return t.map(n=>bo({query:n,schema:r}))},bo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push("SELECT");let u=_t({parentQuery:t,queries:s,level:1,schema:r});u&&p.push(u);let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let f=(d.subTypes?[n,...d.subTypes]:[n]).map(h=>ee(h));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=f.flatMap(g=>h?.map(m=>`${g}:\u27E8${m}\u27E9`));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(i){let h=ge(i,n,r),$=fe(h);p.push(`WHERE ${$}`);}return c&&p.push(Ve(c)),typeof o=="number"&&p.push(`LIMIT ${o}`),typeof a=="number"&&p.push(`START ${a}`),p.join(`
103
+ `,mr=e=>$i(e);var yr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([c])=>[c,await ur(c,e,t,r)]))).map(c=>[c[0],c[1]]),o=(await Promise.all([...r.surrealDB||[]].map(async([c])=>[c,mr(t)]))).map(c=>[c[0],c[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(o)}})();var oe=Symbol.for("queryPath"),tt=Symbol.for("stepPrint"),Ie=Symbol.for("edgeType"),Fe=Symbol.for("edgeSchema"),Ne=Symbol.for("dbNode"),Mt=Symbol.for("isTransformed"),rt=Symbol.for("parent"),se=Symbol.for("fieldSchema"),we=Symbol.for("sharedMetadata"),Le=Symbol.for("suqlMetadata");var gr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Er=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let s=r.relations[e.relation].subTypes||[],i=[e.relation,...s],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[o]=e.oppositeLinkFieldsPlayedBy,c=r.entities[o.thing]?.subTypes||r.relations[o.thing]?.subTypes||[],p=[o.thing,...c],u=`->\u27E8${t}_${o.plays}\u27E9->(\u27E8${p.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${a}${u}`:n==="refs"?e.cardinality==="MANY"?`$parent.[\`${o.plays}\`]`:`$parent.\`${o.plays}\``:`${a}${u}`}else throw new Error("Unsupported linkField target")};var Fr=(e,t,r)=>r?t:`${e}\xB7${t}`;var wr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],de=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,s])=>{let[i,a]=tryit(()=>t(n,s))();return i?!1:a}))},Mr=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:a,value:o,meta:c})=>{if(c.depth===2&&(a&&(o.dataFields=o.dataFields?.map(p=>({...p,...o.idFields?.includes(p.path)?{isIdField:!0}:{isIdField:!1},cardinality:p.cardinality||"ONE",dbPath:"dbPath"in p?p.dbPath:Fr(a,p.path,p.shared)}))),o.extends)){if(!o.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${c.nodePath}`);let p=i.entities[o.extends]||i.relations[o.extends],u=[o.extends,...p.allExtends||[]];if(o.allExtends=u,u.forEach(d=>{if(i.entities[d])i.entities[d].subTypes=[a,...i.entities[d].subTypes||[]];else if(i.relations[d])i.relations[d].subTypes=[a,...i.relations[d].subTypes||[]];else throw new Error(`[Schema] ${a} is extending a thing that does not exist in the schema: ${d}`)}),o.idFields=p.idFields?Array.from(new Set((o.idFields||[]).concat(p.idFields))):o.idFields,o.dataFields=p.dataFields?(o.dataFields||[]).concat(p.dataFields.map(d=>{let l=o.extends,f=e.entities[l]||e.relations[l];for(;!f.dataFields?.find(h=>h.path===d.path);)l="extends"in f?f.extends:void 0,f=e.entities[l]||e.relations[l];return {...d,inherited:!0,dbPath:"dbPath"in d?d.dbPath:Fr(l,d.path,d.shared),[we]:{inheritanceOrigin:d[we]?.inheritanceOrigin||o.extends}}})):o.dataFields,"roles"in p){let d=o,l=p;if(l.roles){let f=mapEntries(l.roles,(h,$)=>[h,{...$,inherited:!0,[we]:{inheritanceOrigin:$[we]?.inheritanceOrigin||o.extends}}]);d.roles={...d.roles||{},...f};}}o.linkFields=p.linkFields?(o.linkFields||[]).concat(p.linkFields.map(d=>({...d,inherited:!0,[we]:{inheritanceOrigin:d[we]?.inheritanceOrigin||o.extends}}))):o.linkFields,p?.hooks?.pre&&(o.hooks=o.hooks||{},o.hooks.pre=o.hooks.pre||[],o.hooks.pre=[...p?.hooks?.pre||[],...o?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:i,value:a,meta:o})=>{if(i==="linkFields"){let p=(()=>{if(!o.nodePath)throw new Error("No path");let[d,l]=o.nodePath.split(".");return {thing:l,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),u=Array.isArray(a)?a.map(d=>({...d,...p})):[{...a,...p}];r.push(...u);}}),produce(n,i=>traverse(i,({value:a,key:o,meta:c})=>{if(c.depth===2&&a.idFields&&!a.id){a.name=o;let p=()=>{if(c.nodePath?.split(".")[0]==="entities")return "entity";if(c.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=p();let u=Object.keys(t).find(d=>t[d]?.get(a.defaultDBConnector.id));if(a.db=u,a.dbContext=gr[u],a.dbProviderConfig=u==="surrealDB"?t[u]?.get(a.defaultDBConnector.id)?.providerConfig:void 0,a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"linkFields"in a&&a.linkFields){let d=a;d.linkFields?.forEach(l=>{l.fieldType="linkField";let f=n.relations[l.relation];if(!l.isVirtual){if(!f)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(f.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: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.$things=[l.relation,...f.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){if(l.oppositeLinkFieldsPlayedBy=r.filter(h=>h.relation===l.relation&&h.plays!==l.plays&&h.target==="role"),l.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${l.path}. Path:${c.nodePath}."`);l.pathToRelation=d.linkFields?.find(h=>h.target==="relation"&&h.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(h=>[h.thing,...K(n,h.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(h=>h.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(a.db==="surrealDB"){let h=f?.roles?.[l.plays][we]?.inheritanceOrigin??l.relation,$=Er({linkField:l,originalRelation:h,withExtensionsSchema:n,linkMode:a.dbProviderConfig.linkMode});l[Le]={queryPath:$};}});}if("roles"in a){let d=a;Object.entries(d.roles).forEach(([l,f])=>{f.fieldType="roleField";let h=r.filter(y=>y.relation===o&&y.plays===l)||[];f.playedBy=h.map(y=>({...y,pathToRelation:y.target==="relation"?y.path:d.linkFields?.find(R=>R.target==="relation"&&R.relation===o&&R.plays===l)?.path??y.relation.toLocaleLowerCase()}));let $=r.filter(y=>y.target==="relation"&&y.plays===l&&d.allExtends?.includes(y.relation));f.impactedLinkFields=$,f.path=l;let g=[...new Set(h.flatMap(y=>[...K(n,y.thing).subTypes||[],y.thing]).flat().filter(Boolean))];f.$things=g;let m=f[we]?.inheritanceOrigin||a.name,b=g.flatMap(y=>{let L=K(e,y)?.subTypes||[];return [y,...L]}),F=()=>{if(a.dbProviderConfig.linkMode==="edges")return `->\`${m}_${l}\`->(\`${b.join("`,`")}\`)`;if(a.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.[\`${l}\`]`;if(f.cardinality==="ONE")return `$parent.\`${l}\``}throw new Error("Unsupported linkMode")};if(a.db==="surrealDB"){let y=F();f[Le]={queryPath:y};}});}}if(a&&typeof a=="object"&&"playedBy"in a){let p=[...new Set(a.playedBy.map(u=>u.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${o}, path:${c.nodePath}, played by: ${p.join(", ")}`),a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${o}, path:${c.nodePath}`)}if(c.depth===4){let[p,u]=c.nodePath?.split(".")||[],d=i[p][u];!isArray(a)&&typeof a=="object"&&(a.validations&&(a.validations.required&&d.requiredFields.push(a.path),a.validations.enum&&d.enumFields.push(a.path),a.validations.fn&&d.fnValidatedFields.push(a.path)),a.default?a.isVirtual?d.virtualFields.push(a.path):d.computedFields.push(a.path):a.isVirtual&&d.virtualFields.push(a.path));}}))},K=(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`)},N=(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)}`)},it=(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 s="roles"in e?e.roles[t]:void 0;if(s)return ["roleField",s];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},ot=(e,t)=>{let r=N(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},Sr=(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=N(e,t),s=n.linkFields?.find(o=>o.path===r);if(s)return s;let i=n.dataFields?.find(o=>o.path===r);if(i)return i;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},Rt=(e,t,r)=>Qt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],n=e.linkFields?.map(h=>h.path)||[],s="roles"in e?listify(e.roles,h=>h):[],i=[...r||[],...n||[],...s||[]],o=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!t)return {fields:i,dataFields:r,roleFields:s,linkFields:n};let c=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!i.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!i.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),p=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],u=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...s||[],...n||[]].includes(h)):[],d=[...c,...p].filter(h=>!h?.startsWith("%")).filter(h=>!o.includes(h)).filter(h=>h),l=t.$filter?de(t.$filter,(h,$)=>p.includes(h)):{},f=t.$filter?de(t.$filter,(h,$)=>u.includes(h)):{};return {fields:i,dataFields:r,roleFields:s,linkFields:n,usedFields:c,usedLinkFields:n.filter(h=>c.includes(h)),usedRoleFields:s.filter(h=>c.includes(h)),usedDataFields:r.filter(h=>c.includes(h)),unidentifiedFields:d,...p.length?{localFilters:l}:{},...u.length?{nestedFilters:f}:{}}};var Lr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Qr=(e,t,r)=>{let s=(r.nodePath||"").split("."),i=isArray(t)?s.slice(0,-2).join("."):s.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},Qe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var st=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Te=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,s])=>{r[n]=isDraft(s)?current(s):s;}),r}else return e},pe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Ae=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var xe=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Dr=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(!n.every(s=>typeof s=="object"))if(n.every(s=>typeof s=="string")){let s=xe(t,r),[i]=s,a=e.$op==="create"?"link":"replace",o=i.thing,c=i.thingType,p={$op:a,$thing:o,$thingType:c},u=n.filter(l=>l.startsWith("_:")),d=n.filter(l=>!l.startsWith("_:"));u.length&&!d.length?e[t]=u.map(l=>({...p,$tempId:l,$bzId:l})):u.length&&d.length?e[t]=[...u.map(l=>({...p,$tempId:l,$bzId:l})),{...p,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...p,$id:e[t],$bzId:`S_${nanoid()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(n)} Parent: ${JSON.stringify(e,null,2)})`)};var Oe=(e,t,r)=>{let n=N(r,t),{usedDataFields:s}=ue(n,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&s.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&s.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var at=(e,t,r)=>{let n=N(r,t),{usedFields:s}=ue(n,t);return t.$op?(Oe(e,t,r),t.$op):t.$id||t.$filter?s.length>0?(Oe(e,{...t,$op:"update"},r),"update"):(Oe(e,{...t,$op:"link"},r),"link"):t.$tempId?s.length>0?(Oe(e,{...t,$op:"create"},r),"create"):(Oe(e,{...t,$op:"create"},r),"link"):(Oe(e,{...t,$op:"create"},r),"create")};var Ir=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(s=>{let i=at(s,s,t);return {...{...s.$thing?{}:{$thing:s.$entity||s.$relation},...s.$thingType?{}:{$thingType:Sr(s,t)},...s.$op?{}:{$op:i},...s.$bzId?{}:{$bzId:`R_${Ae()}`}},...s}});e.$root=isArray(e.$root)?n:n[0];};var lt=(e,t)=>{let r=t[tt];return isSet(r)?r.has("clean")?(Reflect.set(t,tt,r.add("clean")),!0):!1:(Reflect.set(t,tt,new Set(["clean"])),!0)};var Ar=(e,t,r)=>{if(lt("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(s=>{if(isObject(s)&&"$id"in s&&isArray(s.$id)){let i=s;if(N(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,o)=>({...Te(i),$id:a,$bzId:`${i.$bzId}_${o}`,...Qe(i)}))}return s});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Or=(e,t,r,n)=>{let s=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=xe(t,r),[o]=a,c=at(e,{...i,$thing:o.thing,$thingType:o.thingType},n),u=i.$bzId?i.$bzId:i.$tempId?i.$tempId:i.$id&&!isArray(i.$id)?`SN_ONE_${o.thing}_${i.$id}`:i.$id&&isArray(i.$id)?`SN_MANY_${o.thing}_${Ae()}`:`SM_${Ae()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[Fe]:r,$thing:o.thing,$thingType:o.thingType,$op:c,$bzId:u}});e[t]=isArray(e[t])?s:s[0];};var Ii=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Ai=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,qr=e=>{let r=e.toString().replace(Ii,"").trim().split("=>")[0].split("{")[0].replace(Ai,"").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 je=({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=qr(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 Pr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(s=>{let i=N(r,s),{unidentifiedFields:a}=ue(i,s),{computedFields:o,virtualFields:c}=i,p=listify(s,(l,f)=>f!==void 0?l:void 0),u=p.filter(l=>c?.includes(l));if(u.length>0)throw new Error(`Virtual fields can't be sent to DB: "${u.join(",")}"`);if(o.filter(l=>!p.includes(l)).forEach(l=>{let f=i.dataFields?.find(b=>b.path===l),$=i.linkFields?.find(b=>b.path===l)?.oppositeLinkFieldsPlayedBy[0],g="roles"in i?wr(i.roles,(b,F)=>b===l):void 0,m=f||$||g;if(!m)throw new Error(`no field Def for ${l}`);if(s.$op==="create"&&!s[l]){let b=je({currentThing:s,fieldSchema:m,mandatoryDependencies:!0});s[l]=b;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(s)}`)}),e};var dt=(e,t)=>{let r=N(t,e).hooks;if(r?.pre){let n=`on${Lr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var Nr=(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:o,fnValidatedFields:c,dataFields:p}=N(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(u=>{if(!(u in i))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&o.forEach(u=>{if(u in i){let d=p?.find(l=>l.path===u)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(i[u]))i[u].some(l=>{if(!d.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(d&&!d.includes(i[u]))throw new Error(`[Validations] Option "${i[u]}" is not a valid option for field "${u}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&c.forEach(u=>{if(u in i)try{let d=p?.find(l=>l.path===u)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(i[u]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${u}] ${d.message}`)}}),isObject(i)&&"$thing"in i){let u=i.$thing,d=i,l=clone(Te(e)),f=clone(Te(d)),h=n.mutation?.context||{},$=clone(Te(i[Ne]||{}));dt(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let b=m.fn(f,l,h,$);if(b===!1)throw new Error(`${m.message}.`);if(b!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(b){throw new Error(`[Validations:thing:${u}] ${b.message}`)}}});}}});};var xr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if(!st(i)||i.$fields||i[Mt])return;let a=dt(i,r).filter(d=>d.type==="transform"),o=clone(Te(e)),c=clone(Te(i)),p=n.mutation?.context||{},u=clone(Te(i[Ne]||i.$dbNode));a.forEach(d=>{let l=d.fn(c,o,p,u||{});Object.keys(l).length!==0&&(c={...c,...l,...Qe(i),[Mt]:!0},Object.assign(i,c));});});};var jr=(e,t,r)=>{let n=xe(t,r),[s]=n;e[t]={$thing:s.thing,$thingType:s.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Fe]:r};};var _e=e=>{if(Array.isArray(e)){for(let t of e)if(_e(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"&&_e(e[t]))return !0}return !1};var Ur=(e,t)=>{for(let s of e)if(!("$entity"in s)&&!("$relation"in s)&&(!("$thing"in s)||!("$thingType"in s)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,s=>traverse(s,i=>{let{value:a,meta:o}=i,c=a;if(isObject(c)){if(c.$id){if(o.nodePath?.includes(".$filter"))return;let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},u=N(t,p);if(!u?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=u.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),u?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let p=N(t,c);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=p.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c&&c.$thing){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[oe]=o.nodePath;let u=N(t,p);if(c.$filter&&(Object.keys(c.$filter).length===0?c.$filter=void 0:(c.$filter=Re(c.$filter,c.$thing,t),c.$filterByUnique=Ot(c.$filter,u))),c.$fields){c.$fields.some(f=>u?.idFields?.includes(f?.$path||f))||(c.$fields=[...c.$fields,...Array.isArray(u.idFields)?u.idFields:[]],c.$idNotIncluded=!0);let l=c.$fields?.flatMap(f=>{let h=_r(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}else {let l=At(u)?.flatMap(f=>{let h=_r(f,u,t);return Array.isArray(h)?h:[h]}).filter(Boolean);c.$fields=l;}c.$excludedFields&&(c.$fields=c.$fields.filter(d=>ut(u,d)?!0:!c.$excludedFields.includes(d.$path)));}}}))},At=e=>{let t=e.dataFields?.map(i=>i.path)||[],r=e.linkFields?.map(i=>i.path)||[],n=Object.keys(e.roles||{})||[];return [...t,...r,...n]},Ot=(e,t)=>Object.keys(e||{}).some(n=>{let s=e[n];if(s!==null&&typeof s<"u"){let i=t.idFields?.includes(n),a=t.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique),o=n==="$id"&&!Array.isArray(s);if(i||a||o){if(typeof s!="object"||s===null||Array.isArray(s))return !Array.isArray(s);{let p=Object.keys(s);if(p.length===1&&p[0]==="$eq"){let u=s.$eq;if(typeof u!="object"||u===null||!Array.isArray(u))return !0}return !1}}}return !1}),ut=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),_i=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:s,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:s,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[se]:a}},Ui=e=>{let{field:t,fieldStr:r,linkField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e,{target:c,oppositeLinkFieldsPlayedBy:p}=n;return p.map(u=>{let d=c==="role"?u.thingType:"relation",l=c==="role"?u.thing:n.relation,f={[`$${d}`]:l},h=N(a,f),$=t?.$fields?.filter(b=>ut(h,b)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let b=h.idFields||[];g=[...t.$fields,...b];}else g=t.$fields;else g=At(h);else g=["id"];t.$excludedFields&&(g=g.filter(b=>ut(h,b)?!0:!t.$excludedFields.includes(b.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:d,$plays:n.plays,$playedBy:{...u,oppositeLinkFieldsPlayedBy:void 0},$path:u.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:l,$fields:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:c,$intermediary:u.relation,$justId:s,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Ot(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[se]:o}})},Wi=e=>{let{field:t,fieldStr:r,roleField:n,$justId:s,dbPath:i,schema:a,fieldSchema:o}=e;return n.playedBy.map(c=>{let{thing:p,thingType:u,relation:d}=c,l={[`$${u}`]:p},f=N(a,l),h=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=At(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>ut(f,m)?!0:!t.$excludedFields.includes(m.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:s,$id:t.$id,$filter:g,$idNotIncluded:h,$filterByUnique:Ot(t.$filter,f),$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[se]:o}})},_r=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,s=typeof e=="string",i=t.dataFields?.find(c=>c.path===n),a=t.linkFields?.find(c=>c.path===n),o=t.roles?.[n];if(i){let c=!!i.isVirtual&&!!i.default;return _i({field:e,fieldStr:n,$justId:s,dbPath:i.dbPath,isVirtual:c,fieldSchema:i})}else {if(a)return Ui({field:e,fieldStr:n,linkField:a,$justId:s,dbPath:a.path,schema:r,fieldSchema:a});if(o)return Wi({field:e,fieldStr:n,roleField:o,$justId:s,dbPath:n,schema:r,fieldSchema:o})}return null},Re=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce((p,u)=>{let d=a[u],l=isArray(d)?d:[d];if(u.startsWith("$"))if(["$id","$thing"].includes(u))p[u]=d;else if(["$not","$or","$and"].includes(u))p[u]=Re(d,t,r);else if(["$eq","$in","$exists"].includes(u))p[u]=d;else throw new Error(`[Internal] Unknown filter operator ${u}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[h,$]=it(f,u);if(h==="idField")p[u]=d;else if(h==="dataField")isObject(d)||isArray(d)&&d.some(isObject)?p[u]=isArray(d)?{$or:Re(d,t,r)}:Re(d,t,r):isArray(d)?p[u]={$in:d}:p[u]={$eq:d};else if(h==="linkField"||h==="roleField"){let g=$,[m]=g.$things;l.every(b=>typeof b=="string")?p[u]={$id:l,$thing:m}:l.every(b=>isObject(b))&&(p[u]=isArray(d)?{$or:Re(d,m,r)}:Re(d,m,r));}else throw new Error(`Field ${u} not found in schema of ${t}`)}return p},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var Ji=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(lt("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);},Yi=(e,t)=>{},Pt=(e,t,r)=>{let n={$rootWrap:{$root:e}},s=_e(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:o,parent:c,key:p,meta:u})=>{if(!(!c||!p)&&isObject(o)){let d=u.nodePath?.split(".")||[];if(d.some(h=>h.startsWith("%")))return;if(!("$root"in o)){if(!("$thing"in o||"$entity"in o||"$relation"in o)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],g=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(g)&&!$.startsWith("%")&&!g.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(o)?current(o):o)}`)}}let l=o,f=d.includes("$filter");"$filter"in l&&l.$filter&&(l.$filter=Re(l.$filter,l.$thing,t)),Object.keys(l).forEach(h=>{if(Ji(l,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?Qt(t,l,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Yi();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(l[h]===null?jr(l,h,$):Dr(l,h,$)),$.fieldType==="rootField"){if(!("$root"in l))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Ir(l,t);}let g=isArray(l[h])?l[h]:[l[h]],m=d.slice(1).join(".");g.forEach(F=>{if(F){if($?.cardinality==="ONE"&&!F.$op&&!F.$id&&!F.$filter&&!F.$tempId&&l.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(F.$tempId&&!(F.$op===void 0||F.$op==="link"||F.$op==="create"||F.$op==="update"))throw new Error(`Invalid op ${F.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&Or(l,h,$,t),Ar(l,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&Pr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(F=>{let y=N(t,F),{unidentifiedFields:R,usedLinkFields:L,usedFields:D,fields:C}=ue(y,F);if(D.forEach(_=>{if(!C.includes(_))throw new Error(`[Schema] Field ${_} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(o)}`);if(L.length>1){let _=y.linkFields?.filter(J=>L.includes(J.path));_?.some((J,he)=>_.some((v,I)=>{if(he!==I&&J.target!==v.target&&J.relation===v.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),s||(xr(l,h,t,r),Nr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var Wr=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 vr=async(e,t)=>{let r=u=>{let d=[],l=[],f=m=>{if(m.$id)return m.$id;let b=N(t,m),{idFields:F}=b;if(!F)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[y]=F;if(!y)throw new Error(`no idField: ${JSON.stringify(m)}`);let R=b.dataFields?.find(C=>C.path===y),L=je({currentThing:m,fieldSchema:R,mandatoryDependencies:!0}),D=m[y]||m.$id||L;if(!D)throw new Error(`no idValue: ${JSON.stringify(m)}`);return D},h=m=>{if(m.$op==="create"){let b=f(m);if(d.find(F=>F.$id===b&&F.$op==="create"))throw new Error(`Duplicate id ${b} for node ${JSON.stringify(m)}`);d.push({...m,$id:b});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let b=f(m);if(d.find(F=>F.$id===b&&F.$op==="create"))throw new Error(`Duplicate id ${b} for edge ${JSON.stringify(m)}`);l.push({...m,$id:b});return}l.push(m);};return traverse(u,({value:m,parent:b,meta:F})=>{if(!isObject(m))return;let y=m;if(!F.nodePath?.includes(".$filter")&&y.$thing){if(!y.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(y)}`);if(!y.$bzId)throw new Error("[internal error] BzId not found");let R=N(t,y),{dataFields:L,roleFields:D,linkFields:C,usedFields:_}=ue(R,y),J=()=>{if(y.$op==="create"||y.$op==="delete")return y.$op;if(y.$op==="update"){let I=_.filter(B=>L?.includes(B)),k=_.filter(B=>D?.includes(B)),E=_.filter(B=>C?.includes(B));if(I.length>0)return "update";if(k.length>0||E.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(y)}`)}return "match"},he={...y.$id&&{$id:y.$id},...y.$tempId&&{$tempId:y.$tempId},...y.$filter&&{$filter:y.$filter},$thing:y.$thing,...y.$thingType&&{$thingType:y.$thingType},...shake(pick(y,L||[""])),$op:J(),$bzId:y.$bzId};h(he);let v=y[Fe];if(v?.fieldType==="linkField"){if((y.$op==="link"||y.$op==="unlink")&&(y.$id||y.$filter)){if(y.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...y,$op:"match"});}let I=v.relation===y.$thing,k=I?y.$bzId:`LT_${v4()}`,B=Qr(u,b,F).$bzId;if(!B)throw new Error("No parent id found");let T=()=>y.$op==="delete"?I?"match":"delete":y.$op==="unlink"?I?"unlink":"delete":y.$op==="link"||y.$op==="create"?I?"link":"create":y.$op==="replace"?"replace":"match",S=N(t,{$thing:v.relation,$thingType:"relation"});if(!Object.keys(S.roles).includes(v.plays))throw new Error(`[Wrong format] Field ${v.plays} is not a role of relation ${v.relation}`);let Q={$bzId:k,$thing:v.relation,$thingType:"relation",...y.$tempId?{$tempId:y.$tempId}:{},$op:T(),...I?{}:{[v.path]:y.$bzId},[v.plays]:B,[Fe]:v,[Ie]:"linkField"};$(Q),(y.$op==="unlink"||T()==="unlink")&&I&&$({$thing:v.relation,$thingType:"relation",$bzId:k,$op:"match",[v.plays]:B,[Fe]:v,[Ie]:"linkField"});}if(y.$thingType==="relation"){let I=de(y,(B,T)=>D.includes(B)),k=mapEntries(I,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),E=de(m,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(I).filter(B=>!B.startsWith("$")).length>0){if(y.$op==="create"||y.$op==="delete"){let B=()=>{if(y.$op==="create")return "link";if(y.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=N(t,y).roles,S=mapEntries(k,(Q,A)=>{let U=T[Q]?.cardinality;if(!U)throw new Error(`Role ${Q} not found in schema`);if(Array.isArray(A)){if(U==="ONE"){if(A.length>1)throw new Error(`[Error] Role ${Q} is not a MANY relation`);return [Q,A[0].$bzId||A[0]]}return [Q,A.map(q=>q.$bzId||q)]}return [Q,A.$bzId||A]}),w={...E,$thing:y.$thing,$thingType:"relation",$op:B(),...S,$bzId:y.$bzId,[Ie]:"roleField"};$(w);return}if(y.$op==="match"||y.$op==="update"&&Object.keys(I).length>0){let B=0;Object.entries(I).forEach(([T,S])=>{let w=isArray(S)?S:[S],Q=A=>A==="create"||A==="replace"?"link":A;w.forEach(A=>{if(!A)return;let U=Q(A.$op);if(U==="replace")throw new Error("Not supported yet: replace on roleFields");if(U==="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 q={...E,$thing:y.$thing,$thingType:"relation",$op:U==="delete"?"unlink":U,[T]:A.$bzId,$bzId:y.$bzId,[Ie]:"roleField"};$(q);});});}}}}}),[d,l]},[n,s]=r(e),i=n.reduce((u,d)=>{if(!d.$bzId)return [...u,d];let l=u.findIndex(f=>f.$bzId===d.$bzId);if(l===-1)return [...u,d];if(u[l].$op==="create"&&d.$op==="match")return u;if(u[l].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...u.slice(0,l),d,...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d},...u.slice(l+1)];if(u[l].$op==="update"&&d.$op==="match"||u[l].$op==="match"&&d.$op==="update")return [...u.slice(0,l),{...u[l],...d,$op:"update"},...u.slice(l+1)];if(u[l].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(u[l].$filter)===JSON.stringify(d.$filter))return u;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${u[l].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${u[l].$op}. Current: ${d.$op}`)},[]),a=s.reduce((u,d)=>{let l=u.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(l){let f={...l};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=l[$],m=d[$];Array.isArray(g)&&Array.isArray(m)?f[$]=Array.from(new Set([...g,...m])):!Array.isArray(g)&&Array.isArray(m)?g!==void 0?f[$]=Array.from(new Set([g,...m])):f[$]=m:Array.isArray(g)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...g,m]))):g!==null&&m!==null&&g!==void 0&&m!==void 0?f[$]=Array.from(new Set([g,m])):g==null&&(f[$]=m);}),[...u.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...u,d]},[]);i.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&a.filter(d=>d.$bzId===u.$bzId||d.$tempId&&d.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Wr(u))}`)}});let o=[...i,...a],c=new Set(o.filter(u=>u.$tempId).map(u=>u.$tempId)),p=Array.from(c).filter(u=>!o.some(d=>d.$tempId===u&&d.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var We={};function re(e){return {enumerable:!0,value:e}}function Kr(e){return {enumerable:!0,writable:!0,value:e}}var no=()=>!0,Jr=()=>({}),Gr=e=>e,io=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),oo=(e,t,r,[n,s])=>t.call(r,e.call(r,n,s),s),De=(e,t)=>Object.freeze(Object.create(e,t));function Yr(e,t,r){return e.reduce((n,s)=>function(...i){return r(n,s,this,i)},t)}function Xr(e){return De(this,{fn:re(e)})}var Zr={},x=Xr.bind(Zr);var en={},kt=Xr.bind(en);function ht(e,t){return t.filter(r=>e.isPrototypeOf(r))}function tn(e,t,...r){let n=Yr(ht(en,r).map(i=>i.fn),no,io),s=Yr(ht(Zr,r).map(i=>i.fn),Gr,oo);return De(this,{from:re(e),to:re(t),guards:re(n),reducers:re(s)})}var rn={},nn={},j=tn.bind(rn);tn.bind(nn,null);function so(e,t,r){return xt(t,e,r,this.immediates)||e}function on(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 ao={enter:Gr};function ae(...e){let t=ht(rn,e),r=ht(nn,e),n={final:re(e.length===0),transitions:re(on(t))};return r.length&&(n.immediates=re(r),n.enter=re(so)),De(ao,n)}var lo={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Nt.isPrototypeOf(n)?De(sn,{machine:re(n),transitions:re(this.transitions)}).enter(e,t,r):(n.then(s=>t.send({type:"done",data:s})).catch(s=>t.send({type:"error",error:s})),e)}},sn={enter(e,t,r){if(t.child=$e(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,xt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function z(e,...t){let r=re(on(t));return Nt.isPrototypeOf(e)?De(sn,{machine:re(e),transitions:r}):De(lo,{fn:re(e),transitions:r})}var Nt={get state(){return {name:this.current,value:this.states[this.current]}}};function ye(e,t,r=Jr){return typeof e!="string"&&(r=t||Jr,t=e,e=Object.keys(t)[0]),We._create&&We._create(e,t),De(Nt,{context:re(r),current:re(e),states:re(t)})}function xt(e,t,r,n){let{context:s}=e;for(let{to:i,guards:a,reducers:o}of n)if(a(s,r)){e.context=o.call(e,s,r);let c=t.original||t,p=De(c,{current:re(i),original:{value:c}});We._onEnter&&We._onEnter(t,i,e.context,s,r);let u=p.state.value;return e.machine=p,e.onChange(e),u.enter(p,e,r)}}function co(e,t){let r=t.type||t,{machine:n}=e,{value:s,name:i}=n.state;return s.transitions.has(r)?xt(e,n,t,s.transitions.get(r))||n:(We._send&&We._send(r,i),n)}var uo={send(e){co(this,e);}};function $e(e,t,r,n){let s=Object.create(uo,{machine:Kr(e),context:Kr(e.context(r,n)),onChange:re(t)});return s.send=s.send.bind(s),s.machine=s.machine.state.value.enter(s.machine,s,n),s}var dn=(e,t)=>{if(!t)return;let r=po(t);return fo(r,e.query)},po=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),fo=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let s=n;Object.keys(s).forEach(i=>{(s[i]===void 0||s[i]===null||isArray(s[i])&&s[i].length===0)&&(t?.returnNulls?s[i]=null:delete s[i]),s[i]===void 0&&delete s[i];}),Object.getOwnPropertySymbols(s).forEach(i=>{delete s[i];}),t?.noMetadata===!0&&Object.keys(s).forEach(i=>{i.startsWith("$")&&delete s[i];});}}));var un=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:o})=>{if(isObject(o)){let c=o;if(!c.$thing)return;if(c.$thing){let p=N(e,c),{virtualFields:u}=p,d=c[oe];if(!d)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(t,d),f=l.$fields.map($=>$.$path),h=l.$excludedFields;u.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let g=p.dataFields?.find(m=>m.path===$);if(g?.default){let m=je({currentThing:c,fieldSchema:g,mandatoryDependencies:!0});c[$]=m;}else if(c[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete c[$];});}}})))(r):void 0;var Ke={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},ge=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let c=Object.keys(a).reduce((p,u)=>{let d=a[u];if(u.startsWith("$")){if(["$or","$and","$not"].includes(u))return {...p,[u]:void 0,[Ke[u]]:ge(d,t,r)};if(u==="$id")return {...p,$id:void 0,[Ke[u]]:{$IN:isArray(d)?d:[d]}};if(u==="$thing")return p;if(u==="$exists")return {...p,$exists:void 0,[Ke[u]]:d};if(u==="$eq")return {...p,$eq:void 0,[Ke[u]]:d};if(u==="$in")return {...p,$in:void 0,[Ke[u]]:d};throw new Error(`Unknown filter operator ${u}`)}let l=t in r.entities?r.entities[t]:r.relations[t],[f,h]=it(l,u);if(f==="idField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return {...p,"record::id(id)":{$IN:isArray(d)?d:[d]}}}if(f==="dataField")return {...p,[u]:ge(d,t,r)};if(f==="linkField"||f==="roleField"){let g=h[Le].queryPath;return {...p,[g]:ge(d,t,r)}}throw new Error(`Field ${u} not found in schema, Defined in $filter`)},{});return shake(c)});return n?i:i[0]},fe=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,s])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(s)?s.map(o=>fe(o)):[fe(s)];i==="!"?r.push(`!(${a.join(" AND ")})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(s))if(n.includes("<-")||n.includes("->")){let i=fe(s);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=fe(s),a=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=fe(s),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(s);if(i.length===1&&i[0].startsWith("$")){let[a]=i,o=s[a];if(a==="$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 c=a.replace("$","");if(Array.isArray(o))r.push(`${n} ${c} [${o.map(p=>p===null?"NONE":`'${p}'`).join(", ")}]`);else if(isObject(o)){let p=fe(o);r.push(`${n} ${c} ${p}`);}else r.push(`${n} ${c} ${o===null?"NONE":`'${o}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(s)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${s.map(a=>a===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${s===null?"NONE":`'${s}'`}`);}}),r.join(" AND ")},Ve=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:s}=r;return `${n}${s?" DESC":" ASC"}`}).join(", ")}`;var pn=e=>{let{queries:t,schema:r}=e;return t.map(n=>bo({query:n,schema:r}))},bo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push("SELECT");let u=_t({parentQuery:t,queries:s,level:1,schema:r});u&&p.push(u);let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let f=(d.subTypes?[n,...d.subTypes]:[n]).map(h=>ee(h));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=f.flatMap(g=>h?.map(m=>`${g}:\u27E8${m}\u27E9`));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(i){let h=ge(i,n,r),$=fe(h);p.push(`WHERE ${$}`);}return c&&p.push(Ve(c)),typeof o=="number"&&p.push(`LIMIT ${o}`),typeof a=="number"&&p.push(`START ${a}`),p.join(`
104
104
  `)},_t=e=>{let{queries:t,schema:r,level:n,parentQuery:s}=e,i=[],a=s[oe];return i.push(M(`"${a}" as \`$$queryPath\``,n)),i.push(M("record::id(id) as `$id`",n)),i.push(M("record::tb(id) as `$thing`",n)),t.forEach(o=>{let c=Fo({query:o,level:n,schema:r});c&&i.push(c);}),i.length===0?null:i.join(`,
105
105
  `)},Fo=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?To({query:t,level:n}):t.$fieldType==="link"?wo({query:t,level:n,schema:r}):t.$fieldType==="role"?Mo({query:t,level:n,schema:r}):null},To=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},wo=e=>{let{query:t,schema:r,level:n}=e,{$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push(M("(",n));let u=n+1;p.push(M("SELECT",u));let d=_t({parentQuery:t,queries:s,level:u+1,schema:r});d&&p.push(d);let l=t[se][Le].queryPath;if(p.push(M(`FROM ${l}`,u)),i){let f=ge(i,t.$thing,r),h=fe(f);p.push(`WHERE ${h}`);}return c&&p.push(M(Ve(c),u)),typeof o=="number"&&p.push(M(`LIMIT ${o}`,u)),typeof a=="number"&&p.push(M(`START ${a}`,u)),p.push(M(`) AS \`${t.$as}\``,n)),p.join(`
106
106
  `)},Mo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let s=[];s.push(M("(",n));let i=n+1;s.push(M("SELECT",i));let a=i+1,o=_t({parentQuery:t,queries:t.$fields,level:a,schema:r});o&&s.push(o);let c=t[se][Le].queryPath;if(s.push(M(`FROM ${c}`,i)),t.$filter){let p=ge(t.$filter,t.$playedBy.thing,r),u=fe(p);s.push(`WHERE ${u}`);}return s.push(M(`) AS \`${t.$as}\``,n)),s.join(`
107
- `)};var ne="0.11.23";var $n=async e=>{let{client:t,queries:r,config:n}=e,s=`
107
+ `)};var ne="0.11.24";var fn=async e=>{let{client:t,queries:r,config:n}=e,s=`
108
108
  BEGIN TRANSACTION;
109
109
  ${r.join(";")};
110
110
  COMMIT TRANSACTION;
111
- `;return n.query?.debugger&&console.log(`batchedQuery[${ne}]`,JSON.stringify({batchedQuery:s})),await t.query(s)};var yn=e=>{let{res:t,queries:r}=e;return t.map((s,i)=>gn(r[i],s))},gn=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Ut(e,t[0])}if(t.length>=1)return t.map(r=>Ut(e,r))}else throw new Error("res is unexpectedly not an array")},Ut=(e,t)=>{let r={[oe]:t.$$queryPath,$id:t.$id,$thing:hr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(n=>{let s=n.$as,i=t[s];n.$path==="id"&&e.$idNotIncluded||(r[s]=Lo(n,i));}),r},Lo=(e,t)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:r}=e[se];return e[se].cardinality==="ONE"&&mn(t,r),mn(t,r)??null}return e.$justId?e.$filterByUnique||e[se].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[se].cardinality==="ONE"?Ut(e,t[0]):gn(e,t)},mn=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(s=>new Date(s).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(s=>isDate(s)?new Date(s).toISOString():s);return isArray(e)?n:n[0]}return e};var En=e=>{let{queries:t,schema:r}=e;return t.map(n=>Qo({query:n,schema:r}))},Qo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=r.entities[n]||r.relations[n];if(!p)throw new Error(`Schema for ${n} not found`);let u=t[oe],d=Bn(u),l=bn(s.filter(y=>y.$fieldType==="data")),f=Fn(s.filter(y=>y.$fieldType==="link"||y.$fieldType==="role"),r),h=[...d,...l,...f].join(`,
112
- `),$=Ro(t,p),g=i?`WHERE id AND (${fe(ge(i,n,r))})`:"WHERE id",m=c?Ve(c):"",b=typeof o=="number"?`LIMIT ${o}`:"",F=typeof a=="number"?`START ${a}`:"";return `SELECT ${h} ${$} ${g} ${m} ${b} ${F}`},Ro=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(a=>ee(a)),s=(a,o)=>`${a}:\`${o}\``,i=a=>n.flatMap(o=>a.map(c=>s(o,c))).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")},Bn=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],bn=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}\``),Fn=(e,t)=>e.map(r=>{let n=Bn(r[oe]),s=bn(r.$fields.filter(l=>l.$fieldType==="data")),i=Fn(r.$fields.filter(l=>l.$fieldType==="link"||l.$fieldType==="role"),t),a=[...n,...s,...i].join(`,
113
- `),o=`FROM $parent.\`${r[se].path}\`[*]`,c=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${fe(ge(r.$filter,r.$thing,t))})`:"WHERE id",p=r.$sort?Ve(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${o} ${c} ${p} ${u} ${d} ) AS \`${r.$as}\``}).filter(r=>r);var Wt=j("error","error",x((e,t)=>({...e,error:t.error}))),Do=ye("build",{build:z(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return fn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return En({queries:e.bql.queries,schema:e.schema})},j("done","run",x((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Wt),run:z(async e=>$n({client:e.client,queries:pe(e.surql.queries),config:e.config}),j("done","parse",x((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Wt),parse:z(async e=>yn({res:pe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),j("done","success",x((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Wt),success:ae(),error:ae()},e=>e),Co=async e=>new Promise((t,r)=>{$e(Do,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Tn=async(e,t,r,n)=>Co({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var pt=e=>{let{$filter:t,$var:r,$thing:n,schema:s,depth:i}=e,a=qo(t,K(s,n)),{$not:o,...c}=a,p=[];if(zt(o)){let d=Vt(o,r,n,s,i,!0);p.push(...d);}else if(o!==void 0)throw new Error("$not must be a PositiveFilter object");let u=Vt(c,r,n,s,i,!1);return p.push(...u),p.join(`
111
+ `;return n.query?.debugger&&console.log(`batchedQuery[${ne}]`,JSON.stringify({batchedQuery:s})),await t.query(s)};var mn=e=>{let{res:t,queries:r}=e;return t.map((s,i)=>yn(r[i],s))},yn=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Ut(e,t[0])}if(t.length>=1)return t.map(r=>Ut(e,r))}else throw new Error("res is unexpectedly not an array")},Ut=(e,t)=>{let r={[oe]:t.$$queryPath,$id:t.$id,$thing:hr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(n=>{let s=n.$as,i=t[s];n.$path==="id"&&e.$idNotIncluded||(r[s]=Lo(n,i));}),r},Lo=(e,t)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:r}=e[se];return e[se].cardinality==="ONE"&&$n(t,r),$n(t,r)??null}return e.$justId?e.$filterByUnique||e[se].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[se].cardinality==="ONE"?Ut(e,t[0]):yn(e,t)},$n=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(s=>new Date(s).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(s=>isDate(s)?new Date(s).toISOString():s);return isArray(e)?n:n[0]}return e};var gn=e=>{let{queries:t,schema:r}=e;return t.map(n=>Qo({query:n,schema:r}))},Qo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=r.entities[n]||r.relations[n];if(!p)throw new Error(`Schema for ${n} not found`);let u=t[oe],d=En(u),l=Bn(s.filter(y=>y.$fieldType==="data")),f=bn(s.filter(y=>y.$fieldType==="link"||y.$fieldType==="role"),r),h=[...d,...l,...f].join(`,
112
+ `),$=Ro(t,p),g=i?`WHERE id AND (${fe(ge(i,n,r))})`:"WHERE id",m=c?Ve(c):"",b=typeof o=="number"?`LIMIT ${o}`:"",F=typeof a=="number"?`START ${a}`:"";return `SELECT ${h} ${$} ${g} ${m} ${b} ${F}`},Ro=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(a=>ee(a)),s=(a,o)=>`${a}:\`${o}\``,i=a=>n.flatMap(o=>a.map(c=>s(o,c))).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")},En=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],Bn=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}\``),bn=(e,t)=>e.map(r=>{let n=En(r[oe]),s=Bn(r.$fields.filter(l=>l.$fieldType==="data")),i=bn(r.$fields.filter(l=>l.$fieldType==="link"||l.$fieldType==="role"),t),a=[...n,...s,...i].join(`,
113
+ `),o=`FROM $parent.\`${r[se].path}\`[*]`,c=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${fe(ge(r.$filter,r.$thing,t))})`:"WHERE id",p=r.$sort?Ve(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${o} ${c} ${p} ${u} ${d} ) AS \`${r.$as}\``}).filter(r=>r);var Wt=j("error","error",x((e,t)=>({...e,error:t.error}))),Do=ye("build",{build:z(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return pn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return gn({queries:e.bql.queries,schema:e.schema})},j("done","run",x((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Wt),run:z(async e=>fn({client:e.client,queries:pe(e.surql.queries),config:e.config}),j("done","parse",x((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Wt),parse:z(async e=>mn({res:pe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),j("done","success",x((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Wt),success:ae(),error:ae()},e=>e),Co=async e=>new Promise((t,r)=>{$e(Do,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Fn=async(e,t,r,n)=>Co({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var pt=e=>{let{$filter:t,$var:r,$thing:n,schema:s,depth:i}=e,a=qo(t,K(s,n)),{$not:o,...c}=a,p=[];if(zt(o)){let d=Vt(o,r,n,s,i,!0);p.push(...d);}else if(o!==void 0)throw new Error("$not must be a PositiveFilter object");let u=Vt(c,r,n,s,i,!1);return p.push(...u),p.join(`
114
114
  `)},Vt=(e,t,r,n,s,i)=>{let a=K(n,r),o=[];for(let[c,p]of Object.entries(e)){if(c.startsWith("$")){let l=c.toLowerCase();if(l==="$and"||l==="$or"){let h=(isArray(p)?p:[p]).map(g=>{if(zt(g))return Vt(g,t,r,n,s+1,i).join(`
115
115
  `);throw new Error(`Invalid subfilter in ${l}: ${JSON.stringify(g)}`)}),$=h.join(l==="$and"?`
116
- `:" } or { ");l==="$or"&&h.length>1?o.push(M(`{ ${$} };`,s)):o.push(M($,s));continue}continue}if(a.dataFields?.find(l=>l.dbPath===c||l.path===c)){let l=Io(c,p,t,s,i);o.push(...l);continue}let d=a.linkFields?.find(l=>l.path===c);if(d){let l=Ao(d,p,t,n,s,i);o.push(...l);continue}if(a.thingType==="relation"){let l=a.roles[c];if(l){let f=Oo(l,p,t,r,n,s,i);o.push(...f);continue}}throw new Error(`"${r}" does not have property "${c}"`)}return o},Io=(e,t,r,n,s)=>{let i=[];if(isObject(t)&&!isArray(t))for(let[a,o]of Object.entries(t)){let c=a.toLowerCase(),p="";switch(c){case"$eq":p=`$${r} has ${e} ${me(o)};`;break;case"$ne":p=`not { $${r} has ${e} ${me(o)}; };`;break;case"$in":{if(!isArray(o))throw new Error("Value for $in operator must be an array");let u=o.map(d=>`$${r} has ${e} ${me(d)};`);p=Ge(u),s&&(p=`not { ${p} };`);break}case"$nin":if(!isArray(o))throw new Error("Value for $nin operator must be an array");for(let u of o){let d=`not { $${r} has ${e} ${me(u)}; };`;i.push(M(d,n));}continue;case"$exists":if(o===!0)p=`$${r} has ${e} $${e}_${v4()};`;else if(o===!1)p=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${o}`);break;default:throw new Error(`Unsupported operator "${a}" for data field "${e}"`)}s&&(p=`not { ${p} };`),i.push(M(p,n));}else if(isArray(t)){let a=t.map(c=>`$${r} has ${e} ${me(c)};`),o=Ge(a);o&&(s&&(o=`not { ${o} };`),i.push(M(o,n)));}else {let a=`$${r} has ${e} ${me(t)};`;s&&(a=`not { ${a} };`),i.push(M(a,n));}return i},Ao=(e,t,r,n,s,i)=>{let a=[],[o]=e.oppositeLinkFieldsPlayedBy,p=K(n,o.thing).idFields?.[0];if(!p)throw new Error(`"${o.thing}" does not have an id field`);let u=`${o.thing}_${v4()}`,d="";if(e.target==="relation")if(t===null)d=i?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${me(f)};`);d=Ge(l),i&&(d=`not { ${d} };`);}else d=`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${me(t)};`,i&&(d=`not { ${d} };`);else if(t===null)d=i?`$${u} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`:`not { $${u} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(f=>`$${u} isa ${o.thing}, has ${p} ${me(f)}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`);d=Ge(l),i&&(d=`not { ${d} };`);}else d=`$${u} isa ${o.thing}, has ${p} ${me(t)}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`,i&&(d=`not { ${d} };`);return a.push(M(d,s)),a},Oo=(e,t,r,n,s,i,a)=>{let o=[],[c]=e.playedBy||[],u=K(s,c.thing).idFields?.[0];if(!u)throw new Error(`"${c.thing}" does not have an id field`);let d=`${c.thing}_${v4()}`,l=v4(),f=`${r}_${l}`;o.push(M(`$${f} isa ${n};`,i));let h="";if(t===null)h=`$${f} (${c.plays}: ${d});`,a?o.push(M(h,i)):o.push(M(`not { ${h} };`,i));else if(isArray(t)){let $=t.map(g=>`$${d} isa ${c.thing}, has ${u} ${me(g)}; $${f} (${c.plays}: $${d});`);h=Ge($),a?o.push(M(`not { ${h} };`,i)):o.push(M(h,i));}else h=`$${d} isa ${c.thing}, has ${u} ${me(t)}; $${f} (${c.plays}: $${d});`,a?o.push(M(`not { ${h} };`,i)):o.push(M(h,i));return o.push(M(`$${r} is $${f};`,i)),o},Ge=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},me=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("|")})$"`:me(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},qo=(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,...s}=e,i=wn(s,r);return n&&zt(n)&&(i.$not=wn(n,r)),i},wn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,s])=>{let i=t[n]||n;r[i]=s;}),r},zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Ht="___",Sn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>Po({query:n,schema:r}))},Po=e=>{let{query:t,schema:r}=e,{$path:n,$thing:s,$filter:i,$fields:a,$sort:o,$offset:c,$limit:p,$id:u}=t;if(!n)throw new Error("Path is not defined");let d=[],l=t[oe];if(d.push("match"),d.push(`$${n} isa ${s};`),i||u){let $=ot(r,t),g={...i,...u?{[$]:u}:{}},m=pt({$filter:g,$var:n,$thing:s,schema:r,depth:0});d.push(`
116
+ `:" } or { ");l==="$or"&&h.length>1?o.push(M(`{ ${$} };`,s)):o.push(M($,s));continue}continue}if(a.dataFields?.find(l=>l.dbPath===c||l.path===c)){let l=Io(c,p,t,s,i);o.push(...l);continue}let d=a.linkFields?.find(l=>l.path===c);if(d){let l=Ao(d,p,t,n,s,i);o.push(...l);continue}if(a.thingType==="relation"){let l=a.roles[c];if(l){let f=Oo(l,p,t,r,n,s,i);o.push(...f);continue}}throw new Error(`"${r}" does not have property "${c}"`)}return o},Io=(e,t,r,n,s)=>{let i=[];if(isObject(t)&&!isArray(t))for(let[a,o]of Object.entries(t)){let c=a.toLowerCase(),p="";switch(c){case"$eq":p=`$${r} has ${e} ${me(o)};`;break;case"$ne":p=`not { $${r} has ${e} ${me(o)}; };`;break;case"$in":{if(!isArray(o))throw new Error("Value for $in operator must be an array");let u=o.map(d=>`$${r} has ${e} ${me(d)};`);p=Ge(u),s&&(p=`not { ${p} };`);break}case"$nin":if(!isArray(o))throw new Error("Value for $nin operator must be an array");for(let u of o){let d=`not { $${r} has ${e} ${me(u)}; };`;i.push(M(d,n));}continue;case"$exists":if(o===!0)p=`$${r} has ${e} $${e}_${v4()};`;else if(o===!1)p=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${o}`);break;default:throw new Error(`Unsupported operator "${a}" for data field "${e}"`)}s&&(p=`not { ${p} };`),i.push(M(p,n));}else if(isArray(t)){let a=t.map(c=>`$${r} has ${e} ${me(c)};`),o=Ge(a);o&&(s&&(o=`not { ${o} };`),i.push(M(o,n)));}else {let a=`$${r} has ${e} ${me(t)};`;s&&(a=`not { ${a} };`),i.push(M(a,n));}return i},Ao=(e,t,r,n,s,i)=>{let a=[],[o]=e.oppositeLinkFieldsPlayedBy,p=K(n,o.thing).idFields?.[0];if(!p)throw new Error(`"${o.thing}" does not have an id field`);let u=`${o.thing}_${v4()}`,d="";if(e.target==="relation")if(t===null)d=i?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${me(f)};`);d=Ge(l),i&&(d=`not { ${d} };`);}else d=`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${me(t)};`,i&&(d=`not { ${d} };`);else if(t===null)d=i?`$${u} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`:`not { $${u} isa ${o.thing}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation}; };`;else if(isArray(t)){let l=t.map(f=>`$${u} isa ${o.thing}, has ${p} ${me(f)}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`);d=Ge(l),i&&(d=`not { ${d} };`);}else d=`$${u} isa ${o.thing}, has ${p} ${me(t)}; (${e.plays}: $${r}, ${o.plays}: $${u}) isa ${e.relation};`,i&&(d=`not { ${d} };`);return a.push(M(d,s)),a},Oo=(e,t,r,n,s,i,a)=>{let o=[],[c]=e.playedBy||[],u=K(s,c.thing).idFields?.[0];if(!u)throw new Error(`"${c.thing}" does not have an id field`);let d=`${c.thing}_${v4()}`,l=v4(),f=`${r}_${l}`;o.push(M(`$${f} isa ${n};`,i));let h="";if(t===null)h=`$${f} (${c.plays}: ${d});`,a?o.push(M(h,i)):o.push(M(`not { ${h} };`,i));else if(isArray(t)){let $=t.map(g=>`$${d} isa ${c.thing}, has ${u} ${me(g)}; $${f} (${c.plays}: $${d});`);h=Ge($),a?o.push(M(`not { ${h} };`,i)):o.push(M(h,i));}else h=`$${d} isa ${c.thing}, has ${u} ${me(t)}; $${f} (${c.plays}: $${d});`,a?o.push(M(`not { ${h} };`,i)):o.push(M(h,i));return o.push(M(`$${r} is $${f};`,i)),o},Ge=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},me=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("|")})$"`:me(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},qo=(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,...s}=e,i=Tn(s,r);return n&&zt(n)&&(i.$not=Tn(n,r)),i},Tn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,s])=>{let i=t[n]||n;r[i]=s;}),r},zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Ht="___",Mn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>Po({query:n,schema:r}))},Po=e=>{let{query:t,schema:r}=e,{$path:n,$thing:s,$filter:i,$fields:a,$sort:o,$offset:c,$limit:p,$id:u}=t;if(!n)throw new Error("Path is not defined");let d=[],l=t[oe];if(d.push("match"),d.push(`$${n} isa ${s};`),i||u){let $=ot(r,t),g={...i,...u?{[$]:u}:{}},m=pt({$filter:g,$var:n,$thing:s,schema:r,depth:0});d.push(`
117
117
  ${m}`);}let f=Yt({schema:r,$thing:s,$var:n,$sort:o,depth:0});f&&d.push(f.match);let h=`M_${v4()}`;if(d.push(`?queryPath${h} = "${l}";`),d.push("fetch"),d.push(`?queryPath${h} as "queryPath";`),a){let $=a.filter(b=>b.$fieldType==="data");$&&$.length>0&&d.push(...vt($,n,0));let g=a.filter(b=>b.$fieldType==="link");g&&g.length>0&&d.push(...Jt(g,n,n,0,r));let m=a.filter(b=>b.$fieldType==="role");m&&m.length>0&&d.push(...Kt(m,n,n,0,r));}return f&&d.push(f.sort),typeof c=="number"&&d.push(`
118
118
  offset ${c};`),typeof p=="number"&&d.push(`
119
119
  limit ${p};`),d.join(`
120
120
  `)},vt=(e,t,r)=>{let n=[],s=[],i=[];for(let u=0;u<e.length;u++)e[u].$isVirtual||n.push(e[u].$dbPath),e[u][se].contentType==="FLEX"&&i.push({path:e[u][se].dbPath}),s.push(`{${e[u].$dbPath}:${e[u].$as}}`);let a=n.join(", "),c=`$metadata:{as:[${s.join(",")}]}`,p=[M(`$${t} as "${t}.${c}.$dataFields": ${a};`,r)];return i.length>0&&i.forEach(u=>{p.push(M(`"${u.path}.$multiVal": {match $${t} has ${u.path} $${u.path}; fetch $${u.path}: attribute;};`,r));}),p},Kt=(e,t,r,n,s)=>{let i=n+1,a=[];for(let o of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:d,$filterByUnique:l,$thing:f,$sort:h,$offset:$,$limit:g}=o,m=o[oe],b=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${b}.${o.$var}": {`,n)),a.push(M("match",i));let F=`${t}${Ht}${o.$var}`;if(a.push(M(`$${F} isa ${o.$thing};`,i)),a.push(M(`$${t} (${o.$var}: $${t}${Ht}${o.$var}) isa ${o.$intermediary};`,i)),o.$filter||o.$id){let R=ot(s,o),L=o.$id?{[R]:o.$id}:{},D={...o.$filter,...L};a.push(pt({$filter:D,$var:F,$thing:o.$thing,schema:s,depth:i}));}let y=Yt({schema:s,$thing:f,$var:F,$sort:h,depth:i});if(y&&a.push(y.match),c){let R=`M_${v4()}`;a.push(M(`
121
- ?queryPath${R} = "${m}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${R} as "queryPath";`,i));let L=c?.filter(_=>_.$fieldType==="data");L&&L.length>0&&a.push(...vt(L,F,i));let D=c?.filter(_=>_.$fieldType==="link");D&&D.length>0&&a.push(...Jt(D,F,`${t}.${o.$var}`,i,s));let C=c?.filter(_=>_.$fieldType==="role");C&&C.length>0&&a.push(...Kt(C,F,`${t}.${o.$var}`,i,s));}y&&a.push(y.sort),typeof $=="number"&&a.push(M(`offset ${$};`,i)),typeof g=="number"&&a.push(M(`limit ${g};`,i)),a.push(M("};",n));}return a},Jt=(e,t,r,n,s)=>{let i=n+1,a=[];for(let o of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:d,$filterByUnique:l,$playedBy:f,$thing:h,$sort:$,$offset:g,$limit:m}=o,b=o[oe],F=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${F}.${o.$var}": {`,n)),a.push(M("match",i));let y=`${t}${Ht}${o.$var}`;if(a.push(M(`$${y} isa ${o.$thing};`,i)),o.$filter||o.$id){let L=ot(s,o),D=o.$id?{[L]:o.$id}:{},C={...o.$filter,...D};a.push(pt({$filter:C,$var:y,$thing:o.$thing,schema:s,depth:i}));}let R=Yt({schema:s,$thing:h,$var:y,$sort:$,depth:i});if(R&&a.push(R.match),o.$target==="role"?a.push(M(`$${t}_intermediary (${o.$plays}: $${t}, ${f.plays}: $${y}) isa ${o.$intermediary};`,i)):a.push(M(`$${y} (${o.$plays}: $${t});`,i)),c){let L=`M_${v4()}`;a.push(M(`?queryPath${L} = "${b}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${L} as "queryPath";`,i));let D=c?.filter(J=>J.$fieldType==="data");D&&D.length>0&&a.push(...vt(D,y,i));let C=c?.filter(J=>J.$fieldType==="link");C&&C.length>0&&a.push(...Jt(C,y,`${t}.${o.$var}`,i,s));let _=c?.filter(J=>J.$fieldType==="role");_&&_.length>0&&a.push(...Kt(_,y,`${t}.${o.$var}`,i,s));}R&&a.push(R.sort),typeof g=="number"&&a.push(M(`offset ${g};`,i)),typeof m=="number"&&a.push(M(`limit ${m};`,i)),a.push(M("};",n));}return a},ko=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Yt=e=>{let{$var:t,$thing:r,schema:n,$sort:s,depth:i}=e,a=K(n,r),o=[],c=[];if(s?.forEach(p=>{let u=ko(p),d=a.dataFields?.find(h=>h.path===u.field);if(!d)throw new Error(`"${r}" does not have data field "${u.field}"`);let l=`${u.field}_${v4()}`;o.push(M("{",i)),o.push(M(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),o.push(M("not {",i+1)),o.push(M(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),o.push(M(`$${l}_2 < $${l}_1;`,i+2)),o.push(M("};",i+1)),o.push(M(`?${l}_ = $${l}_1;`,i+1)),o.push(M("} or {",i)),o.push(M(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),o.push(M(`?${l}_ = "~";`,i+1)),o.push(M("};",i)),o.push(M(`?${l} = ?${l}_;`,i));let f=u.desc?"desc":"asc";c.push(`?${l} ${f}`);}),o.length!==0)return {match:o.join(""),sort:M(`sort ${c.join(", ")};`,i)}};var Qn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:s,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,o)=>{let c=r[o],p=t[o];return xo(a,c,p,n,s)})},xo=(e,t,r,n,s)=>e.length===0?null:r.$filterByUnique?Ln(e[0],t,n,s):e.map(i=>Ln(i,t,n,s)),Ln=(e,t,r,n)=>{let{dataFields:s,currentSchema:i,linkFields:a,roleFields:o,schemaValue:c}=Gt(e,r),p=Xt(s,i,n),u=er(a,r,n),d=Zt(o,r,n),l=t?.$fields?.every(h=>!i?.idFields?.includes(typeof h=="string"?h:h.$path));return {...u,...d,...c,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...l?Object.fromEntries(Object.entries(p).filter(([h])=>!i?.idFields?.includes(h))):p}},Gt=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),s=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");s?.length>0&&s.forEach(f=>{let h=f.replace(/\.\$multiVal$/,""),$=e[f][0][h].attribute;e[n][h]=$;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let o=i.type,c={$thing:o.label,$thingType:o.root,[oe]:e.queryPath.value},p={[`$${c.$thingType}`]:c.$thing},u=N(t,p),d=r.filter(f=>{let h=pe(f.split(".").pop());return !f.endsWith(".$dataFields")&&u.linkFields?.some($=>$.path===h)}).map(f=>{let h=pe(f.split(".").pop()),$=pe(u.linkFields?.find(g=>g.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),l=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&u.thingType==="relation"&&u.roles?.[h]}).map(f=>{let h=pe(f.split(".").pop());return {$roleFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:u.roles[h].cardinality}});return {dataFields:i,schemaValue:c,currentSchema:u,linkFields:d,roleFields:l}},Xt=(e,t,r)=>{let{$metaData:n}=e,{as:s}=jo(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).map(([a,o])=>{let c=t.dataFields?.find(l=>l.path===a||l.dbPath===a),p=a==="id",u=Array.isArray(s)?s.find(l=>l[a])?.[a]:a,d;if(c?.cardinality==="ONE"){if(d=o[0]?o[0].value:r.query?.returnNulls?null:void 0,c.contentType==="DATE"||c.contentType==="FLEX"&&o[0].type.value_type==="datetime"?d=d&&`${d}Z`:c.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[u,d],["$id",d]].filter(([l,f])=>f!==void 0)}else if(c?.cardinality==="MANY"){if(!isArray(o))throw new Error("Typedb fetch has changed its format");if(o.length===0)return r.query?.returnNulls?[[u,null]]:[];c.contentType==="DATE"?d=o.map(l=>`${l.value}Z`):c.contentType==="FLEX"?d=o.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):c.contentType==="JSON"?d=o.map(l=>l.value&&JSON.parse(l.value)):d=o.map(l=>l.value);}return [[u,d]].filter(([l,f])=>f!==void 0)}).flat();return Object.fromEntries([...i])},Zt=(e,t,r)=>{let n={};return e.forEach(s=>{let{$roleFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Rn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:b}=Gt(f,t),F=Xt(h,$,r);if(p==="T")return F.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...F};return u==="true"&&$?.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...b}}});l.length>0?n[c]=o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[c]=null);}),n},er=(e,t,r)=>{let n={};return e.forEach(s=>{let{$linkFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Rn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:b}=Gt(f,t),F=Xt(h,$,r);if(p==="T")return F.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...F};return u==="true"&&$.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...b}}});n[c]=l.length>0?o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},Rn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,s=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),o=e.match(n),c=e.match(s);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:o?o[1]:null,filterByUnique:c?c[1]:null}},jo=e=>{try{let r=(s=>{let i=s.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,o,c)=>/^{.*}$/.test(c)?`:${c}`:`:${o}"${c}"`),i=i.replace(/\[([^\]]+)\]/g,(a,o)=>`[${o.split(",").map(c=>c.trim().startsWith("{")&&c.trim().endsWith("}")?c.trim():`"${c.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var $t=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,s=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!s)throw new Error("Client not found");n=await s.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:s,session:n});}return {client:s,session:n}};var Dn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,s=new TypeDBOptions;s.infer=!0;let{session:i}=await $t(r,n),a=await i.transaction(TransactionType.READ,s),[o,c]=await tryit(parallel)(t.length,t,async p=>await a.query.fetch(p).collect());if(o){await a.rollback();let p=o;throw new Error(`Error running TQL query: ${p.errors}`)}return await a.close(),c};var Ho=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,vo=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ko=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,tr=j("error","error",x((e,t)=>({...e,error:t.error}))),Jo=ye("build",{build:z(async e=>Sn({queries:e.bql.queries,schema:e.schema}),j("done","run",x(vo)),tr),run:z(async e=>Dn({dbHandles:e.handles,tqlRequest:pe(e.tql.queries),config:e.config}),j("done","parse",x(Ko)),tr),parse:z(async e=>Qn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:pe(e.tql.res)}),j("done","success",x(Ho)),tr),success:ae(),error:ae()},e=>e),Yo=async e=>new Promise((t,r)=>{$e(Jo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Cn=async(e,t,r,n,s)=>Yo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:s,error:null});var Go=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,rr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,mt=j("error","error",x((e,t)=>({...e,error:t.error}))),Xo=ye("enrich",{enrich:z(async e=>(e.config.query?.debugger&&console.log(`originalBQLQuery[${ne}]`,JSON.stringify(e.bql.raw)),Wr(e.bql.raw,e.schema)),j("done","adapter",x(Go)),mt),adapter:z(async e=>{let t={};e.bql.queries?.forEach((o,c)=>{let p=e.bql.raw[c],u=K(e.schema,o.$thing),{id:d}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let l=t[d];l.rawBql.push(p),l.bqlQueries.push(o),l.indices.push(c);});let r=Object.values(t),n=r.map(o=>{if(o.db==="typeDB")return Cn(o.rawBql,o.bqlQueries,e.schema,e.config,e.handles);if(o.db==="surrealDB")return Tn(o.bqlQueries,e.schema,e.config,o.client);throw new Error(`Unsupported DB "${JSON.stringify(o,null,2)}"`)}),s=await Promise.all(n),i=r.flatMap((o,c)=>{let p=s[c];return o.indices.map((u,d)=>({index:u,result:p[d]}))});return i.sort((o,c)=>o.index<c.index?-1:o.index>c.index?1:0),i.map(({result:o})=>o)},j("done","postHooks",x(rr)),mt),postHooks:z(async e=>hn(e.schema,pe(e.bql.queries),pe(e.bql.res)),j("done","clean",x(rr)),mt),clean:z(async e=>un(e.config,pe(e.bql.res)),j("done","success",x(rr)),mt),success:ae(),error:ae()},e=>e),Zo=async e=>new Promise((t,r)=>{$e(Xo,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>Zo({bql:{raw:e},schema:t,config:r,handles:n,error:null});var nr="___",ts=Symbol.for("grandChildOfCreate"),In=async(e,t,r,n)=>{let s=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],i=(E,B)=>Object.keys(E).filter(T=>!T.startsWith("$")&&!s.includes(T)&&E[T]!==void 0?B?!N(t,E).dataFields?.find(w=>w.path===T):!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:E,key:B,value:T})=>{E&&B&&!B.includes("$")&&!s.includes(B)&&isObject(E)?(Array.isArray(E[B])?E[B]:[E[B]]).forEach(w=>{if(isObject(w)){if(E.$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`)}}):!E&&isObject(T)&&(a.includes(T.$op)||a.push(T.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let c=(E=>{let B=(T,S)=>{let w=[],Q={},A=["$op","$bzId","$parentKey"],U=["$relation","$entity","$id",...A];for(let q in T)if(!A.includes(q)&&!(U.includes(q)&&!S))if(!q.includes("$")&&(isObject(T[q])||Array.isArray(T[q]))){let Z=rs(T[q]);if(Array.isArray(Z)&&Z.length>0)Z.forEach(be=>{let Ee={$path:q,...B(be),...be.$filter&&{$as:be.$bzId}};w.find(Y=>Y.$path===Ee.$path&&!Y.$filter)||(w=[...w,Ee]);});else {let be={$path:q,...B(Z),...!Z.$filter&&{$as:Z.$bzId}};w=[...w,be];}}else Q[q]=T[q];return {...Q,$fields:w}};return E.map(T=>B(T,!0))})(Array.isArray(e)?e:[e]),u=(await ze(c,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,d=(E,B)=>{let T=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:S}=E,w=S?.beforePath||"root",Q=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${w}.${Q}___${S.key}`,ids:T,key:B}}else return {beforePath:"root",ids:T,key:B}},l=(E,B)=>{let T=E?.beforePath||"root";if(typeof T!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${T}.${S}___${E?.key}`},f=E=>{if(E.includes("[")&&E.includes("]")){let[B,T,S]=E.split(/[[\]]/);return T.split(",").map(Q=>`${B}${Q}${S}`)}else return [E]},h={};(E=>produce(E,B=>traverse(B,({key:T,parent:S})=>{if(S&&T&&S.$id&&!T.includes("$")){let w=d(S,T),Q=l(w);if(Array.isArray(S[T])){let A=[];S[T].forEach(U=>{isObject(U)?(U.$objectPath=w,A.push(U.$id.toString())):U&&A.push(U.toString());}),h[Q]={$objectPath:w,$ids:A};}else {let A=S[T];isObject(A)?(h[Q]={$objectPath:w,$ids:[A.$id.toString()]},A.$objectPath=w):A?h[Q]={$objectPath:w,$ids:[A.toString()]}:A===null&&(h[Q]=null);}}})))(u||{});let g=E=>produce(E,B=>traverse(B,({key:T,value:S,parent:w})=>{w&&T&&!T.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(w)&&(Array.isArray(w[T])?w[T].forEach(Q=>{typeof Q!="string"&&(Q.$objectPath=d(w,T),Q.$parentIsCreate=w.$op==="create",Q[ts]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[T])&&(w[T].$parentIsCreate=w.$op==="create",w[T][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[T].$objectPath=d(w,T)));})),m=g(e),b=E=>{let B=[];return E.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let w=l({...S.$objectPath,key:S.$bzId}),Q=h[w];Q&&(Array.isArray(Q.$ids)?Q.$ids:[Q.$ids]).forEach(U=>{let q={...S,$id:U,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};B.push(q);});}else {let w=l(S.$objectPath),Q=h[w];Q?Q?.$ids?.forEach(A=>{let U={...S,$id:A,$bzId:`T4_${v4()}`};B.push(U);}):B.push(S);}else B.push(S);}),B.map(S=>{let w={...S};return i(w,!0).forEach(Q=>{let A=Array.isArray(w[Q])?w[Q]:[w[Q]],U=b(A);w[Q]=U;}),w})},F=b(Array.isArray(m)?m:[m]),y=g(F),L=(E=>{let B=T=>{let S=Y=>{let X=[],H=[],P=[];return Y.forEach(W=>{let ie=i(W,!0);if(ie.length>0){let O=!1;ie.forEach(V=>{(Array.isArray(W[V])?W[V]:[W[V]]).filter(te=>!te.$id&&!te.id&&typeof W=="object").length&&(O=!0);}),O?X.push(W):H.push(W);}else W.$id?P.push({...W,$bzId:W.$tempId||W.$bzId}):P.push({...W,$bzId:W.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:X,operationWithoutMultiples:H,otherOps:P}},{operationWithMultiples:w,operationWithoutMultiples:Q,otherOps:A}=S(T),U=Y=>{let H=(()=>{let V={};for(let le in Y){let G=N(t,Y);!le.startsWith("$")&&G.dataFields?.find(te=>te.path===le)&&(V[le]=Y[le]);}return V})(),P=Object.keys(Y),W=i(Y,!0),ie=[],O=(V,le)=>{if(V===W.length){let te={...le};P.forEach(ce=>{ce.startsWith("$")&&(te[ce]=Y[ce]);}),ie.push({...te,...H});return}let G={...le,[W[V]]:Y[W[V]],...Qe(le),...H};O(V+1,G),O(V+1,le);};return O(0,{...Qe(Y)}),ie},q=[];return w.forEach(Y=>{let X=U(Y),H=[];X.forEach(P=>{let W=i(P,!0);if(P.$op==="create")H.push(P);else if(P.$id){let ie=l(P.$objectPath),O=[];if(W.forEach(V=>{let le=`${ie.includes("undefined")?"root":ie}.${P.$id}${nr}${V}`,G=h[le];P[V].filter(ce=>ce.$op==="unlink"||ce.$op==="delete"||ce.$op==="update").length>0?G?.$ids&&O.push({key:V,ids:G.$ids}):O.push({key:V,ids:[""]});}),O.length===W.length&&!H.find(V=>V.$id===P.$id))H.push(P);else {let V={...P,$bzId:P.$tempId||`T4_${v4()}`};W.forEach(G=>{let te=P[G].filter(ce=>ce.$id);te.length>0?V[G]=te:V[G]=void 0;}),i(V,!0).length>0&&H.push(V);}}else if(P.$objectPath){let ie=l(P.$objectPath),O=h[ie]?.$ids||[];O.forEach(V=>{let le=[];W.forEach(G=>{let te=`${ie}.${V}${nr}${G}`,ce=h[te];ce&&le.push({key:G,ids:ce.$ids});}),W.length===0?O.filter(te=>!H.find(ce=>ce.$id===te)).forEach(te=>{H.push({...P,$id:te,$bzId:P.$tempId||`PQT2_${v4()}`});}):le.length===W.length&&!H.find(G=>G.$id===V)&&(W.forEach(G=>{let te=`${l(P.$objectPath)}.${V}${nr}${G}`,ce=h[te]?.$ids||[],ai=P[G].find(ke=>!ke.$id),dr=[...ce.map(ke=>({...ai,$id:ke,$objectPath:{beforePath:P.$objectPath.beforePath,ids:ke,key:G}})),...P[G].filter(ke=>ke.$id)];dr.length>0&&(P[G]=dr);}),H.push({...P,$id:V,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else H.push(P);}),H.forEach(P=>{q.push(P);});}),[...q,...Q,...A].filter(Y=>i(Y).length>0?!0:Y.$op!=="update").map(Y=>{let X={...Y};return i(X,!0).forEach(H=>{let P=Array.isArray(X[H])?X[H]:[X[H]],W=B(P);X[H]=W;}),X})};return B(E)})(Array.isArray(y)?y:[y]),D=E=>E.map(B=>{let T=i(B,!0),S={...B};return T.forEach(w=>{let Q=Array.isArray(B[w])?B[w]:[B[w]],A=[],U=[],q=[],Z={},be=Rt(t,B,w);Q.filter(O=>O).forEach(O=>{O.$op==="replace"&&O.$id?(Z=O,Array.isArray(O.$id)?U=[...U,...O.$id]:U.push(O.$id)):O.$op==="create"&&be==="ONE"&&O.id?(Z=O,Array.isArray(O.id)?q=[...U,...O.id]:q.push(O.id)):A.push(O);});let Ee=l(Z.$objectPath),X=f(Ee).map(O=>h[O]),H=[];X.filter(O=>O!=null).forEach(O=>{H=[...H,...O?.$ids||[]];});let P=H.filter(O=>!U.includes(O)),W=U.filter(O=>!H.includes(O)),ie=Qe(Z);P.length>0&&A.push({...Z,$op:"unlink",$id:P,$bzId:Z.$tempId||`T4_${v4()}`,id:void 0,...ie}),W.length>0&&W.forEach(O=>{A.push({...Z,$op:"link",$id:O,$bzId:Z.$tempId||`T5_${v4()}`,...ie});}),q.length>0&&q.forEach(O=>{A.push({...Z,$op:"create",id:O,$bzId:Z.$tempId||`T6_${v4()}`,...ie});}),S[w]=D(A);}),S}),C=g(D(g(L)));(E=>produce(E,B=>traverse(B,T=>{let{key:S,value:w,parent:Q,meta:A}=T;S&&Q&&!S?.includes("$")&&S!=="$filter"&&!A.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(Q)&&(Array.isArray(w)?w:[w]).forEach(q=>{let Z=q.$filter?{...q.$objectPath,key:q.$filterBzId}:q.$objectPath,be=l(Z),Ee=h[be],Y=(P,W)=>P.every(ie=>W.includes(ie)),X=q.$id?Array.isArray(q.$id)?Y(q.$id,Ee&&Ee.$ids?Ee.$ids:[]):Ee?.$ids?.includes(q.$id):Ee,H=Rt(t,Q,q.$objectPath.key);if(q.$op==="link"&&X&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${l(q.$objectPath)}" because it is already occupied.`);if(q.$op)switch(q.$op){case"delete":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${q.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"update":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${q.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"unlink":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${q.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"link":if(X)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${q.$id}" because it is already linked to $id:"${Q.$id}"`);break;}});})))(C);let he=(E=>produce(E,B=>traverse(B,T=>{let{value:S,meta:w}=T;isObject(S)&&(S[Symbol.for("path")]=w.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(C);return [...Array.isArray(he)?he:[he]].sort((E,B)=>E.$op==="create"&&B.$op!=="create"?-1:E.$op!=="create"&&B.$op==="create"?1:0)},rs=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var An=(e,t)=>produce(e,n=>gt(t,n)),gt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(s=>gt(e,s,r));return}let n=K(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([s])=>{s.startsWith("$")||s.startsWith("%")||is(e,t,s,n);});},is=(e,t,r,n)=>{let s=t[r];if(!s)return;let i=n.dataFields?.find(o=>o.path===r);if(i){i.contentType==="JSON"&&s!=null&&(t[r]=JSON.stringify(s));return}let a=n.linkFields?.find(o=>o.path===r);if(a){let o=a.oppositeLinkFieldsPlayedBy[0]?.thing;gt(e,s,o);return}if(n.thingType==="relation"){let o=n.roles[r];if(!o)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[c]=o.playedBy||[];if(!c)throw new Error(`Role ${o.path} in ${n} is not played by anything`);gt(e,s,c.thing);}};var kn=async(e,t,r,n)=>{let s=Array.isArray(e)?e:[e],i=s.map(c=>ir(c,!0)),o=(await ze(i,t,r,n)).bql.res;return s.map((c,p)=>{let u=K(t,c.$thing);return xn({mut:c,node:o[p],schema:t,thing:u})})},Nn=new Set(["$op","$bzId","$parentKey"]),ss=new Set(["$relation","$entity","$id",...Nn]),ir=(e,t)=>{let r={};e.$fields?.forEach(s=>{typeof s=="string"?r[s]=s:r[s.$path]=s;});let n={};for(let s in e){if(Nn.has(s)||ss.has(s)&&!t)continue;let i=e[s];s.startsWith("$")?n[s]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[s]={$path:s,...ir(i[0],!1)}):isObject(i)&&(r[s]={$path:s,...ir(i,!1)});}return n.$fields=Object.values(r),n},xn=e=>{let{mut:t,node:r,schema:n,thing:s}=e,i=_n(s),a=ls(r);if(Array.isArray(t))return t.map(c=>{let p=a[c.$id];return p?On({mut:c,node:p,schema:n,thing:s,...i}):c});let o=a[t.$id];return On({mut:t,node:o,schema:n,thing:s,...i})},On=e=>{let{mut:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,{$fields:c,...p}=t;if(!r)return p;let u=jn({$fields:t.$fields,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}),d={...p,[Ne]:u};for(let l in t){if(l.startsWith("$"))continue;let f=t[l];if(i[l]||!f||typeof f!="object"){d[l]=f;continue}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);let g=K(n,$);d[l]=xn({mut:f,schema:n,node:r[l],thing:g});}return d},jn=e=>{let{$fields:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,c=t||as(s),p={$id:r.$id};return c.forEach(u=>{let d=typeof u!="string",l=d?u.$path:u,f=r[l];if(i[l]){p[l]=f;return}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);if(!d){f&&(p[l]=Array.isArray(f)?f.map(qn):qn(f));return}let g=K(n,$),m=_n(g);p[l]=Array.isArray(f)?f.map(b=>Pn({...m,$fields:u.$fields,value:b,schema:n,thing:g})):Pn({...m,$fields:u.$fields,value:f,schema:n,thing:g});}),p},as=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},qn=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},Pn=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 jn({...e,node:t})},_n=e=>{let t=Object.fromEntries(e.dataFields?.map(s=>[s.path,s])||[]),r=Object.fromEntries(e.linkFields?.map(s=>[s.path,s])||[]),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 or=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 Wn=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 f=l.$op,h=`$${l.$bzId}`,$=N(r,l),{idFields:g,defaultDBConnector:m}=$,b=m?.path||l.$thing,F=l.$id,y=g?.[0],R=listify(l,(I,k)=>{if(I.startsWith("$")||I.startsWith("%")||I===y||k===void 0||k===null)return "";let E=$.dataFields?.find(S=>S.path===I);if(!E?.path)return "";let T=E.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(E.contentType))return `has ${T} '${k}'`;if(["NUMBER","BOOLEAN"].includes(E.contentType))return `has ${T} ${k}`;if(E.contentType==="DATE"){if(Number.isNaN(k.valueOf()))throw new Error("Invalid format, Nan Date");return k instanceof Date?`has ${T} ${k.toISOString().replace("Z","")}`:`has ${T} ${new Date(k).toISOString().replace("Z","")}`}if(E.contentType==="FLEX"){let S=`bza${Ae()}`,w=isArray(k)?k.map(Q=>or(Q)):or(k);if(Array.isArray(w))throw new Error("Array in FLEX fields not supported yet");return `has ${T} $${S}; $${S} '${S}' isa ${T}, has ${w.type}Attribute ${w.value}`}throw new Error(`Unsupported contentType ${E.contentType}`)}).filter(I=>I),L=`${h}-atts`,D=listify(l,I=>{if(I.startsWith("$")||I.startsWith("%")||I===y)return "";let k=$.dataFields?.find(T=>T.path===I);if(!k?.path)return "";let B=k.dbPath;return `{${L} isa ${B};}`}).filter(I=>I),C=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,_=F?[`has ${y} ${C}`]:[],J=[..._,...R].filter(I=>I).join(","),he=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[b,..._].filter(I=>I).join(",")};`;if(f==="update"){if(!D.length)throw new Error("update without attributes");return `${h} isa ${[b,..._].filter(I=>I).join(",")}, has ${L};
122
- ${D.join(" or ")};`}return ""},v=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[b,..._].filter(I=>I).join(",")};`:"";if(st(l))return {op:f,deletionMatch:he(),insertionMatch:v(),insertion:f==="create"?`${h} isa ${[b,J].filter(I=>I).join(",")};`:f==="update"&&R.length?`${h} ${R.join(",")};`:"",deletion:f==="delete"?`${h} isa ${b};`:f==="update"&&D.length?`${h} has ${L};`:""};throw new Error("in attributes")},s=l=>{let f=l.$op,h=N(r,l),$=`$${l.$bzId}`,g=l.$id,m=h.defaultDBConnector?.path||l.$thing,b="roles"in h?listify(h.roles,k=>k):[],F="roles"in h?mapEntries(h.roles,(k,E)=>[k,E.dbConnector?.path||k]):{},y=listify(l,(k,E)=>{if(!b.includes(k))return null;if(!("roles"in h))throw new Error("This should have roles! ");let B=F[k];return Array.isArray(E)?E.map(T=>({path:B,id:T})):{path:B,id:E}}).filter(k=>k).flat(),R=y.map(k=>{if(!k?.path)throw new Error("Object without path");return `${k.path}: $${k.id}`}),L=y.length>0?`( ${R.join(" , ")} )`:"",D=l[Ie];if(!D)throw new Error("[internal error] Symbol edgeType not defined");let C=L?`${$} ${L} ${D==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",_=`${$} ${D==="linkField"||f==="delete"?`isa ${m}`:""}`,J=()=>C?f==="link"?`${C};`:f==="create"?`${C}, has id '${g}';`:"":"",he=()=>C&&f==="match"?`${C};`:"",v=()=>C?f==="delete"?`${C};`:f==="match"?`${C};`:"":"",I=()=>C?f==="delete"?`${_};`:f==="unlink"?`${$} ${L};`:"":"";return {deletionMatch:v(),insertionMatch:he(),deletion:I(),insertion:J(),op:""}},i=(l,f)=>{let h=f==="edges"?s:n;if(Array.isArray(l))return l.map(y=>{let{preDeletionBatch:R,insertionMatch:L,deletionMatch:D,insertion:C,deletion:_}=h(y);return shake({preDeletionBatch:R,insertionMatch:L,deletionMatch:D,insertion:C,deletion:_},J=>!J)}).filter(y=>y);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:b,deletion:F}=h(l);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:b,deletion:F},y=>!y)},a=i(e),o=Array.isArray(a)?a:[a],c=i(t,"edges"),p=Array.isArray(c)?c:[c],u=[...o,...p];return shake({insertionMatches:u.map(l=>l.insertionMatch).join(" ").trim(),deletionMatches:u.map(l=>l.deletionMatch).join(" ").trim(),insertions:u.map(l=>l.insertion).join(" ").trim(),deletions:u.map(l=>l.deletion).join(" ").trim()},l=>!l)};var Vn=async(e,t,r,n,s)=>{let i=[...t,...r],a=i.map(o=>{let c=e.insertions?.find(d=>d.get(`${o.$bzId}`))?.get(`${o.$bzId}`),p=o.$thing||o.$relation||o.$entity,u=p?K(n,p):void 0;if(o.$op==="create"||o.$op==="update"||o.$op==="link"){if(o.$op!=="update"&&!c&&o.$id)return {$id:o.$id,$error:"Does not exist or it's not linked to the parent"};let d=c?.asThing().iid,l=Object.entries(o).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,g])=>{if(u?.dataFields?.find(b=>b.path===$)?.contentType==="JSON")return h[$]=JSON.parse(g),h;if(o.$thingType==="relation"){let b=i.filter(F=>F.$id&&F.$bzId===g);return b.length===1?(h[$]=b[0].$id,h):(h[$]=g,h)}return h[$]=g,h},{});if(s.mutation?.noMetadata)return l;let f=o.$tempId&&!o.$tempId.startsWith("_:")?{$tempId:`_:${o.$tempId}`}:{};return {$dbId:d,...o,...l,[o.path]:o.$id,...f}}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(a)};var zn=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 $t(t,r),s=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 s.query.delete(i);let o=a&&s.query.insert(a),c=o?await o.collect():void 0;return await s.commit(),{insertions:c}}catch(o){throw new Error(`Transaction failed: ${o.message}`)}finally{await s.close();}};var ps=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),fs=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),$s=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),ar=j("error","error",x((e,t)=>({...e,error:t.error}))),ms=ye("buildMutation",{buildMutation:z(async e=>Wn(e.bql.things,e.bql.edges,e.schema),j("done","runMutation",x(fs)),ar),runMutation:z(async e=>zn(e.tql.mutation,e.handles,e.config),j("done","parseMutation",x($s)),ar),parseMutation:z(async e=>Vn(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),j("done","success",x(ps)),ar),success:ae(),error:ae()},e=>e),ys=async e=>new Promise((t,r)=>{$e(ms,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Hn=async(e,t,r,n,s,i,a)=>ys({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:s,config:i,handles:a,error:null});var vn=async(e,t)=>{let r=a=>{let{$filter:o,$thing:c,$bzId:p,$op:u,$id:d,$tempId:l}=a,f=K(t,c),{usedDataFields:h}=ue(f,a),{idFields:$}=f,g=d||a[$[0]],m=(a[Fe]?.$things||[c]).map(ee),b=de(a,E=>E.startsWith("$")),F=de(a,E=>!E.startsWith("$")),y=JSON.stringify(F),R=Object.entries(b).map(([E,B])=>E=="$tempId"?`'$tempId': '_:${B}'`:`'${E}': '${B}'`).join(","),L=a[rt],D=h.filter(E=>!$.includes(E)).map(E=>{let B=f.dataFields?.find(S=>S.path===E||S.dbPath===E);if(!B)throw new Error(`Data field schema not found for ${E}`);let T=a[E];return T===null?`${E} = NONE`:`${E} = ${Ze(T,B.contentType)}`}).filter(Boolean),C=`$\u27E8${l||p}\u27E9`,_=L?.bzId?`array::flatten($\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:g?isArray(g)?m.flatMap(E=>g.map(B=>`${E}:\u27E8${B}\u27E9`)).join(", "):m.map(E=>`${E}:\u27E8${g}\u27E9`).join(", "):!0,J=(()=>{if(L?.bzId){let E=`array::flatten($\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return g?isArray(g)?`${E}[? $this.id() IN [${g.map(B=>`'${B}'`).join(", ")}] ]`:`${E}[? $this.id() IN ['${g}'] ]`:E}else return g?isArray(g)?m.flatMap(E=>g.map(B=>`${E}:\u27E8${B}\u27E9`)).join(", "):m.map(E=>`${E}:\u27E8${g}\u27E9`).join(", "):m.join(", ")})(),he=o?`WHERE ${fe(ge(o,c,t))}`:"",v=D.length>0?`SET ${D.join(", ")}`:"",I=`VALUE (CREATE ONLY Delta SET input = ${y}, meta = {${R}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,k="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return l?"":`LET ${C} = (SELECT VALUE id FROM ${J} ${he});`;if(a.$op==="create"){if(isArray(g))throw new Error("Cannot create multiple things at once");let E=ee(c);return `LET ${C} = (CREATE ONLY ${E}:\u27E8${g}\u27E9 ${v} RETURN ${I});`}if(a.$op==="update")return `LET ${C} = IF (${_}) THEN (UPDATE ${J} ${v} ${he} RETURN ${I}) END;`;if(a.$op==="delete")return `LET ${C} = IF (${_}) THEN (DELETE ${J} ${he} RETURN ${k}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:o,$bzId:c,$op:p,$tempId:u}=a,d=K(t,o),{usedRoleFields:l}=ue(d,a),f=`$\u27E8${u||c}\u27E9`,h="roles"in d?l.flatMap(m=>{let b=d.roles[m];if(!b)throw new Error(`Role field schema not found for ${m}`);let{cardinality:F}=b,y=isArray(a[m])?a[m].map(R=>`$\u27E8${R}\u27E9`):[`$\u27E8${a[m]}\u27E9`];if(F==="ONE"){if(y.length>1)throw new Error(`${p==="link"?"Linking":"Replacing"} multiple values to a ONE field ${m}`);switch(p){case"link":case"replace":return `${m} = ((type::is::array(${y[0]}) && array::len(${y[0]})==1) && ${y[0]}[0]) || ${y[0]}`;case"unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${p} for ONE cardinality`)}}else if(F==="MANY"){let R=`array::flatten([${y}])`;switch(p){case"link":return `${m} += ${R}`;case"unlink":return `${m} -= ${R}`;case"replace":return `${m} = ${R}`;default:throw new Error(`Unsupported operation ${p} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${F}`)}):[],$=h.length>0?`${h.join(", ")}`:"",g=$?`SET ${$}`:"";return `IF ${f} THEN (UPDATE ${f} ${g} RETURN VALUE id) END; ${f};`},s=a=>{let{$thing:o,$op:c}=a,p=K(t,o),u=ee(o),{usedRoleFields:d}=ue(p,a);if(!["create","delete"].includes(c))throw new Error("Arcs can only be created or deleted");let[l,f]=d,h=isArray(a[l])?a[l]:[a[l]],$=isArray(a[f])?a[f]:[a[f]];if(c==="create"){if(d.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let g=de(a,C=>!C.startsWith("$")),b=`(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 )`,y=p.roles[l].cardinality==="MANY",L=p.roles[f].cardinality==="MANY";return h.flatMap(C=>$.flatMap(_=>`FOR $node1 IN fn::as_array($\u27E8${C}\u27E9) { FOR $node2 IN fn::as_array($\u27E8${_}\u27E9) { CREATE ONLY ${u} SET ${l} = ${y?"fn::as_array($node1)":"$node1"}, ${f} = ${L?"fn::as_array($node2)":"$node2"} RETURN ${b}; } }`))}if(c==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${l}) CONTAINSANY $\u27E8${h}\u27E9 AND fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 RETURN BEFORE`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(s)]};var Kn=async(e,t,r)=>{let n=`
121
+ ?queryPath${R} = "${m}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${R} as "queryPath";`,i));let L=c?.filter(_=>_.$fieldType==="data");L&&L.length>0&&a.push(...vt(L,F,i));let D=c?.filter(_=>_.$fieldType==="link");D&&D.length>0&&a.push(...Jt(D,F,`${t}.${o.$var}`,i,s));let C=c?.filter(_=>_.$fieldType==="role");C&&C.length>0&&a.push(...Kt(C,F,`${t}.${o.$var}`,i,s));}y&&a.push(y.sort),typeof $=="number"&&a.push(M(`offset ${$};`,i)),typeof g=="number"&&a.push(M(`limit ${g};`,i)),a.push(M("};",n));}return a},Jt=(e,t,r,n,s)=>{let i=n+1,a=[];for(let o of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:d,$filterByUnique:l,$playedBy:f,$thing:h,$sort:$,$offset:g,$limit:m}=o,b=o[oe],F=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${F}.${o.$var}": {`,n)),a.push(M("match",i));let y=`${t}${Ht}${o.$var}`;if(a.push(M(`$${y} isa ${o.$thing};`,i)),o.$filter||o.$id){let L=ot(s,o),D=o.$id?{[L]:o.$id}:{},C={...o.$filter,...D};a.push(pt({$filter:C,$var:y,$thing:o.$thing,schema:s,depth:i}));}let R=Yt({schema:s,$thing:h,$var:y,$sort:$,depth:i});if(R&&a.push(R.match),o.$target==="role"?a.push(M(`$${t}_intermediary (${o.$plays}: $${t}, ${f.plays}: $${y}) isa ${o.$intermediary};`,i)):a.push(M(`$${y} (${o.$plays}: $${t});`,i)),c){let L=`M_${v4()}`;a.push(M(`?queryPath${L} = "${b}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${L} as "queryPath";`,i));let D=c?.filter(J=>J.$fieldType==="data");D&&D.length>0&&a.push(...vt(D,y,i));let C=c?.filter(J=>J.$fieldType==="link");C&&C.length>0&&a.push(...Jt(C,y,`${t}.${o.$var}`,i,s));let _=c?.filter(J=>J.$fieldType==="role");_&&_.length>0&&a.push(...Kt(_,y,`${t}.${o.$var}`,i,s));}R&&a.push(R.sort),typeof g=="number"&&a.push(M(`offset ${g};`,i)),typeof m=="number"&&a.push(M(`limit ${m};`,i)),a.push(M("};",n));}return a},ko=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Yt=e=>{let{$var:t,$thing:r,schema:n,$sort:s,depth:i}=e,a=K(n,r),o=[],c=[];if(s?.forEach(p=>{let u=ko(p),d=a.dataFields?.find(h=>h.path===u.field);if(!d)throw new Error(`"${r}" does not have data field "${u.field}"`);let l=`${u.field}_${v4()}`;o.push(M("{",i)),o.push(M(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),o.push(M("not {",i+1)),o.push(M(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),o.push(M(`$${l}_2 < $${l}_1;`,i+2)),o.push(M("};",i+1)),o.push(M(`?${l}_ = $${l}_1;`,i+1)),o.push(M("} or {",i)),o.push(M(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),o.push(M(`?${l}_ = "~";`,i+1)),o.push(M("};",i)),o.push(M(`?${l} = ?${l}_;`,i));let f=u.desc?"desc":"asc";c.push(`?${l} ${f}`);}),o.length!==0)return {match:o.join(""),sort:M(`sort ${c.join(", ")};`,i)}};var Ln=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:s,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,o)=>{let c=r[o],p=t[o];return xo(a,c,p,n,s)})},xo=(e,t,r,n,s)=>e.length===0?null:r.$filterByUnique?Sn(e[0],t,n,s):e.map(i=>Sn(i,t,n,s)),Sn=(e,t,r,n)=>{let{dataFields:s,currentSchema:i,linkFields:a,roleFields:o,schemaValue:c}=Gt(e,r),p=Xt(s,i,n),u=er(a,r,n),d=Zt(o,r,n),l=t?.$fields?.every(h=>!i?.idFields?.includes(typeof h=="string"?h:h.$path));return {...u,...d,...c,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...l?Object.fromEntries(Object.entries(p).filter(([h])=>!i?.idFields?.includes(h))):p}},Gt=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),s=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");s?.length>0&&s.forEach(f=>{let h=f.replace(/\.\$multiVal$/,""),$=e[f][0][h].attribute;e[n][h]=$;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let o=i.type,c={$thing:o.label,$thingType:o.root,[oe]:e.queryPath.value},p={[`$${c.$thingType}`]:c.$thing},u=N(t,p),d=r.filter(f=>{let h=pe(f.split(".").pop());return !f.endsWith(".$dataFields")&&u.linkFields?.some($=>$.path===h)}).map(f=>{let h=pe(f.split(".").pop()),$=pe(u.linkFields?.find(g=>g.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),l=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&u.thingType==="relation"&&u.roles?.[h]}).map(f=>{let h=pe(f.split(".").pop());return {$roleFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:u.roles[h].cardinality}});return {dataFields:i,schemaValue:c,currentSchema:u,linkFields:d,roleFields:l}},Xt=(e,t,r)=>{let{$metaData:n}=e,{as:s}=jo(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).map(([a,o])=>{let c=t.dataFields?.find(l=>l.path===a||l.dbPath===a),p=a==="id",u=Array.isArray(s)?s.find(l=>l[a])?.[a]:a,d;if(c?.cardinality==="ONE"){if(d=o[0]?o[0].value:r.query?.returnNulls?null:void 0,c.contentType==="DATE"||c.contentType==="FLEX"&&o[0].type.value_type==="datetime"?d=d&&`${d}Z`:c.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[u,d],["$id",d]].filter(([l,f])=>f!==void 0)}else if(c?.cardinality==="MANY"){if(!isArray(o))throw new Error("Typedb fetch has changed its format");if(o.length===0)return r.query?.returnNulls?[[u,null]]:[];c.contentType==="DATE"?d=o.map(l=>`${l.value}Z`):c.contentType==="FLEX"?d=o.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):c.contentType==="JSON"?d=o.map(l=>l.value&&JSON.parse(l.value)):d=o.map(l=>l.value);}return [[u,d]].filter(([l,f])=>f!==void 0)}).flat();return Object.fromEntries([...i])},Zt=(e,t,r)=>{let n={};return e.forEach(s=>{let{$roleFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Qn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:b}=Gt(f,t),F=Xt(h,$,r);if(p==="T")return F.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...F};return u==="true"&&$?.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...b}}});l.length>0?n[c]=o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[c]=null);}),n},er=(e,t,r)=>{let n={};return e.forEach(s=>{let{$linkFields:i,$metaData:a,$cardinality:o}=s,{as:c,justId:p,idNotIncluded:u,filterByUnique:d}=Qn(a);if(c===null)return;let l=i.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:b}=Gt(f,t),F=Xt(h,$,r);if(p==="T")return F.id;{let y=er(g,t,r),R=Zt(m,t,r),L={...F};return u==="true"&&$.idFields?.forEach(D=>delete L[D]),{...L,...y,...R,...b}}});n[c]=l.length>0?o==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},Qn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,s=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),o=e.match(n),c=e.match(s);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:o?o[1]:null,filterByUnique:c?c[1]:null}},jo=e=>{try{let r=(s=>{let i=s.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,o,c)=>/^{.*}$/.test(c)?`:${c}`:`:${o}"${c}"`),i=i.replace(/\[([^\]]+)\]/g,(a,o)=>`[${o.split(",").map(c=>c.trim().startsWith("{")&&c.trim().endsWith("}")?c.trim():`"${c.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var $t=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,s=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!s)throw new Error("Client not found");n=await s.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:s,session:n});}return {client:s,session:n}};var Rn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,s=new TypeDBOptions;s.infer=!0;let{session:i}=await $t(r,n),a=await i.transaction(TransactionType.READ,s),[o,c]=await tryit(parallel)(t.length,t,async p=>await a.query.fetch(p).collect());if(o){await a.rollback();let p=o;throw new Error(`Error running TQL query: ${p.errors}`)}return await a.close(),c};var Ho=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,vo=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ko=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,tr=j("error","error",x((e,t)=>({...e,error:t.error}))),Jo=ye("build",{build:z(async e=>Mn({queries:e.bql.queries,schema:e.schema}),j("done","run",x(vo)),tr),run:z(async e=>Rn({dbHandles:e.handles,tqlRequest:pe(e.tql.queries),config:e.config}),j("done","parse",x(Ko)),tr),parse:z(async e=>Ln({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:pe(e.tql.res)}),j("done","success",x(Ho)),tr),success:ae(),error:ae()},e=>e),Yo=async e=>new Promise((t,r)=>{$e(Jo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Dn=async(e,t,r,n,s)=>Yo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:s,error:null});var Go=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,rr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,mt=j("error","error",x((e,t)=>({...e,error:t.error}))),Xo=ye("enrich",{enrich:z(async e=>(e.config.query?.debugger&&console.log(`originalBQLQuery[${ne}]`,JSON.stringify(e.bql.raw)),Ur(e.bql.raw,e.schema)),j("done","adapter",x(Go)),mt),adapter:z(async e=>{let t={};e.bql.queries?.forEach((o,c)=>{let p=e.bql.raw[c],u=K(e.schema,o.$thing),{id:d}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let l=t[d];l.rawBql.push(p),l.bqlQueries.push(o),l.indices.push(c);});let r=Object.values(t),n=r.map(o=>{if(o.db==="typeDB")return Dn(o.rawBql,o.bqlQueries,e.schema,e.config,e.handles);if(o.db==="surrealDB")return Fn(o.bqlQueries,e.schema,e.config,o.client);throw new Error(`Unsupported DB "${JSON.stringify(o,null,2)}"`)}),s=await Promise.all(n),i=r.flatMap((o,c)=>{let p=s[c];return o.indices.map((u,d)=>({index:u,result:p[d]}))});return i.sort((o,c)=>o.index<c.index?-1:o.index>c.index?1:0),i.map(({result:o})=>o)},j("done","postHooks",x(rr)),mt),postHooks:z(async e=>un(e.schema,pe(e.bql.queries),pe(e.bql.res)),j("done","clean",x(rr)),mt),clean:z(async e=>dn(e.config,pe(e.bql.res)),j("done","success",x(rr)),mt),success:ae(),error:ae()},e=>e),Zo=async e=>new Promise((t,r)=>{$e(Xo,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>Zo({bql:{raw:e},schema:t,config:r,handles:n,error:null});var nr="___",ts=Symbol.for("grandChildOfCreate"),Cn=async(e,t,r,n)=>{let s=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],i=(E,B)=>Object.keys(E).filter(T=>!T.startsWith("$")&&!s.includes(T)&&E[T]!==void 0?B?!N(t,E).dataFields?.find(w=>w.path===T):!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:E,key:B,value:T})=>{E&&B&&!B.includes("$")&&!s.includes(B)&&isObject(E)?(Array.isArray(E[B])?E[B]:[E[B]]).forEach(w=>{if(isObject(w)){if(E.$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`)}}):!E&&isObject(T)&&(a.includes(T.$op)||a.push(T.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let c=(E=>{let B=(T,S)=>{let w=[],Q={},A=["$op","$bzId","$parentKey"],U=["$relation","$entity","$id",...A];for(let q in T)if(!A.includes(q)&&!(U.includes(q)&&!S))if(!q.includes("$")&&(isObject(T[q])||Array.isArray(T[q]))){let Z=rs(T[q]);if(Array.isArray(Z)&&Z.length>0)Z.forEach(be=>{let Ee={$path:q,...B(be),...be.$filter&&{$as:be.$bzId}};w.find(Y=>Y.$path===Ee.$path&&!Y.$filter)||(w=[...w,Ee]);});else {let be={$path:q,...B(Z),...!Z.$filter&&{$as:Z.$bzId}};w=[...w,be];}}else Q[q]=T[q];return {...Q,$fields:w}};return E.map(T=>B(T,!0))})(Array.isArray(e)?e:[e]),u=(await ze(c,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,d=(E,B)=>{let T=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:S}=E,w=S?.beforePath||"root",Q=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${w}.${Q}___${S.key}`,ids:T,key:B}}else return {beforePath:"root",ids:T,key:B}},l=(E,B)=>{let T=E?.beforePath||"root";if(typeof T!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${T}.${S}___${E?.key}`},f=E=>{if(E.includes("[")&&E.includes("]")){let[B,T,S]=E.split(/[[\]]/);return T.split(",").map(Q=>`${B}${Q}${S}`)}else return [E]},h={};(E=>produce(E,B=>traverse(B,({key:T,parent:S})=>{if(S&&T&&S.$id&&!T.includes("$")){let w=d(S,T),Q=l(w);if(Array.isArray(S[T])){let A=[];S[T].forEach(U=>{isObject(U)?(U.$objectPath=w,A.push(U.$id.toString())):U&&A.push(U.toString());}),h[Q]={$objectPath:w,$ids:A};}else {let A=S[T];isObject(A)?(h[Q]={$objectPath:w,$ids:[A.$id.toString()]},A.$objectPath=w):A?h[Q]={$objectPath:w,$ids:[A.toString()]}:A===null&&(h[Q]=null);}}})))(u||{});let g=E=>produce(E,B=>traverse(B,({key:T,value:S,parent:w})=>{w&&T&&!T.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(w)&&(Array.isArray(w[T])?w[T].forEach(Q=>{typeof Q!="string"&&(Q.$objectPath=d(w,T),Q.$parentIsCreate=w.$op==="create",Q[ts]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[T])&&(w[T].$parentIsCreate=w.$op==="create",w[T][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[T].$objectPath=d(w,T)));})),m=g(e),b=E=>{let B=[];return E.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let w=l({...S.$objectPath,key:S.$bzId}),Q=h[w];Q&&(Array.isArray(Q.$ids)?Q.$ids:[Q.$ids]).forEach(U=>{let q={...S,$id:U,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};B.push(q);});}else {let w=l(S.$objectPath),Q=h[w];Q?Q?.$ids?.forEach(A=>{let U={...S,$id:A,$bzId:`T4_${v4()}`};B.push(U);}):B.push(S);}else B.push(S);}),B.map(S=>{let w={...S};return i(w,!0).forEach(Q=>{let A=Array.isArray(w[Q])?w[Q]:[w[Q]],U=b(A);w[Q]=U;}),w})},F=b(Array.isArray(m)?m:[m]),y=g(F),L=(E=>{let B=T=>{let S=Y=>{let X=[],H=[],P=[];return Y.forEach(W=>{let ie=i(W,!0);if(ie.length>0){let O=!1;ie.forEach(V=>{(Array.isArray(W[V])?W[V]:[W[V]]).filter(te=>!te.$id&&!te.id&&typeof W=="object").length&&(O=!0);}),O?X.push(W):H.push(W);}else W.$id?P.push({...W,$bzId:W.$tempId||W.$bzId}):P.push({...W,$bzId:W.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:X,operationWithoutMultiples:H,otherOps:P}},{operationWithMultiples:w,operationWithoutMultiples:Q,otherOps:A}=S(T),U=Y=>{let H=(()=>{let V={};for(let le in Y){let G=N(t,Y);!le.startsWith("$")&&G.dataFields?.find(te=>te.path===le)&&(V[le]=Y[le]);}return V})(),P=Object.keys(Y),W=i(Y,!0),ie=[],O=(V,le)=>{if(V===W.length){let te={...le};P.forEach(ce=>{ce.startsWith("$")&&(te[ce]=Y[ce]);}),ie.push({...te,...H});return}let G={...le,[W[V]]:Y[W[V]],...Qe(le),...H};O(V+1,G),O(V+1,le);};return O(0,{...Qe(Y)}),ie},q=[];return w.forEach(Y=>{let X=U(Y),H=[];X.forEach(P=>{let W=i(P,!0);if(P.$op==="create")H.push(P);else if(P.$id){let ie=l(P.$objectPath),O=[];if(W.forEach(V=>{let le=`${ie.includes("undefined")?"root":ie}.${P.$id}${nr}${V}`,G=h[le];P[V].filter(ce=>ce.$op==="unlink"||ce.$op==="delete"||ce.$op==="update").length>0?G?.$ids&&O.push({key:V,ids:G.$ids}):O.push({key:V,ids:[""]});}),O.length===W.length&&!H.find(V=>V.$id===P.$id))H.push(P);else {let V={...P,$bzId:P.$tempId||`T4_${v4()}`};W.forEach(G=>{let te=P[G].filter(ce=>ce.$id);te.length>0?V[G]=te:V[G]=void 0;}),i(V,!0).length>0&&H.push(V);}}else if(P.$objectPath){let ie=l(P.$objectPath),O=h[ie]?.$ids||[];O.forEach(V=>{let le=[];W.forEach(G=>{let te=`${ie}.${V}${nr}${G}`,ce=h[te];ce&&le.push({key:G,ids:ce.$ids});}),W.length===0?O.filter(te=>!H.find(ce=>ce.$id===te)).forEach(te=>{H.push({...P,$id:te,$bzId:P.$tempId||`PQT2_${v4()}`});}):le.length===W.length&&!H.find(G=>G.$id===V)&&(W.forEach(G=>{let te=`${l(P.$objectPath)}.${V}${nr}${G}`,ce=h[te]?.$ids||[],si=P[G].find(ke=>!ke.$id),dr=[...ce.map(ke=>({...si,$id:ke,$objectPath:{beforePath:P.$objectPath.beforePath,ids:ke,key:G}})),...P[G].filter(ke=>ke.$id)];dr.length>0&&(P[G]=dr);}),H.push({...P,$id:V,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else H.push(P);}),H.forEach(P=>{q.push(P);});}),[...q,...Q,...A].filter(Y=>i(Y).length>0?!0:Y.$op!=="update").map(Y=>{let X={...Y};return i(X,!0).forEach(H=>{let P=Array.isArray(X[H])?X[H]:[X[H]],W=B(P);X[H]=W;}),X})};return B(E)})(Array.isArray(y)?y:[y]),D=E=>E.map(B=>{let T=i(B,!0),S={...B};return T.forEach(w=>{let Q=Array.isArray(B[w])?B[w]:[B[w]],A=[],U=[],q=[],Z={},be=Rt(t,B,w);Q.filter(O=>O).forEach(O=>{O.$op==="replace"&&O.$id?(Z=O,Array.isArray(O.$id)?U=[...U,...O.$id]:U.push(O.$id)):O.$op==="create"&&be==="ONE"&&O.id?(Z=O,Array.isArray(O.id)?q=[...U,...O.id]:q.push(O.id)):A.push(O);});let Ee=l(Z.$objectPath),X=f(Ee).map(O=>h[O]),H=[];X.filter(O=>O!=null).forEach(O=>{H=[...H,...O?.$ids||[]];});let P=H.filter(O=>!U.includes(O)),W=U.filter(O=>!H.includes(O)),ie=Qe(Z);P.length>0&&A.push({...Z,$op:"unlink",$id:P,$bzId:Z.$tempId||`T4_${v4()}`,id:void 0,...ie}),W.length>0&&W.forEach(O=>{A.push({...Z,$op:"link",$id:O,$bzId:Z.$tempId||`T5_${v4()}`,...ie});}),q.length>0&&q.forEach(O=>{A.push({...Z,$op:"create",id:O,$bzId:Z.$tempId||`T6_${v4()}`,...ie});}),S[w]=D(A);}),S}),C=g(D(g(L)));(E=>produce(E,B=>traverse(B,T=>{let{key:S,value:w,parent:Q,meta:A}=T;S&&Q&&!S?.includes("$")&&S!=="$filter"&&!A.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(Q)&&(Array.isArray(w)?w:[w]).forEach(q=>{let Z=q.$filter?{...q.$objectPath,key:q.$filterBzId}:q.$objectPath,be=l(Z),Ee=h[be],Y=(P,W)=>P.every(ie=>W.includes(ie)),X=q.$id?Array.isArray(q.$id)?Y(q.$id,Ee&&Ee.$ids?Ee.$ids:[]):Ee?.$ids?.includes(q.$id):Ee,H=Rt(t,Q,q.$objectPath.key);if(q.$op==="link"&&X&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${l(q.$objectPath)}" because it is already occupied.`);if(q.$op)switch(q.$op){case"delete":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${q.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"update":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${q.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"unlink":if(!X&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${q.$id}" because it is not linked to $id:"${Q.$id}"`);break;case"link":if(X)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${q.$id}" because it is already linked to $id:"${Q.$id}"`);break;}});})))(C);let he=(E=>produce(E,B=>traverse(B,T=>{let{value:S,meta:w}=T;isObject(S)&&(S[Symbol.for("path")]=w.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(C);return [...Array.isArray(he)?he:[he]].sort((E,B)=>E.$op==="create"&&B.$op!=="create"?-1:E.$op!=="create"&&B.$op==="create"?1:0)},rs=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var In=(e,t)=>produce(e,n=>gt(t,n)),gt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(s=>gt(e,s,r));return}let n=K(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([s])=>{s.startsWith("$")||s.startsWith("%")||is(e,t,s,n);});},is=(e,t,r,n)=>{let s=t[r];if(!s)return;let i=n.dataFields?.find(o=>o.path===r);if(i){i.contentType==="JSON"&&s!=null&&(t[r]=JSON.stringify(s));return}let a=n.linkFields?.find(o=>o.path===r);if(a){let o=a.oppositeLinkFieldsPlayedBy[0]?.thing;gt(e,s,o);return}if(n.thingType==="relation"){let o=n.roles[r];if(!o)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[c]=o.playedBy||[];if(!c)throw new Error(`Role ${o.path} in ${n} is not played by anything`);gt(e,s,c.thing);}};var Pn=async(e,t,r,n)=>{let s=Array.isArray(e)?e:[e],i=s.map(c=>ir(c,!0)),o=(await ze(i,t,r,n)).bql.res;return s.map((c,p)=>{let u=K(t,c.$thing);return Nn({mut:c,node:o[p],schema:t,thing:u})})},kn=new Set(["$op","$bzId","$parentKey"]),ss=new Set(["$relation","$entity","$id",...kn]),ir=(e,t)=>{let r={};e.$fields?.forEach(s=>{typeof s=="string"?r[s]=s:r[s.$path]=s;});let n={};for(let s in e){if(kn.has(s)||ss.has(s)&&!t)continue;let i=e[s];s.startsWith("$")?n[s]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[s]={$path:s,...ir(i[0],!1)}):isObject(i)&&(r[s]={$path:s,...ir(i,!1)});}return n.$fields=Object.values(r),n},Nn=e=>{let{mut:t,node:r,schema:n,thing:s}=e,i=jn(s),a=ls(r);if(Array.isArray(t))return t.map(c=>{let p=a[c.$id];return p?An({mut:c,node:p,schema:n,thing:s,...i}):c});let o=a[t.$id];return An({mut:t,node:o,schema:n,thing:s,...i})},An=e=>{let{mut:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,{$fields:c,...p}=t;if(!r)return p;let u=xn({$fields:t.$fields,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}),d={...p,[Ne]:u};for(let l in t){if(l.startsWith("$"))continue;let f=t[l];if(i[l]||!f||typeof f!="object"){d[l]=f;continue}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);let g=K(n,$);d[l]=Nn({mut:f,schema:n,node:r[l],thing:g});}return d},xn=e=>{let{$fields:t,node:r,schema:n,thing:s,dataFieldMap:i,linkFieldMap:a,roleFieldMap:o}=e,c=t||as(s),p={$id:r.$id};return c.forEach(u=>{let d=typeof u!="string",l=d?u.$path:u,f=r[l];if(i[l]){p[l]=f;return}let $=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||o[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${s.name}" does not have field "${l}"`);if(!d){f&&(p[l]=Array.isArray(f)?f.map(On):On(f));return}let g=K(n,$),m=jn(g);p[l]=Array.isArray(f)?f.map(b=>qn({...m,$fields:u.$fields,value:b,schema:n,thing:g})):qn({...m,$fields:u.$fields,value:f,schema:n,thing:g});}),p},as=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},On=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},qn=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})},jn=e=>{let t=Object.fromEntries(e.dataFields?.map(s=>[s.path,s])||[]),r=Object.fromEntries(e.linkFields?.map(s=>[s.path,s])||[]),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 or=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 Un=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 f=l.$op,h=`$${l.$bzId}`,$=N(r,l),{idFields:g,defaultDBConnector:m}=$,b=m?.path||l.$thing,F=l.$id,y=g?.[0],R=listify(l,(I,k)=>{if(I.startsWith("$")||I.startsWith("%")||I===y||k===void 0||k===null)return "";let E=$.dataFields?.find(S=>S.path===I);if(!E?.path)return "";let T=E.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(E.contentType))return `has ${T} '${k}'`;if(["NUMBER","BOOLEAN"].includes(E.contentType))return `has ${T} ${k}`;if(E.contentType==="DATE"){if(Number.isNaN(k.valueOf()))throw new Error("Invalid format, Nan Date");return k instanceof Date?`has ${T} ${k.toISOString().replace("Z","")}`:`has ${T} ${new Date(k).toISOString().replace("Z","")}`}if(E.contentType==="FLEX"){let S=`bza${Ae()}`,w=isArray(k)?k.map(Q=>or(Q)):or(k);if(Array.isArray(w))throw new Error("Array in FLEX fields not supported yet");return `has ${T} $${S}; $${S} '${S}' isa ${T}, has ${w.type}Attribute ${w.value}`}throw new Error(`Unsupported contentType ${E.contentType}`)}).filter(I=>I),L=`${h}-atts`,D=listify(l,I=>{if(I.startsWith("$")||I.startsWith("%")||I===y)return "";let k=$.dataFields?.find(T=>T.path===I);if(!k?.path)return "";let B=k.dbPath;return `{${L} isa ${B};}`}).filter(I=>I),C=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,_=F?[`has ${y} ${C}`]:[],J=[..._,...R].filter(I=>I).join(","),he=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[b,..._].filter(I=>I).join(",")};`;if(f==="update"){if(!D.length)throw new Error("update without attributes");return `${h} isa ${[b,..._].filter(I=>I).join(",")}, has ${L};
122
+ ${D.join(" or ")};`}return ""},v=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[b,..._].filter(I=>I).join(",")};`:"";if(st(l))return {op:f,deletionMatch:he(),insertionMatch:v(),insertion:f==="create"?`${h} isa ${[b,J].filter(I=>I).join(",")};`:f==="update"&&R.length?`${h} ${R.join(",")};`:"",deletion:f==="delete"?`${h} isa ${b};`:f==="update"&&D.length?`${h} has ${L};`:""};throw new Error("in attributes")},s=l=>{let f=l.$op,h=N(r,l),$=`$${l.$bzId}`,g=l.$id,m=h.defaultDBConnector?.path||l.$thing,b="roles"in h?listify(h.roles,k=>k):[],F="roles"in h?mapEntries(h.roles,(k,E)=>[k,E.dbConnector?.path||k]):{},y=listify(l,(k,E)=>{if(!b.includes(k))return null;if(!("roles"in h))throw new Error("This should have roles! ");let B=F[k];return Array.isArray(E)?E.map(T=>({path:B,id:T})):{path:B,id:E}}).filter(k=>k).flat(),R=y.map(k=>{if(!k?.path)throw new Error("Object without path");return `${k.path}: $${k.id}`}),L=y.length>0?`( ${R.join(" , ")} )`:"",D=l[Ie];if(!D)throw new Error("[internal error] Symbol edgeType not defined");let C=L?`${$} ${L} ${D==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",_=`${$} ${D==="linkField"||f==="delete"?`isa ${m}`:""}`,J=()=>C?f==="link"?`${C};`:f==="create"?`${C}, has id '${g}';`:"":"",he=()=>C&&f==="match"?`${C};`:"",v=()=>C?f==="delete"?`${C};`:f==="match"?`${C};`:"":"",I=()=>C?f==="delete"?`${_};`:f==="unlink"?`${$} ${L};`:"":"";return {deletionMatch:v(),insertionMatch:he(),deletion:I(),insertion:J(),op:""}},i=(l,f)=>{let h=f==="edges"?s:n;if(Array.isArray(l))return l.map(y=>{let{preDeletionBatch:R,insertionMatch:L,deletionMatch:D,insertion:C,deletion:_}=h(y);return shake({preDeletionBatch:R,insertionMatch:L,deletionMatch:D,insertion:C,deletion:_},J=>!J)}).filter(y=>y);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:b,deletion:F}=h(l);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:b,deletion:F},y=>!y)},a=i(e),o=Array.isArray(a)?a:[a],c=i(t,"edges"),p=Array.isArray(c)?c:[c],u=[...o,...p];return shake({insertionMatches:u.map(l=>l.insertionMatch).join(" ").trim(),deletionMatches:u.map(l=>l.deletionMatch).join(" ").trim(),insertions:u.map(l=>l.insertion).join(" ").trim(),deletions:u.map(l=>l.deletion).join(" ").trim()},l=>!l)};var Wn=async(e,t,r,n,s)=>{let i=[...t,...r],a=i.map(o=>{let c=e.insertions?.find(d=>d.get(`${o.$bzId}`))?.get(`${o.$bzId}`),p=o.$thing||o.$relation||o.$entity,u=p?K(n,p):void 0;if(o.$op==="create"||o.$op==="update"||o.$op==="link"){if(o.$op!=="update"&&!c&&o.$id)return {$id:o.$id,$error:"Does not exist or it's not linked to the parent"};let d=c?.asThing().iid,l=Object.entries(o).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,g])=>{if(u?.dataFields?.find(b=>b.path===$)?.contentType==="JSON")return h[$]=JSON.parse(g),h;if(o.$thingType==="relation"){let b=i.filter(F=>F.$id&&F.$bzId===g);return b.length===1?(h[$]=b[0].$id,h):(h[$]=g,h)}return h[$]=g,h},{});if(s.mutation?.noMetadata)return l;let f=o.$tempId&&!o.$tempId.startsWith("_:")?{$tempId:`_:${o.$tempId}`}:{};return {$dbId:d,...o,...l,[o.path]:o.$id,...f}}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(a)};var Vn=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 $t(t,r),s=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 s.query.delete(i);let o=a&&s.query.insert(a),c=o?await o.collect():void 0;return await s.commit(),{insertions:c}}catch(o){throw new Error(`Transaction failed: ${o.message}`)}finally{await s.close();}};var ps=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),fs=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),$s=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),ar=j("error","error",x((e,t)=>({...e,error:t.error}))),ms=ye("buildMutation",{buildMutation:z(async e=>Un(e.bql.things,e.bql.edges,e.schema),j("done","runMutation",x(fs)),ar),runMutation:z(async e=>Vn(e.tql.mutation,e.handles,e.config),j("done","parseMutation",x($s)),ar),parseMutation:z(async e=>Wn(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),j("done","success",x(ps)),ar),success:ae(),error:ae()},e=>e),ys=async e=>new Promise((t,r)=>{$e(ms,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),zn=async(e,t,r,n,s,i,a)=>ys({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:s,config:i,handles:a,error:null});var Hn=async(e,t)=>{let r=a=>{let{$filter:o,$thing:c,$bzId:p,$op:u,$id:d,$tempId:l}=a,f=K(t,c),{usedDataFields:h}=ue(f,a),{idFields:$}=f,g=d||a[$[0]],m=(a[Fe]?.$things||[c]).map(ee),b=de(a,E=>E.startsWith("$")),F=de(a,E=>!E.startsWith("$")),y=JSON.stringify(F),R=Object.entries(b).map(([E,B])=>E=="$tempId"?`'$tempId': '_:${B}'`:`'${E}': '${B}'`).join(","),L=a[rt],D=h.filter(E=>!$.includes(E)).map(E=>{let B=f.dataFields?.find(S=>S.path===E||S.dbPath===E);if(!B)throw new Error(`Data field schema not found for ${E}`);let T=a[E];return T===null?`${E} = NONE`:`${E} = ${Ze(T,B.contentType)}`}).filter(Boolean),C=`$\u27E8${l||p}\u27E9`,_=L?.bzId?`array::flatten($\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:g?isArray(g)?m.flatMap(E=>g.map(B=>`${E}:\u27E8${B}\u27E9`)).join(", "):m.map(E=>`${E}:\u27E8${g}\u27E9`).join(", "):!0,J=(()=>{if(L?.bzId){let E=`array::flatten($\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return g?isArray(g)?`${E}[? $this.id() IN [${g.map(B=>`'${B}'`).join(", ")}] ]`:`${E}[? $this.id() IN ['${g}'] ]`:E}else return g?isArray(g)?m.flatMap(E=>g.map(B=>`${E}:\u27E8${B}\u27E9`)).join(", "):m.map(E=>`${E}:\u27E8${g}\u27E9`).join(", "):m.join(", ")})(),he=o?`WHERE ${fe(ge(o,c,t))}`:"",v=D.length>0?`SET ${D.join(", ")}`:"",I=`VALUE (CREATE ONLY Delta SET input = ${y}, meta = {${R}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,k="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return l?"":`LET ${C} = (SELECT VALUE id FROM ${J} ${he});`;if(a.$op==="create"){if(isArray(g))throw new Error("Cannot create multiple things at once");let E=ee(c);return `LET ${C} = (CREATE ONLY ${E}:\u27E8${g}\u27E9 ${v} RETURN ${I});`}if(a.$op==="update")return `LET ${C} = IF (${_}) THEN (UPDATE ${J} ${v} ${he} RETURN ${I}) END;`;if(a.$op==="delete")return `LET ${C} = IF (${_}) THEN (DELETE ${J} ${he} RETURN ${k}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:o,$bzId:c,$op:p,$tempId:u}=a,d=K(t,o),{usedRoleFields:l}=ue(d,a),f=`$\u27E8${u||c}\u27E9`,h="roles"in d?l.flatMap(m=>{let b=d.roles[m];if(!b)throw new Error(`Role field schema not found for ${m}`);let{cardinality:F}=b,y=isArray(a[m])?a[m].map(R=>`$\u27E8${R}\u27E9`):[`$\u27E8${a[m]}\u27E9`];if(F==="ONE"){if(y.length>1)throw new Error(`${p==="link"?"Linking":"Replacing"} multiple values to a ONE field ${m}`);switch(p){case"link":case"replace":return `${m} = ((type::is::array(${y[0]}) && array::len(${y[0]})==1) && ${y[0]}[0]) || ${y[0]}`;case"unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${p} for ONE cardinality`)}}else if(F==="MANY"){let R=`array::flatten([${y}])`;switch(p){case"link":return `${m} += ${R}`;case"unlink":return `${m} -= ${R}`;case"replace":return `${m} = ${R}`;default:throw new Error(`Unsupported operation ${p} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${F}`)}):[],$=h.length>0?`${h.join(", ")}`:"",g=$?`SET ${$}`:"";return `IF ${f} THEN (UPDATE ${f} ${g} RETURN VALUE id) END; ${f};`},s=a=>{let{$thing:o,$op:c}=a,p=K(t,o),u=ee(o),{usedRoleFields:d}=ue(p,a);if(!["create","delete"].includes(c))throw new Error("Arcs can only be created or deleted");let[l,f]=d,h=isArray(a[l])?a[l]:[a[l]],$=isArray(a[f])?a[f]:[a[f]];if(c==="create"){if(d.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let g=de(a,C=>!C.startsWith("$")),b=`(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 )`,y=p.roles[l].cardinality==="MANY",L=p.roles[f].cardinality==="MANY";return h.flatMap(C=>$.flatMap(_=>`FOR $node1 IN fn::as_array($\u27E8${C}\u27E9) { FOR $node2 IN fn::as_array($\u27E8${_}\u27E9) { CREATE ONLY ${u} SET ${l} = ${y?"fn::as_array($node1)":"$node1"}, ${f} = ${L?"fn::as_array($node2)":"$node2"} RETURN ${b}; } }`))}if(c==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${l}) CONTAINSANY $\u27E8${h}\u27E9 AND fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 RETURN BEFORE`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(s)]};var vn=async(e,t,r)=>{let n=`
123
123
  BEGIN TRANSACTION;
124
124
  ${t.join(";")};
125
125
  LET $DELTAS = SELECT * FROM Delta;
@@ -129,9 +129,8 @@ limit ${p};`),d.join(`
129
129
  LET $LOGS = SELECT * FROM LOG;
130
130
  RETURN $LOGS;
131
131
  COMMIT TRANSACTION;
132
- `;r.mutation?.debugger&&console.log(`>>> batchedMutation[${ne}]`,JSON.stringify({batchedMutation:n}));try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Xn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Yn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Yn(s,r)})},Yn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=de(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?de(s,i=>!i.startsWith("$")):s};var Es=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Bs=(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}}},bs=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},lr=j("error","error",x((e,t)=>({...e,error:t.error}))),Fs=ye("buildMutation",{buildMutation:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> surqlMachine/buildMutation[${ne}]`,JSON.stringify(e.bql.flat)),vn(e.bql.flat,e.schema)),j("done","runMutation",x(Bs)),lr),runMutation:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> surqlMachine/runMutation[${ne}]`,JSON.stringify(e.surql.mutations)),Kn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config)),j("done","parseMutation",x(bs)),lr),parseMutation:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> surqlMachine/parseMutation[${ne}]`,JSON.stringify(e.surql.res)),Xn({res:e.surql.res,config:e.config,schema:e.schema})),j("done","success",x(Es)),lr),success:ae(),error:ae()},e=>e),Ts=async e=>new Promise((t,r)=>{$e(Fs,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ei=async(e,t,r,n,s,i)=>Ts({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ri=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=ue(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...de(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[rt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=de(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(F=>n(F,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let b=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([F,y])=>{let R=b.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:F});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(F=>n(F,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(F=>F.path===g),b=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([F,y])=>{b.filter(L=>y.includes(L.$op)).forEach(L=>{let D=de(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:F});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{b.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ni=ae,He=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,ws=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Ms=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Ss=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ls=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/enrich[${ne}]`,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)),Qs=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/preQuery[${ne}]`,JSON.stringify(e.bql.enriched)),In(e.bql.enriched,e.schema,e.config,e.handles)),Rs=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/preQueryDependencies[${ne}]`,JSON.stringify(e.bql.enriched)),kn(e.bql.enriched,e.schema,e.config,e.handles)),Ds=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/parseBQL[${ne}]`,JSON.stringify(e.bql.enriched)),Kr(e.bql.enriched,e.schema)),Cs=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/flattenBQL[${ne}]`,JSON.stringify(e.bql.enriched)),ri(e.bql.enriched,e.schema)),Is=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}.`)},As=e=>_e(e.bql.enriched),Pe=j("error","error",x((e,t)=>({...e,error:t.error}))),Os=ye("stringify",{stringify:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/stringify[${ne}]`,JSON.stringify(e.bql.raw)),An(e.bql.raw,e.schema)),j("done","enrich",x(He)),Pe),enrich:z(Ls,j("done","preQuery",kt(Is),x(He)),j("done","parseBQL",x(He)),Pe),preQuery:z(Qs,j("done","preHookDependencies",kt(As),x(He)),j("done","parseBQL",x(He)),Pe),preHookDependencies:z(Rs,j("done","enrich",x(He)),Pe),parseBQL:z(Ds,j("done","flattenBQL",x(ws)),Pe),flattenBQL:z(Cs,j("done","adapter",x(Ms)),Pe),adapter:z(async e=>{e.config.mutation?.debugger&&console.log(`>>> mutationMachine/adapter[${ne}]`,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 Hn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ei(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",x(Ss)),Pe),success:ni(),error:ni()},e=>e),qs=async e=>new Promise((t,r)=>{$e(Os,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ii=async(e,t,r,n)=>qs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var bt=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 Ps;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 cr=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 s=new bt({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.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 o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);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 a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Mr(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 yr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...Tt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(ii)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.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();});}},vu=cr;//! Todo: delete when this works with the new $thing and $thingType fields
132
+ `;r.mutation?.debugger&&console.log(`>>> batchedMutation[${ne}]`,JSON.stringify({batchedMutation:n}));try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Gn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Jn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Jn(s,r)})},Jn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=de(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?de(s,i=>!i.startsWith("$")):s};var Es=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Bs=(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}}},bs=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},lr=j("error","error",x((e,t)=>({...e,error:t.error}))),Fs=ye("buildMutation",{buildMutation:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> surqlMachine/buildMutation[${ne}]`,JSON.stringify(e.bql.flat)),Hn(e.bql.flat,e.schema)),j("done","runMutation",x(Bs)),lr),runMutation:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> surqlMachine/runMutation[${ne}]`,JSON.stringify(e.surql.mutations)),vn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config)),j("done","parseMutation",x(bs)),lr),parseMutation:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> surqlMachine/parseMutation[${ne}]`,JSON.stringify(e.surql.res)),Gn({res:e.surql.res,config:e.config,schema:e.schema})),j("done","success",x(Es)),lr),success:ae(),error:ae()},e=>e),Ts=async e=>new Promise((t,r)=>{$e(Fs,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Zn=async(e,t,r,n,s,i)=>Ts({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ti=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=ue(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...de(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[rt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=de(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(F=>n(F,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let b=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([F,y])=>{let R=b.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:F});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(F=>n(F,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(F=>F.path===g),b=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([F,y])=>{b.filter(L=>y.includes(L.$op)).forEach(L=>{let D=de(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:F});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{b.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ri=ae,He=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,ws=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Ms=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Ss=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ls=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/enrich[${ne}]`,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)),Qs=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/preQuery[${ne}]`,JSON.stringify(e.bql.enriched)),Cn(e.bql.enriched,e.schema,e.config,e.handles)),Rs=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/preQueryDependencies[${ne}]`,JSON.stringify(e.bql.enriched)),Pn(e.bql.enriched,e.schema,e.config,e.handles)),Ds=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/parseBQL[${ne}]`,JSON.stringify(e.bql.enriched)),vr(e.bql.enriched,e.schema)),Cs=async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/flattenBQL[${ne}]`,JSON.stringify(e.bql.enriched)),ti(e.bql.enriched,e.schema)),Is=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}.`)},As=e=>_e(e.bql.enriched),Pe=j("error","error",x((e,t)=>({...e,error:t.error}))),Os=ye("stringify",{stringify:z(async e=>(e.config.mutation?.debugger&&console.log(`>>> mutationMachine/stringify[${ne}]`,JSON.stringify(e.bql.raw)),In(e.bql.raw,e.schema)),j("done","enrich",x(He)),Pe),enrich:z(Ls,j("done","preQuery",kt(Is),x(He)),j("done","parseBQL",x(He)),Pe),preQuery:z(Qs,j("done","preHookDependencies",kt(As),x(He)),j("done","parseBQL",x(He)),Pe),preHookDependencies:z(Rs,j("done","enrich",x(He)),Pe),parseBQL:z(Ds,j("done","flattenBQL",x(ws)),Pe),flattenBQL:z(Cs,j("done","adapter",x(Ms)),Pe),adapter:z(async e=>{e.config.mutation?.debugger&&console.log(`>>> mutationMachine/adapter[${ne}]`,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 zn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return Zn(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",x(Ss)),Pe),success:ri(),error:ri()},e=>e),qs=async e=>new Promise((t,r)=>{$e(Os,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ni=async(e,t,r,n)=>qs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var bt=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 Ps;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 cr=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 s=new bt({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.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 o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);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 a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Mr(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 yr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...Tt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(ni)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.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();});}},vu=cr;//! Todo: delete when this works with the new $thing and $thingType fields
133
133
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
134
- //! Todo: Sandbox the function in computeFunction()
135
134
  //! reads all the insertions and gets the first match. This means each id must be unique
136
135
  //!old
137
136