@blitznocode/blitz-orm 0.15.2 → 0.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,35 +1,35 @@
1
- import {produce,enableMapSet,current,isDraft}from'immer';import {isObject,tryit,parallel,isArray,clone,shake,mapEntries,pick,listify,isDate,isSymbol,isEqual}from'radash';import {TypeDBOptions,TransactionType,SessionType,TypeDB,TypeDBCredential}from'typedb-driver';import No,{ConnectionStatus}from'surrealdb';import {traverse,getNodeByPath}from'object-traversal';import {nanoid,customAlphabet}from'nanoid';import'acorn';import {isSet}from'util/types';import {v4}from'uuid';import It,{z as z$1}from'zod/v4';var Ao=Object.defineProperty;var Oo=(e,t)=>{for(var r in t)Ao(e,r,{get:t[r],enumerable:true});};var Wt=new Set((process.env.BORM_LOG_TAGS||"").split(",").map(e=>e.trim()).filter(e=>!!e)),fe=(e,...t)=>{(Wt.has("*")||(Array.isArray(e)?e.some(n=>Wt.has(n)||n==="*"):Wt.has(e)||e==="*"))&&console.log(...t);},Z=(...e)=>fe("debug",...e);var ko=3e5,Co={attempts:-1,retryDelay:1e3,retryDelayMax:6e4},Ze="SurrealClient",vt=(e,t,r)=>{let n,i=new Promise((o,s)=>{n=setTimeout(()=>s(new Error(r)),t);});return Promise.race([e,i]).finally(()=>clearTimeout(n))},Po=e=>e instanceof Error&&(e.message.includes("token has expired")||e.message.includes("token is invalid")),Bt=class{#e=new No;#n;#i;#o;#t=null;#r=false;constructor(t,r={}){this.#n=t,this.#i=r.queryTimeoutMs??ko,this.#o={...Co,...r.reconnect};}async connect(){if(this.#r)throw new Error("Client has been closed");if(this.#e.status===ConnectionStatus.Connected)return;if(this.#t)return this.#t;let{url:t,namespace:r,database:n,username:i,password:o}=this.#n;return fe([Ze,"info"],"Connecting to SurrealDB",{url:t,namespace:r,database:n}),this.#t=this.#e.connect(t,{namespace:r,database:n,auth:{username:i,password:o},versionCheck:false,reconnect:{enabled:true,...this.#o,retryDelayMultiplier:2,retryDelayJitter:.1},prepare:async s=>{fe([Ze,"info"],"prepare: refreshing token via signin()"),await s.signin({username:i,password:o});}}).then(()=>{fe([Ze,"info"],"Connected to SurrealDB");}).finally(()=>{this.#t=null;}),this.#t}async close(){this.#r||(this.#r=true,await this.#e.close().catch(()=>{}));}async#s(t){try{return await vt(t(),this.#i,"Query timeout")}catch(r){if(!Po(r))throw r;fe([Ze,"info"],"Token expired, refreshing via signin()",{status:this.#e.status,error:r instanceof Error?r.message:r});try{await vt(this.#e.signin({username:this.#n.username,password:this.#n.password}),this.#i,"Token refresh timeout"),fe([Ze,"info"],"Token refreshed successfully");}catch(n){throw fe([Ze,"info"],"Token refresh failed",{status:this.#e.status,error:n instanceof Error?n.message:n}),n}return vt(t(),this.#i,"Query timeout")}}async query(...t){if(this.#r)throw new Error("Client has been closed");return this.#s(()=>this.#e.query(...t))}async queryRaw(...t){if(this.#r)throw new Error("Client has been closed");return this.#s(()=>this.#e.queryRaw(...t))}get status(){return this.#e.status}};var Ht={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var Ur=e=>e.replace(/`/g,""),qo=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],le=e=>qo.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var Jt=e=>{if(typeof e=="string"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return `<datetime>"${e}"`;if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return JSON.stringify(e);if(["number","boolean"].includes(typeof e))return e;throw new Error(`Unsupported type ${typeof e}`)};var vr={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"},Ge=(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"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e)?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`<datetime>"${e}"`;case "FLEX":{let r=isArray(e)?e.map(n=>Jt(n)):Jt(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 _o=" ",Ue=e=>_o.repeat(e),Ft=(e,t)=>e.split(`
2
- `).map(r=>r.trim()?`${Ue(t)}${r}`:r).join(`
3
- `),zo=e=>{let t=`USE NS test;
1
+ import {enableMapSet,produce,isDraft,current}from'immer';import {isObject,tryit,parallel,isArray,clone,shake,mapEntries,listify,isDate,isSymbol,pick,isEqual}from'radash';import {TypeDBOptions,TransactionType,SessionType,TypeDB,TypeDBCredential}from'typedb-driver';import {Surreal,UnsupportedVersionError}from'surrealdb';import {traverse,getNodeByPath}from'object-traversal';import {nanoid,customAlphabet}from'nanoid';import'acorn';import {isSet}from'util/types';import {v4}from'uuid';import Ct,{z}from'zod/v4';var Oo=Object.defineProperty;var No=(e,t)=>{for(var r in t)Oo(e,r,{get:t[r],enumerable:true});};var Ht=new Set((process.env.BORM_LOG_TAGS||"").split(",").map(e=>e.trim()).filter(e=>!!e)),ue=(e,...t)=>{(Ht.has("*")||(Array.isArray(e)?e.some(n=>Ht.has(n)||n==="*"):Ht.has(e)||e==="*"))&&console.log(...t);},Z=(...e)=>ue("debug",...e);var Ue="SurrealClient",Co={enabled:true,attempts:-1,retryDelayMultiplier:1.2,retryDelayJitter:0},bt=class{#e=new Surreal;#s;#a;#l;#r=null;#c=false;#o=false;#t="disconnected";#n=null;#i="";constructor(t,r={}){this.#s=t,this.#a={...Co,...r.reconnect},this.#l=r.versionCheck??false;}async connect(){if(this.#o)throw new Error("Client has been closed");if(this.#t==="connected")return;if(this.#r)return this.#r;let{url:t,namespace:r,database:n,username:i,password:o}=this.#s;return ue([Ue,"info"],`Opening connection to ${t}`),this.#d(),this.#t="connecting",this.#r=this.#e.connect(t,{namespace:r,database:n,versionCheck:this.#l,reconnect:this.#a,authentication:async()=>({username:i,password:o})}).then(async()=>{await this.#u(),this.#t="connected",this.#i="",ue([Ue,"info"],"Connection established");}).catch(s=>{throw this.#i=s.message,s instanceof UnsupportedVersionError&&ue([Ue,"error"],"Unsupported SurrealDB version",{version:s.version,minimum:s.minimum,maximum:s.maximum}),s}).finally(()=>{this.#r=null;}),this.#r}async close(){this.#o||(this.#o=true,await this.#e.close().catch(()=>{}),this.#t="disconnected",this.#n=null);}async query(t,r){if(this.#o)throw new Error("Client has been closed");return typeof t=="string"?this.#e.query(t,r):this.#e.query(t)}get state(){return this.#t}get version(){return this.#n}get latestError(){return this.#i}#d(){this.#c||(this.#c=true,this.#e.subscribe("connecting",()=>{this.#t="connecting";}),this.#e.subscribe("reconnecting",()=>{this.#t="retrying";}),this.#e.subscribe("connected",()=>{this.#t="connected",this.#i="",ue([Ue,"info"],"Connection re-established");}),this.#e.subscribe("disconnected",()=>{this.#t="disconnected",this.#n=null;}),this.#e.subscribe("error",t=>{this.#i=t.message,ue([Ue,"error"],"Connection error",{error:t.message});}));}async#u(){try{let t=await this.#e.version();this.#n=t.version.replace(/^surrealdb-/,""),ue([Ue,"info"],`Database version ${this.#n}`);}catch{ue([Ue,"info"],"Database version unknown");}}};var Jt={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var zr=e=>e.replace(/`/g,""),Po=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],le=e=>Po.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var Ur=e=>{if(typeof e=="string"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return `<datetime>"${e}"`;if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return JSON.stringify(e);if(["number","boolean"].includes(typeof e))return e;if(typeof e=="object"&&e!==null)return JSON.stringify(e);throw new Error(`Unsupported type ${typeof e}`)};var Wr={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"},Ge=(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"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e)?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`<datetime>"${e}"`;case "FLEX":return Ur(e);default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var jo=" ",We=e=>jo.repeat(e),Tt=(e,t)=>e.split(`
2
+ `).map(r=>r.trim()?`${We(t)}${r}`:r).join(`
3
+ `),_o=e=>{let t=`USE NS test;
4
4
  USE DB test;
5
5
 
6
6
  BEGIN TRANSACTION;
7
7
  `,r=`-- ENTITIES
8
- ${Hr(e.entities)}`,n=`
8
+ ${vr(e.entities)}`,n=`
9
9
  -- RELATIONS
10
- ${Hr(e.relations)}`,i=Ko();return `${t}${r}${n}${i}COMMIT TRANSACTION;`},Hr=e=>Object.entries(e).map(([t,r])=>Vo(le(t),r,1)).join(`
10
+ ${vr(e.relations)}`,i=Jo();return `${t}${r}${n}${i}COMMIT TRANSACTION;`},vr=e=>Object.entries(e).map(([t,r])=>Vo(le(t),r,1)).join(`
11
11
 
12
- `),Vo=(e,t,r)=>{let n=`${Ue(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,i=Ft(`-- DATA FIELDS
13
- ${Uo(t.dataFields??[],e,r)}`,r+1),o=Ft(`
12
+ `),Vo=(e,t,r)=>{let n=`${We(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,i=Tt(`-- DATA FIELDS
13
+ ${zo(t.dataFields??[],e,r)}`,r+1),o=Tt(`
14
14
  -- LINK FIELDS
15
- ${Wo(t.linkFields??[],e,r)}`,r+1),s="roles"in t?Ft(`
15
+ ${Uo(t.linkFields??[],e,r)}`,r+1),s="roles"in t?Tt(`
16
16
  -- ROLES
17
- ${vo(t.roles,e,r)}`,r+1):"";return `${n}
18
- ${i}${o}${s}`},Uo=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let i=Jo(n.contentType,n.validations),o=`${Ue(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${o} VALUE ${s};`:""}return `${o} TYPE ${i};`}).filter(Boolean).join(`
19
- `),Wo=(e,t,r)=>e.map(n=>{let i=n.cardinality==="MANY"?`option<array<record<${n.$things.map(le).join("|")}>>>`:`option<record<${n.$things.map(le).join("|")}>>`,o=`${Ue(r)}DEFINE FIELD ${le(n.path)} ON TABLE ${t}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${o} VALUE ${s};`:""}if(n.target==="role"){let s=e.find(h=>h.target==="relation"&&h.relation===n.relation),l=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!l||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let d=n.cardinality==="ONE"?`record<${le(n.relation)}>`:`array<record<${le(n.relation)}>>`,c=le(n.pathToRelation||""),u=`${c}.${l}`,p=n.cardinality==="ONE"?`${o} VALUE <future> {RETURN SELECT VALUE ${u} FROM ONLY $this};`:`${o} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${u} || []) FROM ONLY $this)};`,f=s?.path?"":`${Ue(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${d}>;`;return [p,f].join(`
20
- `)}if(n.target==="relation")return `${`${Ue(r)}DEFINE FIELD ${le(n.path)} ON TABLE ${t} TYPE ${i};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
21
- `),vo=(e,t,r)=>Object.entries(e).map(([n,i])=>{let o=i.cardinality==="MANY"?`array<record<${i.$things.map(le).join("|")}>>`:`record<${i.$things.map(le).join("|")}>`,s=`${Ue(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${o}>;`,a=Ho(n,t,i,r);return `${s}
17
+ ${Wo(t.roles,e,r)}`,r+1):"";return `${n}
18
+ ${i}${o}${s}`},zo=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let i=Ho(n.contentType,n.validations),o=`${We(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${o} VALUE ${s};`:""}return `${o} TYPE ${i};`}).filter(Boolean).join(`
19
+ `),Uo=(e,t,r)=>e.map(n=>{let i=n.cardinality==="MANY"?`option<array<record<${n.$things.map(le).join("|")}>>>`:`option<record<${n.$things.map(le).join("|")}>>`,o=`${We(r)}DEFINE FIELD ${le(n.path)} ON TABLE ${t}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${o} VALUE ${s};`:""}if(n.target==="role"){let s=e.find(h=>h.target==="relation"&&h.relation===n.relation),l=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!l||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let d=n.cardinality==="ONE"?`record<${le(n.relation)}>`:`array<record<${le(n.relation)}>>`,c=le(n.pathToRelation||""),u=`${c}.${l}`,p=n.cardinality==="ONE"?`${o} VALUE <future> {RETURN SELECT VALUE ${u} FROM ONLY $this};`:`${o} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${u} || []) FROM ONLY $this)};`,f=s?.path?"":`${We(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${d}>;`;return [p,f].join(`
20
+ `)}if(n.target==="relation")return `${`${We(r)}DEFINE FIELD ${le(n.path)} ON TABLE ${t} TYPE ${i};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
21
+ `),Wo=(e,t,r)=>Object.entries(e).map(([n,i])=>{let o=i.cardinality==="MANY"?`array<record<${i.$things.map(le).join("|")}>>`:`record<${i.$things.map(le).join("|")}>`,s=`${We(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${o}>;`,a=vo(n,t,i,r);return `${s}
22
22
  ${a}`}).join(`
23
- `),Ho=(e,t,r,n)=>{let i=`update_${e}`,o=r.playedBy?.find(B=>B.target==="relation"),s=o?.pathToRelation,a=r.playedBy?.find(B=>B.target==="role"),l=a?.pathToRelation,d=o??a;if(!d)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=le(s??l),u=(B,g)=>B.map(({path:T,cardinality:w})=>`${T} ${g==="remove"?w==="ONE"?"=":"-=":w==="ONE"?"=":"+="} ${g==="remove"?w==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),p=r.impactedLinkFields?.map(B=>({path:B.path,cardinality:B.cardinality}))||[],h=[{path:c,cardinality:d.cardinality},...p],$=u(h,"remove"),E=u(h,"add"),m=`
23
+ `),vo=(e,t,r,n)=>{let i=`update_${e}`,o=r.playedBy?.find(B=>B.target==="relation"),s=o?.pathToRelation,a=r.playedBy?.find(B=>B.target==="role"),l=a?.pathToRelation,d=o??a;if(!d)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=le(s??l),u=(B,g)=>B.map(({path:T,cardinality:w})=>`${T} ${g==="remove"?w==="ONE"?"=":"-=":w==="ONE"?"=":"+="} ${g==="remove"?w==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),p=r.impactedLinkFields?.map(B=>({path:B.path,cardinality:B.cardinality}))||[],h=[{path:c,cardinality:d.cardinality},...p],$=u(h,"remove"),E=u(h,"add"),y=`
24
24
  IF ($before.${e}) THEN {UPDATE $before.${e} SET ${$}} END;
25
- IF ($after.${e}) THEN {UPDATE $after.${e} SET ${E}} END;`,y=`
25
+ IF ($after.${e}) THEN {UPDATE $after.${e} SET ${E}} END;`,m=`
26
26
  LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
27
27
  FOR $unlink IN $edges.deletions {UPDATE $unlink SET ${$};};
28
28
  FOR $link IN $edges.additions {${d.cardinality==="ONE"?`
29
29
  IF ($link.${c}) THEN {UPDATE $link.${c} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
30
30
  UPDATE $link SET ${E};
31
- };`;return Ft(`DEFINE EVENT ${i} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?m:y}
32
- };`,n+1)},Jo=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>Ge(n,e)).join("|")}`:vr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},Ko=()=>`
31
+ };`;return Tt(`DEFINE EVENT ${i} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?y:m}
32
+ };`,n+1)},Ho=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>Ge(n,e)).join("|")}`:Wr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},Jo=()=>`
33
33
  -- BORM TOOLS
34
34
  DEFINE FUNCTION fn::get_mutated_edges(
35
35
  $before_relation: option<array|record>,
@@ -51,7 +51,7 @@ ${a}`}).join(`
51
51
  DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
52
52
  RETURN (type::is::array($var) AND $var) OR [$var]
53
53
  };
54
- `,Jr=e=>zo(e);var Zo=e=>{let t=[],r=new Map;for(let n of e){let{dbPath:i,contentType:o}=n,s=`${i}-${o}`;r.has(s)||(r.set(s,true),t.push(n));}return t},Go=(e,t)=>{let r="",n=[];r+=`
54
+ `,Hr=e=>_o(e);var Xo=e=>{let t=[],r=new Map;for(let n of e){let{dbPath:i,contentType:o}=n,s=`${i}-${o}`;r.has(s)||(r.set(s,true),t.push(n));}return t},Zo=(e,t)=>{let r="",n=[];r+=`
55
55
  `;for(let a of Object.keys(t.entities).filter(l=>t.entities[l].defaultDBConnector.id===e)){let l=t.entities[a],{dataFields:d,linkFields:c,name:u}=l;if(r+=`${u} sub ${"extends"in l?l.extends:"entity"},
56
56
  `,d&&d.length>0)for(let p of d)p.contentType!=="REF"&&(p.inherited||(p.isIdField?r+=` owns ${p.dbPath} @key,
57
57
  `:r+=` owns ${p.dbPath},
@@ -67,7 +67,7 @@ ${a}`}).join(`
67
67
  `),r+=`
68
68
  `;}let i=`define
69
69
 
70
- `,o=Zo(n);for(let a of o)if(a.contentType==="TEXT"||a.contentType==="ID"||a.contentType==="JSON")i+=`${a.dbPath} sub attribute, value string;
70
+ `,o=Xo(n);for(let a of o)if(a.contentType==="TEXT"||a.contentType==="ID"||a.contentType==="JSON")i+=`${a.dbPath} sub attribute, value string;
71
71
  `;else if(a.contentType==="EMAIL")i+=`${a.dbPath} sub attribute, value string,
72
72
  `,i+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';
73
73
  `;else if(a.contentType==="DATE")i+=`${a.dbPath} sub attribute, value datetime;
@@ -90,57 +90,57 @@ flexAttribute sub attribute, abstract, value string,
90
90
  owns doubleAttribute,
91
91
  owns booleanAttribute,
92
92
  owns datetimeAttribute;
93
- `},Kr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let i=Go(e,r),o=n.typeDB.get(e)?.session,s=n.typeDB.get(e)?.client;if(!o){console.log("Session Status: ","NO SESSION");return}if(!s)throw new Error("No TypeDB client found");await o.close();let[{dbName:a}]=t.dbConnectors;await(await s.databases.get(a)).delete(),await s.databases.create(a);let c=await(await s.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(i),await c.commit(),await c.close(),i};var Yr=async(e,t,r)=>await(async()=>{let o=(await Promise.all([...r.typeDB||[]].map(async([l])=>[l,await Kr(l,e,t,r)]))).map(l=>[l[0],l[1]]),a=(await Promise.all([...r.surrealDB||[]].map(async([l])=>[l,Jr(t)]))).map(l=>[l[0],l[1]]);return {typeDB:Object.fromEntries(o),surrealDB:Object.fromEntries(a)}})();var Xr={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var oe=Symbol.for("queryPath"),bt=Symbol.for("stepPrint"),We=Symbol.for("edgeType"),Oe=Symbol.for("edgeSchema");var et=Symbol.for("dbNode"),Kt=Symbol.for("isTransformed"),Tt=Symbol.for("parent"),ue=Symbol.for("fieldSchema"),J=Symbol.for("sharedMetadata"),Ne=Symbol.for("suqlMetadata");var tn=(e,t)=>{let r=Zr(e.entities),n=Zr(e.relations),i=ts(e),o={entities:{},relations:{}};return r.forEach(s=>{let a=e.entities[s];if(!a)throw new Error(`Entity "${s}" does not exist`);let l="extends"in a?o.entities[a.extends]:void 0;l&&Xt(o,l.name,s);let d=Gr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i});o.entities[s]={...d,defaultDBConnector:a.defaultDBConnector,thingType:"entity"};}),n.forEach(s=>{let a=e.relations[s];if(!a)throw new Error(`Relation "${s}" does not exist`);let l="extends"in a?o.relations[a.extends]:void 0;l&&Xt(o,l.name,s);let d=Gr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i}),c={...d,defaultDBConnector:a.defaultDBConnector,roles:Object.fromEntries(Object.entries(a.roles??{}).map(([u,p])=>[u,en({role:p,roleName:u,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i})])),thingType:"relation"};"extends"in a&&l&&Object.entries(l?.roles??{}).forEach(([u,p])=>{let f=en({role:p,roleName:u,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i});c.roles[u]={...f,inherited:true,[J]:{...p[J],inheritanceOrigin:p[J]?.inheritanceOrigin||a.extends}};}),o.relations[s]=c;}),Object.values(o.entities).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Yt(o,a.$things);});}),Object.values(o.relations).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Yt(o,a.$things);}),Object.values(s.roles??{}).forEach(a=>{a.$things=Yt(o,a.$things);});}),o},Zr=e=>{let t=[],r=new Set,n=new Set;for(let i of Object.keys(e))rn({thingMap:e,name:i,inProcess:n,seen:r,ordered:t});return t},rn=e=>{let{thingMap:t,name:r,inProcess:n,seen:i,ordered:o}=e;if(i.has(r))return;if(n.has(r))throw new Error(`A list of thing extends each other that creates circular dependencies: ${[...n]}`);n.add(r);let s=t[r];if(!s)throw new Error(`Entity/relation "${r}" does not exist`);"extends"in s&&rn({...e,name:s.extends}),n.delete(r),i.add(r),o.push(r);},es=(e,t)=>{let r=t,n=[];for(;r;){let i=e.entities[r]||e.relations[r];if(!i)throw new Error(`Entity/relation "${r}" does not exist`);n.push(r),r="extends"in i?i.extends:void 0;}return n.length!==0?n:void 0},Xt=(e,t,r)=>{let n=e.entities[t]??e.relations[t];if(!n)throw new Error(`Entity/relation "${t}" does not exist`);n.subTypes=n.subTypes??[],n.subTypes.push(r),n.extends&&Xt(e,n.extends,r);},Gr=e=>{let{schema:t,enrichedSchema:r,name:n,thing:i,dbHandles:o,extendedThing:s,allLinkFields:a}=e,[l]=Object.entries(o).find(([h,$])=>$.get(i.defaultDBConnector.id))??[];if(!l)throw new Error(`DB handle for ${i.defaultDBConnector.id} does not exist`);let d=[...i.idFields??s?.idFields??[]];if(d.length===0)throw new Error(`"${n}" does not have an id field`);let c={...i.hooks},u=i.dataFields?.map(h=>rs(h,n,d))??[],p=i.linkFields?.map(h=>is({linkField:h,thingName:n,thing:i,schema:t,allLinkFields:a}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([h,$])=>[h,ns($,h)]));return "extends"in i&&s&&(s.hooks?.pre&&(c.pre=[...s.hooks.pre||[],...i.hooks?.pre||[]]),s.dataFields?.forEach(h=>{u.push({...h,inherited:true,[J]:{...h[J],inheritanceOrigin:h[J]?.inheritanceOrigin||i.extends}});}),s.linkFields?.forEach(h=>{p.push({...h,inherited:true,[J]:{...h[J],inheritanceOrigin:h[J]?.inheritanceOrigin||i.extends}});}),Object.entries(s.refFields??{}).forEach(([h,$])=>{f[h]={...$,inherited:true,[J]:{...$[J],inheritanceOrigin:$[J]?.inheritanceOrigin||i.extends}};})),{...i,name:n,db:l,dbContext:Xr[l],idFields:d,hooks:c,dataFields:u,linkFields:p,refFields:f,enumFields:u?.filter(h=>h.validations?.enum).map(h=>h.path)??[],fnValidatedFields:u?.filter(h=>h.validations?.fn).map(h=>h.path)??[],virtualFields:u?.filter(h=>h.isVirtual).map(h=>h.path)??[],computedFields:u?.filter(h=>h.default&&!h.isVirtual).map(h=>h.path)??[],requiredFields:u?.filter(h=>h.validations?.required).map(h=>h.path)??[],allExtends:"extends"in i?es(r,i.extends):void 0,dbProviderConfig:l==="surrealDB"?o[l]?.get(i.defaultDBConnector.id)?.providerConfig:void 0}},ts=e=>{let t=[];return Object.entries(e.entities).forEach(([r,n])=>{n.linkFields?.forEach(i=>{t.push({...i,thing:r,thingType:"entity",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),Object.entries(e.relations).forEach(([r,n])=>{n.linkFields?.forEach(i=>{t.push({...i,thing:r,thingType:"relation",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),t},rs=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:os(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:false,[J]:{fieldType:"dataField"},[Ne]:{dbPath:e.path}}),ns=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[J]:{fieldType:"refField"}}),is=e=>{let{linkField:t,thing:r,thingName:n,schema:i,allLinkFields:o}=e,s=i.relations[t.relation];if(!t.isVirtual){if(!s)throw new Error(`The relation ${t.relation} does not exist in the schema`);if(!nn(i,t.relation,t.plays))throw new Error(`The role ${t.plays} is not defined in the relation ${t.relation} (linkField: ${t.path})`)}let a=t.cardinality==="MANY"?`$parent.[\`${t.path}\`]`:`$parent.\`${t.path}\``;if(t.target==="relation"){if(t.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${n}" LinkField: "${t.path}."`);return {...t,$things:[t.relation],oppositeLinkFieldsPlayedBy:[{plays:t.path,thing:t.relation,thingType:"relation"}],fieldType:"linkField",inherited:false,[J]:{fieldType:"linkField"},[Ne]:{queryPath:a}}}let l=o.filter(d=>d.relation===t.relation&&d.plays!==t.plays&&d.target==="role");if(l.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${n}" LinkField: "${t.path}."`);return l.length>1&&console.warn(`[Schema] LinkField ${t.path} in ${n} has multiple candidates ${l.map(d=>d.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`),{...t,fieldType:"linkField",pathToRelation:r.linkFields?.find(d=>d.target==="relation"&&d.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:false,$things:l.map(d=>d.thing),oppositeLinkFieldsPlayedBy:l,[J]:{fieldType:"linkField"},[Ne]:{queryPath:a}}},en=e=>{let{role:t,roleName:r,relationName:n,relation:i,allExtends:o,allLinkFields:s}=e;if(i.dataFields?.find(d=>d.path===r)||i.linkFields?.find(d=>d.path===r))throw new Error(`[Schema] The path ${r} is already in use by a dataField or linkField in ${n}.`);let a=s.filter(d=>d.relation===n&&d.plays===r),l=s.filter(d=>d.target==="relation"&&d.plays===r&&o?.includes(d.relation));return {...t,fieldType:"roleField",inherited:false,playedBy:a.map(d=>({...d,pathToRelation:d.target==="relation"?d.path:i.linkFields?.find(c=>c.target==="relation"&&c.relation===r&&c.plays===r)?.path??d.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:r,$things:[...new Set(a.map(d=>d.thing))],[J]:{fieldType:"roleField"},[Ne]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${r}\`]`:`$parent.\`${r}\``}}},os=(e,t,r)=>r?t:`${e}\xB7${t}`,nn=(e,t,r)=>{let n=e.relations[t];if(!n)throw new Error(`Relation "${t}" does not exist`);return n.roles?.[r]?true:"extends"in n?nn(e,n.extends,r):false},Yt=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var sn=e=>{let t=$s(e),r={},n=ps(t);for(let i in t.entities)Zt("entity",i,r,t,n);for(let i in t.relations)Zt("relation",i,r,t,n);return r},Zt=(e,t,r,n,i)=>{let o=r[t];if(o){if(o.type===e)return o;throw new Error(`Found entity and relation with the same name: ${t}`)}let s=e==="entity"?n.entities[t]:n.relations[t];if(!s)throw new Error(`${e==="entity"?"Entity":"Relation"} "${t}" not found`);let a="extends"in s&&s.extends?Zt(e,s.extends,r,n,i):void 0;a&&as(a.name,t,r);let l={},d=a?a.idFields:fs(t,s);if(ls(l,s.dataFields??[],t),cs(l,s.refFields??{},t),ds(l,s.linkFields??[],t,n,i),e==="entity"){let u={type:"entity",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=u,u}"roles"in s&&s.roles&&us(l,s.roles??{},t,i);let c={type:"relation",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=c,c},as=(e,t,r)=>{let n=e;for(;n;){let i=r[n];if(!i)throw new Error(`Thing "${n}" not found`);i.subTypes.push(t),n=i.extends;}},ls=(e,t,r)=>{for(let n of t??[]){let i=e[n.path];if(n.isVirtual){if(n.default?.type==="fn"&&typeof n.default.fn=="function"){let s={type:"computed",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",fn:n.default.fn};ve(r,s,i),e[n.path]=s;continue}if(n.default?.type==="value"){let s={type:"constant",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",value:n.default.value};ve(r,s,i),e[n.path]=s;continue}}let o={type:"data",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",unique:n.validations?.unique??false};ve(r,o,i),e[n.path]=o;}},cs=(e,t,r)=>{for(let[n,i]of Object.entries(t??{})){let o=e[n],s={type:"ref",name:n,contentType:i.contentType,cardinality:i.cardinality??"ONE"};ve(r,s,o),e[n]=s;}},ds=(e,t,r,n,i)=>{for(let o of t??[]){let s=n.relations[o.relation];if(!s)throw new Error(`Relation ${o.relation} not found`);let a=s.roles?.[o.plays];if(!a)throw new Error(`Role ${o.plays} not found in relation ${o.relation}`);let l=e[o.path];if(o.target==="relation"){let p={type:"link",name:o.path,cardinality:o.cardinality,target:"relation",opposite:{thing:o.relation,path:o.plays,cardinality:a.cardinality}};ve(r,p,l),e[o.path]=p;continue}let d=i[o.relation]?.[o.targetRole];if(!d)throw new Error(`Role ${o.targetRole} in relation ${o.relation} does not exist`);let c=d.targetingRole;if(!c)throw new Error(`Role "${o.targetRole}" in relation "${o.relation}" is not played by any other thing that targets role "${o.plays}"`);let u={type:"link",name:o.path,cardinality:o.cardinality,target:"role",opposite:c};ve(r,u,l),e[o.path]=u;}},us=(e,t,r,n)=>{for(let[i,o]of Object.entries(t)){let s=n[r]?.[i]?.targetingRelation??n[r]?.[i]?.targetingRole;if(!s)throw new Error(`Role ${i} in relation ${r} is not played by any other thing`);let a=e[i],l={type:"role",name:i,cardinality:o.cardinality??"ONE",opposite:s};ve(r,l,a),e[i]=l;}},ve=(e,t,r)=>{if(r&&!isEqual(t,r))throw new Error(`Duplicate field name "${t.name}" in "${e}"`)},ps=e=>{let t={};for(let[r,n]of [...Object.entries(e.relations),...Object.entries(e.entities)])for(let i of n.linkFields??[]){let o=t[i.relation]??{};t[i.relation]=o;let s=o[i.plays]??{};o[i.plays]=s;let a=i.target==="relation"?s.targetingRelation:s.targetingRole;if(a){if(a.thing===r||on(r,a.thing,e))continue;if(!on(a.thing,r,e))throw new Error(`Found multiple players for role ${i.plays} in relation ${i.relation}`)}i.target==="relation"?s.targetingRelation={thing:r,path:i.path,cardinality:i.cardinality}:s.targetingRole={thing:r,path:i.path,cardinality:i.cardinality};}return t},on=(e,t,r)=>hs(e,r).includes(t),hs=(e,t)=>{let r=[],n=e;for(;n;){let i=t.entities[n]??t.relations[n];if(!i)throw new Error(`Thing "${n}" not found`);if(!("extends"in i)||!i.extends)break;r.push(i.extends),n=i.extends;}return r.reverse()},fs=(e,t)=>{if(t.idFields&&t.idFields.length>0)return [t.idFields[0],...t.idFields.slice(1)];let r=t.dataFields?.find(n=>n.contentType==="ID");if(r)return [r.path];throw new Error(`No id field found for entity "${e}"`)},$s=e=>{let t={entities:{},relations:{}};for(let r in e.entities)an(r,e,t);for(let r in e.relations)ln(r,e,t);return t},an=(e,t,r)=>{let n=t.entities[e];if(!n)throw new Error(`Entity "${e}" not found`);if("extends"in n&&n.extends){let i=an(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:cn(i,n),linkFields:dn(i,n),refFields:un(i,n)};return r.entities[e]=o,o}return r.entities[e]=n,n},ln=(e,t,r)=>{let n=t.relations[e];if(!n)throw new Error(`Relation "${e}" not found`);if("extends"in n&&n.extends){let i=ln(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:cn(i,n),linkFields:dn(i,n),refFields:un(i,n),roles:ms(i,n)};return r.relations[e]=o,o}return r.relations[e]=n,n},cn=(e,t)=>{let r=new Set(t.dataFields?.map(i=>i.path)??[]);return [...e.dataFields?.filter(i=>!r.has(i.path))??[],...t.dataFields??[]]},dn=(e,t)=>{let r=new Set(t.linkFields?.map(i=>i.path)??[]);return [...e.linkFields?.filter(i=>!r.has(i.path))??[],...t.linkFields??[]]},un=(e,t)=>({...Object.fromEntries(Object.entries(e.refFields??{}).filter(([n])=>!t.refFields?.[n])),...t.refFields??{}}),ms=(e,t)=>({...Object.fromEntries(Object.entries(e.roles??{}).filter(([n])=>!t.roles?.[n])),...t.roles??{}});var tr={};Oo(tr,{action:()=>Bs,createMachine:()=>Qs,d:()=>He,guard:()=>Fs,immediate:()=>Ts,interpret:()=>wn,invoke:()=>Ms,reduce:()=>gn,state:()=>Rs,transition:()=>bs});function pe(e){return {enumerable:true,value:e}}function pn(e){return {enumerable:true,writable:true,value:e}}var He={},ys=()=>true,hn=()=>({}),$n=e=>e,gs=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),Es=(e,t,r,[n,i])=>t.call(r,e.call(r,n,i),i),qe=(e,t)=>Object.freeze(Object.create(e,t));function fn(e,t,r){return e.reduce((n,i)=>function(...o){return r(n,i,this,o)},t)}function mn(e){return qe(this,{fn:pe(e)})}var yn={},gn=mn.bind(yn),Bs=e=>gn((t,r)=>!!~e(t,r)&&t),En={},Fs=mn.bind(En);function St(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Bn(e,t,...r){let n=fn(St(En,r).map(o=>o.fn),ys,gs),i=fn(St(yn,r).map(o=>o.fn),$n,Es);return qe(this,{from:pe(e),to:pe(t),guards:pe(n),reducers:pe(i)})}var Fn={},bn={},bs=Bn.bind(Fn),Ts=Bn.bind(bn,null);function Ss(e,t,r){return er(t,e,r,this.immediates)||e}function Tn(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 ws={enter:$n};function Rs(...e){let t=St(Fn,e),r=St(bn,e),n={final:pe(e.length===0),transitions:pe(Tn(t))};return r.length&&(n.immediates=pe(r),n.enter=pe(Ss)),qe(ws,n)}var Ls={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Gt.isPrototypeOf(n)?qe(Sn,{machine:pe(n),transitions:pe(this.transitions)}).enter(e,t,r):(n.then(i=>{if(e===t.machine)return t.send({type:"done",data:i})}).catch(i=>{if(e===t.machine)return t.send({type:"error",error:i})}),e)}},Sn={enter(e,t,r){if(t.child=wn(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,er(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function Ms(e,...t){let r=pe(Tn(t));return Gt.isPrototypeOf(e)?qe(Sn,{machine:pe(e),transitions:r}):qe(Ls,{fn:pe(e),transitions:r})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function Qs(e,t,r=hn){return typeof e!="string"&&(r=t||hn,t=e,e=Object.keys(t)[0]),He._create&&He._create(e,t),qe(Gt,{context:pe(r),current:pe(e),states:pe(t)})}function er(e,t,r,n){let{context:i}=e;for(let{to:o,guards:s,reducers:a}of n)if(s(i,r)){e.context=a.call(e,i,r);let l=t.original||t,d=qe(l,{current:pe(o),original:{value:l}});He._onEnter&&He._onEnter(t,o,e.context,i,r);let c=d.state.value;e.machine=d;let u=c.enter(d,e,r);return e.onChange(e),u}}function Ds(e,t){let r=t.type||t,{machine:n}=e,{value:i,name:o}=n.state;return i.transitions.has(r)?er(e,n,t,i.transitions.get(r))||n:(He._send&&He._send(r,o),n)}var As={send(e){Ds(this,e);}};function wn(e,t,r,n){let i=Object.create(As,{machine:pn(e),context:pn(e.context(r,n)),onChange:pe(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,n),i}var{createMachine:we,guard:rr,interpret:Re,invoke:U,reduce:q,state:me,transition:x}=tr;var G="0.15.2";var Mn=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ye=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,i])=>{let[o,s]=tryit(()=>t(n,i))();return o?false:s}))},ee=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},z=(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)}`)},wt=(e,t)=>{let r=e.dataFields?.find(o=>o.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(o=>o.path===t);if(n)return ["linkField",n];let i="roles"in e?e.roles[t]:void 0;if(i)return ["roleField",i];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Rt=(e,t)=>{let r=z(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},Qn=(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")},ir=(e,t,r)=>{let n=z(e,t),i=n.linkFields?.find(l=>l.path===r);if(i)return i;let o=n.dataFields?.find(l=>l.path===r);if(o)return o;let s="roles"in n?n.roles?.[r]:void 0;if(s)return s;let a="refFields"in n?n.refFields?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},or=(e,t,r)=>ir(e,t,r)?.cardinality,ge=(e,t)=>{let r=e.dataFields?.map($=>$.path)||[],n=e.linkFields?.map($=>$.path)||[],i="refFields"in e?listify(e.refFields,$=>$):[],o="roles"in e?listify(e.roles,$=>$):[],s=[...r||[],...n||[],...o||[],...i||[]],l=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...s];if(!t)return {fields:s,dataFields:r,roleFields:o,linkFields:n};let d=t.$fields?t.$fields.map($=>{if(typeof $=="string"){if($.startsWith("$")||$.startsWith("%"))return;if(!s.includes($))throw new Error(`Field ${$} not found in the schema`);return $}if("$path"in $&&typeof $.$path=="string")return $.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,$=>{if(!($.startsWith("$")||$.startsWith("%"))){if(!s.includes($))throw new Error(`[Schema] Field ${$} not found in the schema`);return $}}).filter($=>$!==void 0),c=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&r?.includes($)):[],u=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&[...o||[],...n||[]].includes($)):[],p=[...d,...c].filter($=>!$?.startsWith("%")).filter($=>!l.includes($)).filter($=>$),f=t.$filter?ye(t.$filter,($,E)=>c.includes($)):{},h=t.$filter?ye(t.$filter,($,E)=>u.includes($)):{};return {fields:s,dataFields:r,roleFields:o,linkFields:n,refFields:i,usedFields:d,usedLinkFields:n.filter($=>d.includes($)),usedRoleFields:o.filter($=>d.includes($)),usedDataFields:r.filter($=>d.includes($)),usedRefFields:i.filter($=>d.includes($)),unidentifiedFields:p,...c.length?{localFilters:f}:{},...u.length?{nestedFilters:h}:{}}};var Dn=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},An=(e,t,r)=>{let i=(r.nodePath||"").split("."),o=isArray(t)?i.slice(0,-2).join("."):i.slice(0,-1).join(".");return t?getNodeByPath(e,o):{}},xe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Lt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Ie=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};for(let[n,i]of Object.entries(t))r[n]=isDraft(i)?current(i):i;return r}return e},Ee=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},L=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},je=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)(),sr=(e=5)=>customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e)(),On=e=>{let t=({value:r})=>{if(r&&typeof r=="object"&&"$id"in r){let n=Object.keys(r).filter(i=>i.startsWith("$"));for(let i of n)delete r[i];}return r};return produce(e,r=>traverse(r,t))};var rt=(e,t)=>{for(let i of e)if(!("$entity"in i)&&!("$relation"in i)&&(!("$thing"in i)||!("$thingType"in i)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,i=>traverse(i,o=>{let{value:s,meta:a}=o,l=s;if(isObject(l)){if(a.nodePath?.includes(".$filter")||a.nodePath?.includes(".$playedBy"))return;if(l[oe]=a.nodePath,l.$id){let d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=z(t,d);if(!c?.name)throw new Error(`Schema not found for ${l.$thing}`);if(l.$path=c.name,Array.isArray(l.$id)||(l.$filterByUnique=true),c.idFields.length===1){let[u]=c.idFields;l.$filter={...l.$filter,[u]:l.$id},l.$id=void 0;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in l||"$relation"in l||"$thing"in l){let d=z(t,l);if(!d?.name)throw new Error(`Schema not found for ${l.$thing}`);l.$path=d.name;}if(l.$entity?(l.$thing=l.$entity,l.$thingType="entity",l.$entity=void 0):l.$relation&&(l.$thing=l.$relation,l.$thingType="relation",l.$relation=void 0),isObject(l)&&"$thing"in l&&l.$thing){let d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=z(t,d);if(l.$filter&&(Object.keys(l.$filter).length===0?l.$filter=void 0:(l.$filter=_e(l.$filter,l.$thing,t),l.$filterByUnique=lr(l.$filter,c))),l.$fields){l.$fields.some(f=>c?.idFields?.includes(f?.$path||f))||(l.$fields=[...l.$fields,...Array.isArray(c.idFields)?c.idFields:[]],l.$idNotIncluded=true);let p=l.$fields?.flatMap(f=>{let h=Nn(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}else {let p=ar(c)?.flatMap(f=>{let h=Nn(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>Mt(c,u)?true:!l.$excludedFields.includes(u.$path)));}}}))},ar=e=>{let t=e.dataFields?.map(s=>s.path)||[],r=e.linkFields?.map(s=>s.path)||[],n=Object.keys(e.roles||{})||[],i=Object.keys(e.refFields||{})||[];return [...t,...r,...n,...i]},lr=(e,t)=>Object.keys(e||{}).some(n=>{let i=e[n];if(i!==null&&typeof i<"u"){let o=t.idFields?.includes(n),s=t.dataFields?.some(d=>(d.dbPath===n||d.path===n)&&d?.validations?.unique),a=n==="$id"&&!Array.isArray(i);if(o||s||a){if(typeof i!="object"||i===null||Array.isArray(i))return !Array.isArray(i);let d=Object.keys(i);if(d.length===1&&d[0]==="$eq"){let c=i.$eq;if(typeof c!="object"||c===null||!Array.isArray(c))return true}return false}}return false}),Mt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),js=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:i,isVirtual:o,fieldSchema:s}=e;return {$path:r,$dbPath:i,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:o,[ue]:s}},_s=e=>{let{field:t,fieldStr:r,linkField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e,{target:l,oppositeLinkFieldsPlayedBy:d}=n;return d.map(c=>{let u=l==="role"?c.thingType:"relation",p=l==="role"?c.thing:n.relation,f={[`$${u}`]:p},h=z(s,f),$=t?.$fields?.filter(y=>Mt(h,y)).length===0,E=[];if(typeof t!="string")if(t.$fields)if($){let y=h.idFields||[];E=[...t.$fields,...y];}else E=t.$fields;else E=ar(h);else E=["id"];t.$excludedFields&&(E=E.filter(y=>Mt(h,y)?true:!t.$excludedFields.includes(y.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$plays:n.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:o,$as:t.$as||r,$var:r,$thing:p,$fields:E,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:lr(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ue]:a}})},zs=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:i,fieldSchema:o}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:r,$dbPath:i,$contentType:o.contentType,$as:t.$as||r,$var:r,$fieldType:"ref",$justId:n,$fields:t.$fields,$id:t.$id,[ue]:o}},Vs=e=>{let{field:t,fieldStr:r,roleField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e;return n.playedBy.map(l=>{let{thing:d,thingType:c,relation:u}=l,p={[`$${c}`]:d},f=z(s,p),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 $=ar(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>Mt(f,m)?true:!t.$excludedFields.includes(m.$path)));let E=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:r,$dbPath:o,$as:t.$as||r,$var:r,$thing:d,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:i,$id:t.$id,$filter:E,$idNotIncluded:h,$filterByUnique:lr(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ue]:a}})},Nn=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,i=typeof e=="string",o=t.dataFields?.find(d=>d.path===n),s=t.linkFields?.find(d=>d.path===n),a=t.roles?.[n],l=t.refFields?.[n];if(o){let d=!!o.isVirtual&&!!o.default;return js({field:e,fieldStr:n,$justId:i,dbPath:o.dbPath,isVirtual:d,fieldSchema:o})}return s?_s({field:e,fieldStr:n,linkField:s,$justId:i,dbPath:s.path,schema:r,fieldSchema:s}):a?Vs({field:e,fieldStr:n,roleField:a,$justId:i,dbPath:n,schema:r,fieldSchema:a}):l?zs({field:e,fieldStr:n,$justId:i,dbPath:n,isVirtual:false,fieldSchema:l}):null},_e=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(s=>Object.keys(s).reduce((d,c)=>{let u=s[c],p=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))d[c]=u;else if(["$not","$or","$and"].includes(c))d[c]=_e(u,t,r);else if(["$eq","$in","$exists"].includes(c))d[c]=u;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[h,$]=wt(f,c);if(h==="idField")d[c]=u;else if(h==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?d[c]=isArray(u)?{$or:_e(u,t,r)}:_e(u,t,r):isArray(u)?d[c]={$in:u}:d[c]={$eq:u};else if(h==="linkField"||h==="roleField"){let E=$,[m]=E.$things;p.every(y=>typeof y=="string")?d[c]={$id:p,$thing:m}:p.every(y=>isObject(y))&&(d[c]=isArray(u)?{$or:_e(u,m,r)}:_e(u,m,r));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return d},{}));return !n||o.length===1?o[0]:{$or:o}};var Ws=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,vs=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,In=e=>{let r=e.toString().replace(Ws,"").trim().split("=>")[0].split("{")[0].replace(vs,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(o=>o.includes("{")&&o.includes("}")?(o.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(a=>a.split(":")[0].trim().replace(/['"[\]]/g,"")):o.trim()).filter(Boolean):[]};var nt=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=false})=>{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,o=In(n).filter(s=>!(s in e));if(o.length)throw new Error(`Virtual field: Missing arguments ${o.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 kn=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(i=>{if(i.$op!=="create")return;let o=z(r,i),{unidentifiedFields:s}=ge(o,i),{computedFields:a,virtualFields:l}=o,d=listify(i,(p,f)=>f!==void 0?p:void 0),c=d.filter(p=>l?.includes(p));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(a.filter(p=>!d.includes(p)).forEach(p=>{let f=o.dataFields?.find(y=>y.path===p),$=o.linkFields?.find(y=>y.path===p)?.oppositeLinkFieldsPlayedBy[0],E="roles"in o?Mn(o.roles,(y,B)=>y===p):void 0,m=f||$||E;if(!m)throw new Error(`no field Def for ${p}`);if(!i[p]){let y=nt({currentThing:i,fieldSchema:m,mandatoryDependencies:true});i[p]=y;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(i)}`)}),e};var cr=(e,t)=>e.$bzId?e.$bzId:e.$tempId?e.$tempId:e.$id&&!isArray(e.$id)?t?`SN_ONE_${t}_${e.$id}`:`SN_ONE_${e.$id}`:e.$id&&isArray(e.$id)?t?`SN_MANY_${t}_${je()}`:`SN_MANY_${je()}`:`SM_${je()}`;var ze=(e,t,r)=>{if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);let n=z(r,t),{usedDataFields:i}=ge(n,t);if(t.$op==="delete"&&i.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&i.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}},Pn=(e,t,r)=>{(isArray(t)?t:[t]).forEach(i=>{ze(e,i,r);});};var qn=e=>{let t=Object.keys(e).filter(r=>!(r.startsWith("$")||r.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},xn=(e,t,r)=>{let n=z(r,t),{usedFields:i}=ge(n,t);return t.$op?(ze(e,t,r),t.$op):t.$id||t.$filter?i.length>0?(ze(e,{...t,$op:"update"},r),"update"):(ze(e,{...t,$op:"link"},r),"link"):t.$tempId?i.length>0?(ze(e,{...t,$op:"create"},r),"create"):(ze(e,{...t,$op:"create"},r),"link"):(ze(e,{...t,$op:"create"},r),"create")};var Qt=(e,t)=>{if(t[J].fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}if(t[J].fieldType==="roleField"){let r=t;if([...new Set(r.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r.playedBy}throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var jn=(e,t,r,n)=>{let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);let s=qn(o),a=cr(o);if(r[J].fieldType==="refField"){let c=r;if(!isObject(o)){if(c.contentType==="FLEX")return o;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!o.$thing)throw new Error("[Wrong format] The field $thing is required in refFields");return {...o,$op:s,$bzId:a}}let l=r;if(l.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let d=r;if(d.$things.length===1){let c=Qt(t,l),[u]=c;if(o.$thing&&o.$thing!==u.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${u.thing}.`);return {...o,[Oe]:d,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:s,$bzId:a}}if(o.$thing)return [{...o,[Oe]:d,$thing:o.$thing,$thingType:o.$thing in n.entities?"entity":"relation",$op:s,$bzId:a}];if(o.$tempId)throw new Error("[Unsupported] Objects with $tempId and multiple potential players require to explicitly indicate the $thing type.");if(s==="create")throw new Error(`[Wrong format] The field ${t} can be played by multiple things, please specify one on creation.`);return d.$things.map(c=>({...o,[Oe]:d,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:s,$bzId:cr(o,c)}))});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var Dt=(e,t)=>{let r=z(t,e).hooks;if(r?.pre){let n=`on${Dn(e.$op)}`;return r.pre.filter(s=>!s.triggers||s.triggers[n]?.()).flatMap(s=>s.actions)}return []};var _n=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!Lt(o)||o.$fields||o[Kt])return;let s=Dt(o,r).filter(u=>u.type==="transform"),a=clone(Ie(e)),l=clone(Ie(o)),d=n.mutation?.context||{},c=clone(Ie(o[et]||o.$dbNode));s.forEach(u=>{let p=u.fn(l,a,d,c||{});Object.keys(p).length!==0&&(l={...l,...p,...xe(o),[Kt]:true},Object.assign(o,l));});});};var Vn=(e,t,r,n)=>{let i=isArray(e[t])?e[t]:[e[t]];for(let o of i)if("$thing"in o){if(o.$fields)continue;let{requiredFields:s,enumFields:a,fnValidatedFields:l,dataFields:d}=z(r,o);if("$op"in o&&o.$op==="create"){for(let c of s)if(!(c in o))throw new Error(`[Validations] Required field "${c}" is missing.`)}if("$op"in o&&o.$op==="update"||o.$op==="create"){for(let c of a)if(c in o){let u=d?.find(p=>p.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(o[c])){for(let p of o[c])if(p!==null&&!u.includes(p))throw new Error(`[Validations] Option "${p}" is not a valid option for field "${c}".`)}else if(u&&!u.includes(o[c])&&o[c]!==null)throw new Error(`[Validations] Option "${o[c]}" is not a valid option for field "${c}".`)}}if("$op"in o&&o.$op==="update"||o.$op==="create"){for(let c of l)if(c in o)try{let u=d?.find(p=>p.path===c)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(o[c]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${c}] ${u.message}`)}}if(isObject(o)&&"$thing"in o){let c=o.$thing,u=o,p=clone(Ie(e)),f=clone(Ie(u)),h=n.mutation?.context||{},$=clone(Ie(o[et]||{})),E=Dt(u,r);for(let m of E)if(m.type==="validate"){if(m.severity!=="error")continue;try{let y=m.fn(f,p,h,$);if(y===!1)throw new Error(`${m.message}.`);if(y!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(y){throw new Error(`[Validations:thing:${c}] ${y.message}`)}}}}};var Un=(e,t,r,n)=>{let i=isArray(e[t])?e[t]:[e[t]],o=n.slice(1).join(".");i.forEach(s=>{if(s){if(r?.cardinality==="ONE"&&!s.$op&&!s.$id&&!s.$filter&&!s.$tempId&&e.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${o}.${t}`);if(s.$tempId&&!(s.$op===void 0||s.$op==="link"||s.$op==="create"||s.$op==="update"||s.$op==="replace"))throw new Error(`Invalid op ${s.$op} for tempId. TempIds can be created, or linked when created in another part of the same mutation.`)}});};var vn=e=>{if(typeof e!="string")return {isPrefixed:false,obj:e};let t=e.match(/^([^:]+):([^:]+)$/),r=e.match(/^([^:]+):_:([^:]+)$/);if(t&&!e.includes(" ")){let[,n,i]=t;return {isPrefixed:true,obj:{$thing:n,$id:i}}}if(r&&!e.includes(" ")){let[,n,i]=r;return {isPrefixed:true,obj:{$thing:n,$tempId:`_:${i}`}}}return {isPrefixed:false,obj:e}},Hn=(e,t)=>{let r=isArray(e[t])?e[t]:[e[t]];if(r.every(i=>typeof i=="object"))return;if(!r.every(i=>typeof i=="string"||isObject(i)&&"$op"in i&&i.$op==="replace"))throw new Error(`[Mutation Error] Replace can only be used with a single id, an array of ids, or objects with $op: replace. (Field: ${t} Nodes: ${JSON.stringify(r)})`);let n=e.$op==="create"?"link":"replace";e[t]=r.map(i=>{if(typeof i=="string"){if(i.startsWith("_:"))return {$tempId:i,$op:n};let{isPrefixed:o,obj:s}=vn(i);return o?{...s,$op:n}:{$id:i,$op:n}}return i});},Jn=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]],i=e.$op==="create"?"link":"replace";return e[t]=n.map(o=>{if(typeof o=="string"){if(o.startsWith("_:"))return {$tempId:o,$op:i};let{isPrefixed:s,obj:a}=vn(o);if(s)return {...a,$op:i};if(r.contentType==="FLEX")return o;throw new Error("[Wrong format] Field of contentType REF can't use strings as references unless they follow the format `$thing:$id`")}if(typeof o=="object"&&"$thing"in o||r.contentType==="FLEX")return o;throw new Error("[Wrong format] Field of contentType REF can use prefixed id strings, tempIds or objects indicating their $thing")}),e[t]};var Yn=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=xn(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:Qn(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${je()}`}},...i}});e.$root=isArray(e.$root)?n:n[0];};var At=(e,t)=>{let r=t[bt];return isSet(r)?r.has("clean")?(Reflect.set(t,bt,r.add("clean")),true):false:(Reflect.set(t,bt,new Set(["clean"])),true)};var Xn=(e,t,r)=>{if(At("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(isObject(i)&&"$id"in i&&isArray(i.$id)){let o=i;if(z(r,o),!o.$bzId)throw new Error("[Internal Error] No bzId found");return o.$id.map((s,a)=>({...Ie(o),$id:s,$bzId:`${o.$bzId}_${a}`,...xe(o)}))}return i});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Zn=(e,t,r)=>{let n=Qt(t,r),[i]=n;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Oe]:r};};var it=e=>{if(Array.isArray(e)){for(let t of e)if(it(t))return true;return false}if(e.$fields)return true;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&it(e[t]))return true}return false};var ca=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(At("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);},fr=(e,t,r)=>{let n={$rootWrap:{$root:e}},i=it(Array.isArray(e)?e:[e]),o=produce(n,s=>traverse(s,({value:a,parent:l,key:d,meta:c})=>{if(!(!l||!d)&&isObject(a)){let u=c.nodePath?.split(".")||[];if(u.some(h=>h.startsWith("%")))return;if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let h=["$fields","$dbNode","$filter"],$=u.at(-1),E=u.at(-2);if(d==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($||"")&&!h.includes(E||"")&&!$?.startsWith("%")&&!E?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let p=a,f=u.includes("$filter");"$filter"in p&&p.$filter&&(p.$filter=_e(p.$filter,p.$thing,t));for(let h of Object.keys(p)){if(ca(p,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))continue;let $=h!=="$root"?ir(t,p,h):{[J]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);let{fieldType:E}=$[J],m=["linkField","roleField"].includes(E),y=E==="refField",B=E==="rootField";if(E==="dataField"){continue}if((m||y)&&(p[h]===null?m&&Zn(p,h,$):m?Hn(p,h):Jn(p,h,$)),B){if(!("$root"in p))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Yn(p,t);}if((m||y)&&Un(p,h,$,u),(m||y)&&(jn(p,h,$,t),Pn(p,p[h],t)),m||B){Xn(p,h,t),kn(p,h,t);let g=isArray(p[h])?p[h]:[p[h]];for(let T of g){let w=z(t,T),{unidentifiedFields:Q,usedLinkFields:O,usedFields:j,fields:K}=ge(w,T);for(let ce of j)if(!K.includes(ce))throw new Error(`[Schema] Field ${ce} not found in the schema`);if(Q.length>0)throw new Error(`Unknown fields: [${Q.join(",")}] in ${JSON.stringify(a)}`);if(O.length>1){let ce=w.linkFields?.filter(se=>O.includes(se.path));if(ce)for(let se=0;se<ce.length;se++){let I=ce[se];for(let D=0;D<ce.length;D++){let Y=ce[D];if(se!==D&&I.target!==Y.target&&I.relation===Y.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}}}}i||(_n(p,h,t,r),Vn(p,h,t,r));}}}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var Ot=(e,t)=>{if(!t)return;let r=pa(t);return ha(r,e.query)},pa=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),ha=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let i=n;Object.keys(i).forEach(o=>{(i[o]===void 0||i[o]===null||isArray(i[o])&&i[o].length===0)&&(t?.returnNulls?i[o]=null:delete i[o]),i[o]===void 0&&delete i[o];}),Object.getOwnPropertySymbols(i).forEach(o=>{delete i[o];}),t?.noMetadata===true&&Object.keys(i).forEach(o=>{o.startsWith("$")&&delete i[o];});}}));var Nt=async(e,t,r)=>r?(o=>produce(o,s=>traverse(s,({value:a})=>{if(isObject(a)){let l=a;if(!l.$thing)return;if(l.$thing){let d=z(e,l),{virtualFields:c}=d,u=l[oe];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let p=getNodeByPath(t,u);if(p.$fieldType==="ref")return;let f=p.$fields.map($=>$.$path),h=p.$excludedFields;c.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let E=d.dataFields?.find(m=>m.path===$);if(E?.default){let m=nt({currentThing:l,fieldSchema:E,mandatoryDependencies:true});l[$]=m;}else if(l[$]===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 l[$];});}}})))(r):void 0;var $t={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Le=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(s=>{let l=Object.keys(s).reduce((d,c)=>{let u=s[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...d,[c]:void 0,[$t[c]]:Le(u,t,r)};if(c==="$id")return {...d,$id:void 0,[$t[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return d;if(c==="$exists")return {...d,$exists:void 0,[$t[c]]:u};if(c==="$eq")return {...d,$eq:void 0,[$t[c]]:u};if(c==="$in")return {...d,$in:void 0,[$t[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let p=t in r.entities?r.entities[t]:r.relations[t],[f,h]=wt(p,c);if(f==="idField"){if(p.idFields.length>1)throw new Error("Multiple id fields not supported");return {...d,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(f==="dataField")return {...d,[c]:Le(u,t,r)};if(f==="linkField"||f==="roleField"){let E=h[Ne].queryPath;return {...d,[E]:Le(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return n?o:o[0]},be=e=>{if(e==null)return "";let t=Object.entries(e),r=[];for(let[n,i]of t){if(["$OR","$AND","$!"].includes(n)){let o=n.replace("$",""),s=Array.isArray(i)?i.map(a=>be(a)):[be(i)];o==="!"?r.push(`!(${s.join(" AND ")})`):r.push(`(${s.join(` ${o} `)})`);continue}if(isObject(i))if(n.includes("<-")||n.includes("->")){let o=be(i);r.push(`${n}[WHERE ${o}]`);}else if(n.startsWith("$parent.[")){let o=be(i),s=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${s})[WHERE id && ${o}]`);}else if(n.startsWith("$parent")){let o=be(i),s=n.replace("$parent.","");r.push(`fn::as_array(${s})[WHERE id && ${o}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let o=Object.keys(i);if(o.length===1&&o[0].startsWith("$")){let[s]=o,a=i[s];if(s==="$exists")if(a===true)r.push(`${n} IS NOT NONE`);else if(a===false)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${a}`);else {let l=s.replace("$","");if(Array.isArray(a))r.push(`${n} ${l} [${a.map(d=>d===null?"NONE":`'${d}'`).join(", ")}]`);else if(isObject(a)){let d=be(a);r.push(`${n} ${l} ${d}`);}else r.push(`${n} ${l} ${a===null?"NONE":`'${a}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(i)){let o=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${o} [${i.map(s=>s===null?"NONE":`'${s}'`).join(", ")}]`);}else {let o=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${o} ${i===null?"NONE":`'${i}'`}`);}}return r.join(" AND ")},ot=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:i}=r;return `${n}${i?" DESC":" ASC"}`}).join(", ")}`;var ii=e=>{let{queries:t,schema:r}=e;return t.map(n=>Ba({query:n,schema:r}))},Ba=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=[];d.push("SELECT");let c=mr({parentQuery:t,queries:i,level:1,schema:r});c&&d.push(c);let u=r.entities[n]||r.relations[n];if(!u)throw new Error(`Schema for ${n} not found`);let f=(u.subTypes?[n,...u.subTypes]:[n]).map(h=>le(h));if(t.$id)if(typeof t.$id=="string")d.push(`FROM ${f.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=f.flatMap(E=>h?.map(m=>`${E}:\u27E8${m}\u27E9`));d.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else d.push(`FROM ${f.join(",")}`);if(o){let h=Le(o,n,r),$=be(h);d.push(`WHERE ${$}`);}return l&&d.push(ot(l)),typeof a=="number"&&d.push(`LIMIT ${a}`),typeof s=="number"&&d.push(`START ${s}`),d.join(`
94
- `)},mr=e=>{let{queries:t,schema:r,level:n,parentQuery:i}=e,o=[],s=i[oe];return o.push(L(`"${s}" as \`$$queryPath\``,n)),o.push(L("record::id(id) as `$id`",n)),o.push(L("record::tb(id) as `$thing`",n)),t.forEach(a=>{let l=Fa({query:a,level:n,schema:r});l&&o.push(l);}),o.length===0?null:o.join(`,
95
- `)},Fa=e=>{let{query:t,schema:r,level:n}=e;if(t.$fieldType==="data")return ba({query:t,level:n});if(t.$fieldType==="ref")throw new Error("Ref fields are not supported in this context");return t.$fieldType==="link"?Ta({query:t,level:n,schema:r}):t.$fieldType==="role"?Sa({query:t,level:n,schema:r}):null},ba=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?L(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?L(`\`${t.$path}\``,r):L(`\`${t.$path}\` AS \`${t.$as}\``,r)},Ta=e=>{let{query:t,schema:r,level:n}=e,{$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=[];d.push(L("(",n));let c=n+1;d.push(L("SELECT",c));let u=mr({parentQuery:t,queries:i,level:c+1,schema:r});u&&d.push(u);let p=t[ue][Ne].queryPath;if(d.push(L(`FROM ${p}`,c)),o){let f=Le(o,t.$thing,r),h=be(f);d.push(`WHERE ${h}`);}return l&&d.push(L(ot(l),c)),typeof a=="number"&&d.push(L(`LIMIT ${a}`,c)),typeof s=="number"&&d.push(L(`START ${s}`,c)),d.push(L(`) AS \`${t.$as}\``,n)),d.join(`
96
- `)},Sa=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let i=[];i.push(L("(",n));let o=n+1;i.push(L("SELECT",o));let s=o+1,a=mr({parentQuery:t,queries:t.$fields,level:s,schema:r});a&&i.push(a);let l=t[ue][Ne].queryPath;if(i.push(L(`FROM ${l}`,o)),t.$filter){let d=Le(t.$filter,t.$playedBy.thing,r),c=be(d);i.push(`WHERE ${c}`);}return i.push(L(`) AS \`${t.$as}\``,n)),i.join(`
97
- `)};var oi=e=>{let{queries:t,schema:r}=e;return t.map(n=>Ra({query:n,schema:r}))},Ra=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let c=t[oe],u=yr(c),p=si(i.filter(T=>T.$fieldType==="data")),f=ai(i.filter(T=>T.$fieldType==="link"||T.$fieldType==="role"),r),h=li(i.filter(T=>T.$fieldType==="ref")),$=[...u,...p,...f,...h].join(`,
98
- `),E=La(t,d),m=o?`WHERE id AND (${be(Le(o,n,r))})`:"WHERE id",y=l?ot(l):"",B=typeof a=="number"?`LIMIT ${a}`:"",g=typeof s=="number"?`START ${s}`:"";return `SELECT ${$} ${E} ${m} ${y} ${B} ${g}`},La=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(s=>le(s)),i=(s,a)=>`${s}:\`${a}\``,o=s=>n.flatMap(a=>s.map(l=>i(a,l))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${o([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${o(e.$id)}`;throw new Error("Invalid $id")},yr=e=>[`"${e}" as \`$$queryPath\``,"id && record::id(id) || null as `$id`","id && record::tb(id) || null as `$thing`"],si=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}\``),ai=(e,t)=>e.map(r=>{if(!r[oe])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(r)}`);let n=yr(r[oe]),i=si(r.$fields.filter(f=>f.$fieldType==="data")),o=ai(r.$fields.filter(f=>f.$fieldType==="link"||f.$fieldType==="role"),t),s=li(r.$fields.filter(f=>f.$fieldType==="ref")),a=[...n,...i,...o,...s].filter(Boolean).join(`,
99
- `),l=`FROM $parent.\`${r[ue].path}\`[*]`,d=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${be(Le(r.$filter,r.$thing,t))})`:"WHERE id",c=r.$sort?ot(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",p=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${l} ${d} ${c} ${u} ${p} ) AS \`${r.$as}\``}).filter(r=>r),li=e=>e.map(t=>{if(!t[oe])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(t)}`);let r=yr(t[oe]);if(t.$fields?.some(s=>isObject(s)))throw new Error("[Unsupported]: Can't query nested ref fields yet");let i=[...r,"id && null || $this as `$value`",...t.$justId?"":t.$fields?.map(s=>`\u27E8${s}\u27E9`)||["*"]].join(`,
100
- `),o=`FROM $parent.\`${t[ue].dbPath}\``;return `( SELECT ${i} ${o}) AS \`${t.$as}\``});var di=e=>{let{res:t,queries:r,schema:n}=e;return t.map((o,s)=>ui(r[s],o,n))},ui=(e,t,r)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return gr(e,t[0],r)}if(t.length>=1)return t.map(n=>gr(e,n,r))}else throw new Error("res is unexpectedly not an array")},gr=(e,t,r)=>{let n=t.$thing||t.tb,i=n in r.entities?"entity":n in r.relations?"relation":"error";if(i==="error")throw new Error(`[Internal] The $thing ${n} is not defined in the schema.`);let o={[oe]:t.$$queryPath,$id:t.$id,$thing:Ur(n),$thingType:i};return e.$fields.forEach(s=>{let a=s.$as,l=t[a];s.$path==="id"&&e.$idNotIncluded||(o[a]=Da(s,l,r));}),o},Da=(e,t,r)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:n}=e[ue];return ci(t,n)??null}if(e.$fieldType==="ref"){let i=(isArray(t)?t:[t]).map(s=>{if(s.$thing){let a=ee(r,s.$thing),[l]=a.idFields;if(e.$justId)return s.$id;let d=u=>u&&typeof u=="object"&&"id"in u&&"tb"in u?u.id:u;return {...mapEntries(s,(u,p)=>isArray(p)?[u,p.map(f=>d(f))]:[u,d(p)]),[oe]:s.$$queryPath,[l]:s.$id}}return s.$value?ci(s.$value,"FLEX"):s}),{cardinality:o}=e[ue];return o==="ONE"?i[0]:i}return e.$justId?e.$filterByUnique||e[ue].cardinality==="ONE"?t[0]?.$id??null:t?.map(n=>n.$id)??[]:e.$filterByUnique||e[ue].cardinality==="ONE"?gr(e,t[0],r):ui(e,t,r)},ci=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(i=>new Date(i).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(i=>isDate(i)?new Date(i).toISOString():i);return isArray(e)?n:n[0]}return e};var pi=async e=>{let{client:t,queries:r,config:n}=e,i=`
93
+ `},Jr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let i=Zo(e,r),o=n.typeDB.get(e)?.session,s=n.typeDB.get(e)?.client;if(!o){console.log("Session Status: ","NO SESSION");return}if(!s)throw new Error("No TypeDB client found");await o.close();let[{dbName:a}]=t.dbConnectors;await(await s.databases.get(a)).delete(),await s.databases.create(a);let c=await(await s.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(i),await c.commit(),await c.close(),i};var Kr=async(e,t,r)=>await(async()=>{let o=(await Promise.all([...r.typeDB||[]].map(async([l])=>[l,await Jr(l,e,t,r)]))).map(l=>[l[0],l[1]]),a=(await Promise.all([...r.surrealDB||[]].map(async([l])=>[l,Hr(t)]))).map(l=>[l[0],l[1]]);return {typeDB:Object.fromEntries(o),surrealDB:Object.fromEntries(a)}})();var Yr={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var oe=Symbol.for("queryPath"),St=Symbol.for("stepPrint"),ve=Symbol.for("edgeType"),Oe=Symbol.for("edgeSchema");var et=Symbol.for("dbNode"),Kt=Symbol.for("isTransformed"),wt=Symbol.for("parent"),pe=Symbol.for("fieldSchema"),v=Symbol.for("sharedMetadata"),ht=Symbol.for("flexDataValue"),Ne=Symbol.for("suqlMetadata");var en=(e,t)=>{let r=Xr(e.entities),n=Xr(e.relations),i=es(e),o={entities:{},relations:{}};return r.forEach(s=>{let a=e.entities[s];if(!a)throw new Error(`Entity "${s}" does not exist`);let l="extends"in a?o.entities[a.extends]:void 0;l&&Xt(o,l.name,s);let d=Zr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i});o.entities[s]={...d,defaultDBConnector:a.defaultDBConnector,thingType:"entity"};}),n.forEach(s=>{let a=e.relations[s];if(!a)throw new Error(`Relation "${s}" does not exist`);let l="extends"in a?o.relations[a.extends]:void 0;l&&Xt(o,l.name,s);let d=Zr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i}),c={...d,defaultDBConnector:a.defaultDBConnector,roles:Object.fromEntries(Object.entries(a.roles??{}).map(([u,p])=>[u,Gr({role:p,roleName:u,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i})])),thingType:"relation"};"extends"in a&&l&&Object.entries(l?.roles??{}).forEach(([u,p])=>{let f=Gr({role:p,roleName:u,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i});c.roles[u]={...f,inherited:true,[v]:{...p[v],inheritanceOrigin:p[v]?.inheritanceOrigin||a.extends}};}),o.relations[s]=c;}),Object.values(o.entities).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Yt(o,a.$things);});}),Object.values(o.relations).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Yt(o,a.$things);}),Object.values(s.roles??{}).forEach(a=>{a.$things=Yt(o,a.$things);});}),o},Xr=e=>{let t=[],r=new Set,n=new Set;for(let i of Object.keys(e))tn({thingMap:e,name:i,inProcess:n,seen:r,ordered:t});return t},tn=e=>{let{thingMap:t,name:r,inProcess:n,seen:i,ordered:o}=e;if(i.has(r))return;if(n.has(r))throw new Error(`A list of thing extends each other that creates circular dependencies: ${[...n]}`);n.add(r);let s=t[r];if(!s)throw new Error(`Entity/relation "${r}" does not exist`);"extends"in s&&tn({...e,name:s.extends}),n.delete(r),i.add(r),o.push(r);},Go=(e,t)=>{let r=t,n=[];for(;r;){let i=e.entities[r]||e.relations[r];if(!i)throw new Error(`Entity/relation "${r}" does not exist`);n.push(r),r="extends"in i?i.extends:void 0;}return n.length!==0?n:void 0},Xt=(e,t,r)=>{let n=e.entities[t]??e.relations[t];if(!n)throw new Error(`Entity/relation "${t}" does not exist`);n.subTypes=n.subTypes??[],n.subTypes.push(r),n.extends&&Xt(e,n.extends,r);},Zr=e=>{let{schema:t,enrichedSchema:r,name:n,thing:i,dbHandles:o,extendedThing:s,allLinkFields:a}=e,[l]=Object.entries(o).find(([h,$])=>$.get(i.defaultDBConnector.id))??[];if(!l)throw new Error(`DB handle for ${i.defaultDBConnector.id} does not exist`);let d=[...i.idFields??s?.idFields??[]];if(d.length===0)throw new Error(`"${n}" does not have an id field`);let c={...i.hooks},u=i.dataFields?.map(h=>ts(h,n,d))??[],p=i.linkFields?.map(h=>ns({linkField:h,thingName:n,thing:i,schema:t,allLinkFields:a}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([h,$])=>[h,rs($,h)]));return "extends"in i&&s&&(s.hooks?.pre&&(c.pre=[...s.hooks.pre||[],...i.hooks?.pre||[]]),s.dataFields?.forEach(h=>{u.push({...h,inherited:true,[v]:{...h[v],inheritanceOrigin:h[v]?.inheritanceOrigin||i.extends}});}),s.linkFields?.forEach(h=>{p.push({...h,inherited:true,[v]:{...h[v],inheritanceOrigin:h[v]?.inheritanceOrigin||i.extends}});}),Object.entries(s.refFields??{}).forEach(([h,$])=>{f[h]={...$,inherited:true,[v]:{...$[v],inheritanceOrigin:$[v]?.inheritanceOrigin||i.extends}};})),{...i,name:n,db:l,dbContext:Yr[l],idFields:d,hooks:c,dataFields:u,linkFields:p,refFields:f,enumFields:u?.filter(h=>h.validations?.enum).map(h=>h.path)??[],fnValidatedFields:u?.filter(h=>h.validations?.fn).map(h=>h.path)??[],virtualFields:u?.filter(h=>h.isVirtual).map(h=>h.path)??[],computedFields:u?.filter(h=>h.default&&!h.isVirtual).map(h=>h.path)??[],requiredFields:u?.filter(h=>h.validations?.required).map(h=>h.path)??[],allExtends:"extends"in i?Go(r,i.extends):void 0,dbProviderConfig:l==="surrealDB"?o[l]?.get(i.defaultDBConnector.id)?.providerConfig:void 0}},es=e=>{let t=[];return Object.entries(e.entities).forEach(([r,n])=>{n.linkFields?.forEach(i=>{t.push({...i,thing:r,thingType:"entity",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),Object.entries(e.relations).forEach(([r,n])=>{n.linkFields?.forEach(i=>{t.push({...i,thing:r,thingType:"relation",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),t},ts=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:is(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:false,[v]:{fieldType:"dataField"},[Ne]:{dbPath:e.path}}),rs=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[v]:{fieldType:"refField"}}),ns=e=>{let{linkField:t,thing:r,thingName:n,schema:i,allLinkFields:o}=e,s=i.relations[t.relation];if(!t.isVirtual){if(!s)throw new Error(`The relation ${t.relation} does not exist in the schema`);if(!rn(i,t.relation,t.plays))throw new Error(`The role ${t.plays} is not defined in the relation ${t.relation} (linkField: ${t.path})`)}let a=t.cardinality==="MANY"?`$parent.[\`${t.path}\`]`:`$parent.\`${t.path}\``;if(t.target==="relation"){if(t.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${n}" LinkField: "${t.path}."`);return {...t,$things:[t.relation],oppositeLinkFieldsPlayedBy:[{plays:t.path,thing:t.relation,thingType:"relation"}],fieldType:"linkField",inherited:false,[v]:{fieldType:"linkField"},[Ne]:{queryPath:a}}}let l=o.filter(d=>d.relation===t.relation&&d.plays!==t.plays&&d.target==="role");if(l.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${n}" LinkField: "${t.path}."`);return l.length>1&&console.warn(`[Schema] LinkField ${t.path} in ${n} has multiple candidates ${l.map(d=>d.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`),{...t,fieldType:"linkField",pathToRelation:r.linkFields?.find(d=>d.target==="relation"&&d.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:false,$things:l.map(d=>d.thing),oppositeLinkFieldsPlayedBy:l,[v]:{fieldType:"linkField"},[Ne]:{queryPath:a}}},Gr=e=>{let{role:t,roleName:r,relationName:n,relation:i,allExtends:o,allLinkFields:s}=e;if(i.dataFields?.find(d=>d.path===r)||i.linkFields?.find(d=>d.path===r))throw new Error(`[Schema] The path ${r} is already in use by a dataField or linkField in ${n}.`);let a=s.filter(d=>d.relation===n&&d.plays===r),l=s.filter(d=>d.target==="relation"&&d.plays===r&&o?.includes(d.relation));return {...t,fieldType:"roleField",inherited:false,playedBy:a.map(d=>({...d,pathToRelation:d.target==="relation"?d.path:i.linkFields?.find(c=>c.target==="relation"&&c.relation===r&&c.plays===r)?.path??d.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:r,$things:[...new Set(a.map(d=>d.thing))],[v]:{fieldType:"roleField"},[Ne]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${r}\`]`:`$parent.\`${r}\``}}},is=(e,t,r)=>r?t:`${e}\xB7${t}`,rn=(e,t,r)=>{let n=e.relations[t];if(!n)throw new Error(`Relation "${t}" does not exist`);return n.roles?.[r]?true:"extends"in n?rn(e,n.extends,r):false},Yt=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var on=e=>{let t=fs(e),r={},n=us(t);for(let i in t.entities)Zt("entity",i,r,t,n);for(let i in t.relations)Zt("relation",i,r,t,n);return r},Zt=(e,t,r,n,i)=>{let o=r[t];if(o){if(o.type===e)return o;throw new Error(`Found entity and relation with the same name: ${t}`)}let s=e==="entity"?n.entities[t]:n.relations[t];if(!s)throw new Error(`${e==="entity"?"Entity":"Relation"} "${t}" not found`);let a="extends"in s&&s.extends?Zt(e,s.extends,r,n,i):void 0;a&&ss(a.name,t,r);let l={},d=a?a.idFields:hs(t,s);if(as(l,s.dataFields??[],t),ls(l,s.refFields??{},t),cs(l,s.linkFields??[],t,n,i),e==="entity"){let u={type:"entity",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=u,u}"roles"in s&&s.roles&&ds(l,s.roles??{},t,i);let c={type:"relation",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=c,c},ss=(e,t,r)=>{let n=e;for(;n;){let i=r[n];if(!i)throw new Error(`Thing "${n}" not found`);i.subTypes.push(t),n=i.extends;}},as=(e,t,r)=>{for(let n of t??[]){let i=e[n.path];if(n.isVirtual){if(n.default?.type==="fn"&&typeof n.default.fn=="function"){let s={type:"computed",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",fn:n.default.fn};He(r,s,i),e[n.path]=s;continue}if(n.default?.type==="value"){let s={type:"constant",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",value:n.default.value};He(r,s,i),e[n.path]=s;continue}}let o={type:"data",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",unique:n.validations?.unique??false};He(r,o,i),e[n.path]=o;}},ls=(e,t,r)=>{for(let[n,i]of Object.entries(t??{})){let o=e[n],s={type:"ref",name:n,contentType:i.contentType,cardinality:i.cardinality??"ONE"};He(r,s,o),e[n]=s;}},cs=(e,t,r,n,i)=>{for(let o of t??[]){let s=n.relations[o.relation];if(!s)throw new Error(`Relation ${o.relation} not found`);let a=s.roles?.[o.plays];if(!a)throw new Error(`Role ${o.plays} not found in relation ${o.relation}`);let l=e[o.path];if(o.target==="relation"){let p={type:"link",name:o.path,cardinality:o.cardinality,target:"relation",opposite:{thing:o.relation,path:o.plays,cardinality:a.cardinality}};He(r,p,l),e[o.path]=p;continue}let d=i[o.relation]?.[o.targetRole];if(!d)throw new Error(`Role ${o.targetRole} in relation ${o.relation} does not exist`);let c=d.targetingRole;if(!c)throw new Error(`Role "${o.targetRole}" in relation "${o.relation}" is not played by any other thing that targets role "${o.plays}"`);let u={type:"link",name:o.path,cardinality:o.cardinality,target:"role",opposite:c};He(r,u,l),e[o.path]=u;}},ds=(e,t,r,n)=>{for(let[i,o]of Object.entries(t)){let s=n[r]?.[i]?.targetingRelation??n[r]?.[i]?.targetingRole;if(!s)throw new Error(`Role ${i} in relation ${r} is not played by any other thing`);let a=e[i],l={type:"role",name:i,cardinality:o.cardinality??"ONE",opposite:s};He(r,l,a),e[i]=l;}},He=(e,t,r)=>{if(r&&!isEqual(t,r))throw new Error(`Duplicate field name "${t.name}" in "${e}"`)},us=e=>{let t={};for(let[r,n]of [...Object.entries(e.relations),...Object.entries(e.entities)])for(let i of n.linkFields??[]){let o=t[i.relation]??{};t[i.relation]=o;let s=o[i.plays]??{};o[i.plays]=s;let a=i.target==="relation"?s.targetingRelation:s.targetingRole;if(a){if(a.thing===r||nn(r,a.thing,e))continue;if(!nn(a.thing,r,e))throw new Error(`Found multiple players for role ${i.plays} in relation ${i.relation}`)}i.target==="relation"?s.targetingRelation={thing:r,path:i.path,cardinality:i.cardinality}:s.targetingRole={thing:r,path:i.path,cardinality:i.cardinality};}return t},nn=(e,t,r)=>ps(e,r).includes(t),ps=(e,t)=>{let r=[],n=e;for(;n;){let i=t.entities[n]??t.relations[n];if(!i)throw new Error(`Thing "${n}" not found`);if(!("extends"in i)||!i.extends)break;r.push(i.extends),n=i.extends;}return r.reverse()},hs=(e,t)=>{if(t.idFields&&t.idFields.length>0)return [t.idFields[0],...t.idFields.slice(1)];let r=t.dataFields?.find(n=>n.contentType==="ID");if(r)return [r.path];throw new Error(`No id field found for entity "${e}"`)},fs=e=>{let t={entities:{},relations:{}};for(let r in e.entities)sn(r,e,t);for(let r in e.relations)an(r,e,t);return t},sn=(e,t,r)=>{let n=t.entities[e];if(!n)throw new Error(`Entity "${e}" not found`);if("extends"in n&&n.extends){let i=sn(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:ln(i,n),linkFields:cn(i,n),refFields:dn(i,n)};return r.entities[e]=o,o}return r.entities[e]=n,n},an=(e,t,r)=>{let n=t.relations[e];if(!n)throw new Error(`Relation "${e}" not found`);if("extends"in n&&n.extends){let i=an(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:ln(i,n),linkFields:cn(i,n),refFields:dn(i,n),roles:$s(i,n)};return r.relations[e]=o,o}return r.relations[e]=n,n},ln=(e,t)=>{let r=new Set(t.dataFields?.map(i=>i.path)??[]);return [...e.dataFields?.filter(i=>!r.has(i.path))??[],...t.dataFields??[]]},cn=(e,t)=>{let r=new Set(t.linkFields?.map(i=>i.path)??[]);return [...e.linkFields?.filter(i=>!r.has(i.path))??[],...t.linkFields??[]]},dn=(e,t)=>({...Object.fromEntries(Object.entries(e.refFields??{}).filter(([n])=>!t.refFields?.[n])),...t.refFields??{}}),$s=(e,t)=>({...Object.fromEntries(Object.entries(e.roles??{}).filter(([n])=>!t.roles?.[n])),...t.roles??{}});var tr={};No(tr,{action:()=>Es,createMachine:()=>Ms,d:()=>Je,guard:()=>Bs,immediate:()=>bs,interpret:()=>Sn,invoke:()=>Ls,reduce:()=>yn,state:()=>ws,transition:()=>Fs});function he(e){return {enumerable:true,value:e}}function un(e){return {enumerable:true,writable:true,value:e}}var Je={},ms=()=>true,pn=()=>({}),fn=e=>e,ys=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),gs=(e,t,r,[n,i])=>t.call(r,e.call(r,n,i),i),qe=(e,t)=>Object.freeze(Object.create(e,t));function hn(e,t,r){return e.reduce((n,i)=>function(...o){return r(n,i,this,o)},t)}function $n(e){return qe(this,{fn:he(e)})}var mn={},yn=$n.bind(mn),Es=e=>yn((t,r)=>!!~e(t,r)&&t),gn={},Bs=$n.bind(gn);function Rt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function En(e,t,...r){let n=hn(Rt(gn,r).map(o=>o.fn),ms,ys),i=hn(Rt(mn,r).map(o=>o.fn),fn,gs);return qe(this,{from:he(e),to:he(t),guards:he(n),reducers:he(i)})}var Bn={},Fn={},Fs=En.bind(Bn),bs=En.bind(Fn,null);function Ts(e,t,r){return er(t,e,r,this.immediates)||e}function bn(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 Ss={enter:fn};function ws(...e){let t=Rt(Bn,e),r=Rt(Fn,e),n={final:he(e.length===0),transitions:he(bn(t))};return r.length&&(n.immediates=he(r),n.enter=he(Ts)),qe(Ss,n)}var Rs={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Gt.isPrototypeOf(n)?qe(Tn,{machine:he(n),transitions:he(this.transitions)}).enter(e,t,r):(n.then(i=>{if(e===t.machine)return t.send({type:"done",data:i})}).catch(i=>{if(e===t.machine)return t.send({type:"error",error:i})}),e)}},Tn={enter(e,t,r){if(t.child=Sn(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,er(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function Ls(e,...t){let r=he(bn(t));return Gt.isPrototypeOf(e)?qe(Tn,{machine:he(e),transitions:r}):qe(Rs,{fn:he(e),transitions:r})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function Ms(e,t,r=pn){return typeof e!="string"&&(r=t||pn,t=e,e=Object.keys(t)[0]),Je._create&&Je._create(e,t),qe(Gt,{context:he(r),current:he(e),states:he(t)})}function er(e,t,r,n){let{context:i}=e;for(let{to:o,guards:s,reducers:a}of n)if(s(i,r)){e.context=a.call(e,i,r);let l=t.original||t,d=qe(l,{current:he(o),original:{value:l}});Je._onEnter&&Je._onEnter(t,o,e.context,i,r);let c=d.state.value;e.machine=d;let u=c.enter(d,e,r);return e.onChange(e),u}}function Qs(e,t){let r=t.type||t,{machine:n}=e,{value:i,name:o}=n.state;return i.transitions.has(r)?er(e,n,t,i.transitions.get(r))||n:(Je._send&&Je._send(r,o),n)}var Ds={send(e){Qs(this,e);}};function Sn(e,t,r,n){let i=Object.create(Ds,{machine:un(e),context:un(e.context(r,n)),onChange:he(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,n),i}var{createMachine:we,guard:rr,interpret:Re,invoke:U,reduce:q,state:me,transition:x}=tr;var G="0.15.4";var Ln=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ye=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,i])=>{let[o,s]=tryit(()=>t(n,i))();return o?false:s}))},ee=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},V=(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)}`)},Lt=(e,t)=>{let r=e.dataFields?.find(o=>o.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(o=>o.path===t);if(n)return ["linkField",n];let i="roles"in e?e.roles[t]:void 0;if(i)return ["roleField",i];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Mt=(e,t)=>{let r=V(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},Mn=(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")},ir=(e,t,r)=>{let n=V(e,t),i=n.linkFields?.find(l=>l.path===r);if(i)return i;let o=n.dataFields?.find(l=>l.path===r);if(o)return o;let s="roles"in n?n.roles?.[r]:void 0;if(s)return s;let a="refFields"in n?n.refFields?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},or=(e,t,r)=>ir(e,t,r)?.cardinality,ge=(e,t)=>{let r=e.dataFields?.map($=>$.path)||[],n=e.linkFields?.map($=>$.path)||[],i="refFields"in e?listify(e.refFields,$=>$):[],o="roles"in e?listify(e.roles,$=>$):[],s=[...r||[],...n||[],...o||[],...i||[]],l=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...s];if(!t)return {fields:s,dataFields:r,roleFields:o,linkFields:n};let d=t.$fields?t.$fields.map($=>{if(typeof $=="string"){if($.startsWith("$")||$.startsWith("%"))return;if(!s.includes($))throw new Error(`Field ${$} not found in the schema`);return $}if("$path"in $&&typeof $.$path=="string")return $.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,$=>{if(!($.startsWith("$")||$.startsWith("%"))){if(!s.includes($))throw new Error(`[Schema] Field ${$} not found in the schema`);return $}}).filter($=>$!==void 0),c=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&r?.includes($)):[],u=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&[...o||[],...n||[]].includes($)):[],p=[...d,...c].filter($=>!$?.startsWith("%")).filter($=>!l.includes($)).filter($=>$),f=t.$filter?ye(t.$filter,($,E)=>c.includes($)):{},h=t.$filter?ye(t.$filter,($,E)=>u.includes($)):{};return {fields:s,dataFields:r,roleFields:o,linkFields:n,refFields:i,usedFields:d,usedLinkFields:n.filter($=>d.includes($)),usedRoleFields:o.filter($=>d.includes($)),usedDataFields:r.filter($=>d.includes($)),usedRefFields:i.filter($=>d.includes($)),unidentifiedFields:p,...c.length?{localFilters:f}:{},...u.length?{nestedFilters:h}:{}}};var Qn=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Dn=(e,t,r)=>{let i=(r.nodePath||"").split("."),o=isArray(t)?i.slice(0,-2).join("."):i.slice(0,-1).join(".");return t?getNodeByPath(e,o):{}},xe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Qt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Ie=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};for(let[n,i]of Object.entries(t))r[n]=isDraft(i)?current(i):i;return r}return e},Ee=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},L=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},je=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)(),sr=(e=5)=>customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e)(),An=e=>{let t=({value:r})=>{if(r&&typeof r=="object"&&"$id"in r){let n=Object.keys(r).filter(i=>i.startsWith("$"));for(let i of n)delete r[i];}return r};return produce(e,r=>traverse(r,t))};var rt=(e,t)=>{for(let i of e)if(!("$entity"in i)&&!("$relation"in i)&&(!("$thing"in i)||!("$thingType"in i)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,i=>traverse(i,o=>{let{value:s,meta:a}=o,l=s;if(isObject(l)){if(a.nodePath?.includes(".$filter")||a.nodePath?.includes(".$playedBy"))return;if(l[oe]=a.nodePath,l.$id){let d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=V(t,d);if(!c?.name)throw new Error(`Schema not found for ${l.$thing}`);if(l.$path=c.name,Array.isArray(l.$id)||(l.$filterByUnique=true),c.idFields.length===1){let[u]=c.idFields;l.$filter={...l.$filter,[u]:l.$id},l.$id=void 0;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in l||"$relation"in l||"$thing"in l){let d=V(t,l);if(!d?.name)throw new Error(`Schema not found for ${l.$thing}`);l.$path=d.name;}if(l.$entity?(l.$thing=l.$entity,l.$thingType="entity",l.$entity=void 0):l.$relation&&(l.$thing=l.$relation,l.$thingType="relation",l.$relation=void 0),isObject(l)&&"$thing"in l&&l.$thing){let d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=V(t,d);if(l.$filter&&(Object.keys(l.$filter).length===0?l.$filter=void 0:(l.$filter=_e(l.$filter,l.$thing,t),l.$filterByUnique=lr(l.$filter,c))),l.$fields){l.$fields.some(f=>c?.idFields?.includes(f?.$path||f))||(l.$fields=[...l.$fields,...Array.isArray(c.idFields)?c.idFields:[]],l.$idNotIncluded=true);let p=l.$fields?.flatMap(f=>{let h=On(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}else {let p=ar(c)?.flatMap(f=>{let h=On(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>Dt(c,u)?true:!l.$excludedFields.includes(u.$path)));}}}))},ar=e=>{let t=e.dataFields?.map(s=>s.path)||[],r=e.linkFields?.map(s=>s.path)||[],n=Object.keys(e.roles||{})||[],i=Object.keys(e.refFields||{})||[];return [...t,...r,...n,...i]},lr=(e,t)=>Object.keys(e||{}).some(n=>{let i=e[n];if(i!==null&&typeof i<"u"){let o=t.idFields?.includes(n),s=t.dataFields?.some(d=>(d.dbPath===n||d.path===n)&&d?.validations?.unique),a=n==="$id"&&!Array.isArray(i);if(o||s||a){if(typeof i!="object"||i===null||Array.isArray(i))return !Array.isArray(i);let d=Object.keys(i);if(d.length===1&&d[0]==="$eq"){let c=i.$eq;if(typeof c!="object"||c===null||!Array.isArray(c))return true}return false}}return false}),Dt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),xs=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:i,isVirtual:o,fieldSchema:s}=e;return {$path:r,$dbPath:i,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:o,[pe]:s}},js=e=>{let{field:t,fieldStr:r,linkField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e,{target:l,oppositeLinkFieldsPlayedBy:d}=n;return d.map(c=>{let u=l==="role"?c.thingType:"relation",p=l==="role"?c.thing:n.relation,f={[`$${u}`]:p},h=V(s,f),$=t?.$fields?.filter(m=>Dt(h,m)).length===0,E=[];if(typeof t!="string")if(t.$fields)if($){let m=h.idFields||[];E=[...t.$fields,...m];}else E=t.$fields;else E=ar(h);else E=["id"];t.$excludedFields&&(E=E.filter(m=>Dt(h,m)?true:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$plays:n.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:o,$as:t.$as||r,$var:r,$thing:p,$fields:E,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:y,$idNotIncluded:$,$filterByUnique:lr(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[pe]:a}})},_s=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:i,fieldSchema:o}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:r,$dbPath:i,$contentType:o.contentType,$as:t.$as||r,$var:r,$fieldType:"ref",$justId:n,$fields:t.$fields,$id:t.$id,[pe]:o}},Vs=e=>{let{field:t,fieldStr:r,roleField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e;return n.playedBy.map(l=>{let{thing:d,thingType:c,relation:u}=l,p={[`$${c}`]:d},f=V(s,p),h=t?.$fields?.filter(y=>f?.idFields?.includes(y)||f?.idFields?.includes(y.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let y=f.idFields||[];$=[...t.$fields,...y];}else $=t.$fields;else $=ar(f);else $=["id"];t.$excludedFields&&($=$.filter(y=>Dt(f,y)?true:!t.$excludedFields.includes(y.$path)));let E=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:r,$dbPath:o,$as:t.$as||r,$var:r,$thing:d,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:i,$id:t.$id,$filter:E,$idNotIncluded:h,$filterByUnique:lr(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[pe]:a}})},On=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,i=typeof e=="string",o=t.dataFields?.find(d=>d.path===n),s=t.linkFields?.find(d=>d.path===n),a=t.roles?.[n],l=t.refFields?.[n];if(o){let d=!!o.isVirtual&&!!o.default;return xs({field:e,fieldStr:n,$justId:i,dbPath:o.dbPath,isVirtual:d,fieldSchema:o})}return s?js({field:e,fieldStr:n,linkField:s,$justId:i,dbPath:s.path,schema:r,fieldSchema:s}):a?Vs({field:e,fieldStr:n,roleField:a,$justId:i,dbPath:n,schema:r,fieldSchema:a}):l?_s({field:e,fieldStr:n,$justId:i,dbPath:n,isVirtual:false,fieldSchema:l}):null},_e=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(s=>Object.keys(s).reduce((d,c)=>{let u=s[c],p=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))d[c]=u;else if(["$not","$or","$and"].includes(c))d[c]=_e(u,t,r);else if(["$eq","$in","$exists"].includes(c))d[c]=u;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[h,$]=Lt(f,c);if(h==="idField")d[c]=u;else if(h==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?d[c]=isArray(u)?{$or:_e(u,t,r)}:_e(u,t,r):isArray(u)?d[c]={$in:u}:d[c]={$eq:u};else if(h==="linkField"||h==="roleField"){let E=$,[y]=E.$things;p.every(m=>typeof m=="string")?d[c]={$id:p,$thing:y}:p.every(m=>isObject(m))&&(d[c]=isArray(u)?{$or:_e(u,y,r)}:_e(u,y,r));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return d},{}));return !n||o.length===1?o[0]:{$or:o}};var Us=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Ws=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Nn=e=>{let r=e.toString().replace(Us,"").trim().split("=>")[0].split("{")[0].replace(Ws,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(o=>o.includes("{")&&o.includes("}")?(o.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(a=>a.split(":")[0].trim().replace(/['"[\]]/g,"")):o.trim()).filter(Boolean):[]};var nt=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=false})=>{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,o=Nn(n).filter(s=>!(s in e));if(o.length)throw new Error(`Virtual field: Missing arguments ${o.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 In=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(i=>{if(i.$op!=="create")return;let o=V(r,i),{unidentifiedFields:s}=ge(o,i),{computedFields:a,virtualFields:l}=o,d=listify(i,(p,f)=>f!==void 0?p:void 0),c=d.filter(p=>l?.includes(p));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(a.filter(p=>!d.includes(p)).forEach(p=>{let f=o.dataFields?.find(m=>m.path===p),$=o.linkFields?.find(m=>m.path===p)?.oppositeLinkFieldsPlayedBy[0],E="roles"in o?Ln(o.roles,(m,B)=>m===p):void 0,y=f||$||E;if(!y)throw new Error(`no field Def for ${p}`);if(!i[p]){let m=nt({currentThing:i,fieldSchema:y,mandatoryDependencies:true});i[p]=m;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(i)}`)}),e};var cr=(e,t)=>e.$bzId?e.$bzId:e.$tempId?e.$tempId:e.$id&&!isArray(e.$id)?t?`SN_ONE_${t}_${e.$id}`:`SN_ONE_${e.$id}`:e.$id&&isArray(e.$id)?t?`SN_MANY_${t}_${je()}`:`SN_MANY_${je()}`:`SM_${je()}`;var Ve=(e,t,r)=>{if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);let n=V(r,t),{usedDataFields:i}=ge(n,t);if(t.$op==="delete"&&i.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&i.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}},Cn=(e,t,r)=>{(isArray(t)?t:[t]).forEach(i=>{Ve(e,i,r);});};var Pn=e=>{let t=Object.keys(e).filter(r=>!(r.startsWith("$")||r.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},qn=(e,t,r)=>{let n=V(r,t),{usedFields:i}=ge(n,t);return t.$op?(Ve(e,t,r),t.$op):t.$id||t.$filter?i.length>0?(Ve(e,{...t,$op:"update"},r),"update"):(Ve(e,{...t,$op:"link"},r),"link"):t.$tempId?i.length>0?(Ve(e,{...t,$op:"create"},r),"create"):(Ve(e,{...t,$op:"create"},r),"link"):(Ve(e,{...t,$op:"create"},r),"create")};var At=(e,t)=>{if(t[v].fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}if(t[v].fieldType==="roleField"){let r=t;if([...new Set(r.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r.playedBy}throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var jn=e=>isArray(e)?e.map(jn):isObject(e)?{...e,[ht]:true}:e,_n=(e,t,r,n)=>{let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);let s=Pn(o),a=cr(o);if(r[v].fieldType==="refField"){let c=r;if(!isObject(o)){if(c.contentType==="FLEX")return isArray(o)?[jn(o)]:o;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!o.$thing){if(c.contentType==="FLEX")return {...o,[ht]:true};throw new Error("[Wrong format] The field $thing is required in refFields")}return {...o,$op:s,$bzId:a}}let l=r;if(l.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let d=r;if(d.$things.length===1){let c=At(t,l),[u]=c;if(o.$thing&&o.$thing!==u.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${u.thing}.`);return {...o,[Oe]:d,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:s,$bzId:a}}if(o.$thing)return [{...o,[Oe]:d,$thing:o.$thing,$thingType:o.$thing in n.entities?"entity":"relation",$op:s,$bzId:a}];if(o.$tempId)throw new Error("[Unsupported] Objects with $tempId and multiple potential players require to explicitly indicate the $thing type.");if(s==="create")throw new Error(`[Wrong format] The field ${t} can be played by multiple things, please specify one on creation.`);return d.$things.map(c=>({...o,[Oe]:d,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:s,$bzId:cr(o,c)}))});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var Ot=(e,t)=>{let r=V(t,e).hooks;if(r?.pre){let n=`on${Qn(e.$op)}`;return r.pre.filter(s=>!s.triggers||s.triggers[n]?.()).flatMap(s=>s.actions)}return []};var Vn=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!Qt(o)||o.$fields||o[Kt])return;let s=Ot(o,r).filter(u=>u.type==="transform"),a=clone(Ie(e)),l=clone(Ie(o)),d=n.mutation?.context||{},c=clone(Ie(o[et]||o.$dbNode));s.forEach(u=>{let p=u.fn(l,a,d,c||{});Object.keys(p).length!==0&&(l={...l,...p,...xe(o),[Kt]:true},Object.assign(o,l));});});};var Un=(e,t,r,n)=>{let i=isArray(e[t])?e[t]:[e[t]];for(let o of i)if("$thing"in o){if(o.$fields)continue;let{requiredFields:s,enumFields:a,fnValidatedFields:l,dataFields:d}=V(r,o);if("$op"in o&&o.$op==="create"){for(let c of s)if(!(c in o))throw new Error(`[Validations] Required field "${c}" is missing.`)}if("$op"in o&&o.$op==="update"||o.$op==="create"){for(let c of a)if(c in o){let u=d?.find(p=>p.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(o[c])){for(let p of o[c])if(p!==null&&!u.includes(p))throw new Error(`[Validations] Option "${p}" is not a valid option for field "${c}".`)}else if(u&&!u.includes(o[c])&&o[c]!==null)throw new Error(`[Validations] Option "${o[c]}" is not a valid option for field "${c}".`)}}if("$op"in o&&o.$op==="update"||o.$op==="create"){for(let c of l)if(c in o)try{let u=d?.find(p=>p.path===c)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(o[c]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${c}] ${u.message}`)}}if(isObject(o)&&"$thing"in o){let c=o.$thing,u=o,p=clone(Ie(e)),f=clone(Ie(u)),h=n.mutation?.context||{},$=clone(Ie(o[et]||{})),E=Ot(u,r);for(let y of E)if(y.type==="validate"){if(y.severity!=="error")continue;try{let m=y.fn(f,p,h,$);if(m===!1)throw new Error(`${y.message}.`);if(m!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(m){throw new Error(`[Validations:thing:${c}] ${m.message}`)}}}}};var Wn=(e,t,r,n)=>{let i=isArray(e[t])?e[t]:[e[t]],o=n.slice(1).join(".");i.forEach(s=>{if(s){if(r?.cardinality==="ONE"&&!s.$op&&!s.$id&&!s.$filter&&!s.$tempId&&e.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${o}.${t}`);if(s.$tempId&&!(s.$op===void 0||s.$op==="link"||s.$op==="create"||s.$op==="update"||s.$op==="replace"))throw new Error(`Invalid op ${s.$op} for tempId. TempIds can be created, or linked when created in another part of the same mutation.`)}});};var Hn=e=>{if(typeof e!="string")return {isPrefixed:false,obj:e};let t=e.match(/^([^:]+):([^:]+)$/),r=e.match(/^([^:]+):_:([^:]+)$/);if(t&&!e.includes(" ")){let[,n,i]=t;return {isPrefixed:true,obj:{$thing:n,$id:i}}}if(r&&!e.includes(" ")){let[,n,i]=r;return {isPrefixed:true,obj:{$thing:n,$tempId:`_:${i}`}}}return {isPrefixed:false,obj:e}},Jn=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(n.every(s=>typeof s=="object"))return;if(!n.every(s=>typeof s=="string"||isObject(s)&&"$op"in s&&s.$op==="replace"))throw new Error(`[Mutation Error] Replace can only be used with a single id, an array of ids, or objects with $op: replace. (Field: ${t} Nodes: ${JSON.stringify(n)})`);let i=e.$op==="update"&&r?.[v].fieldType==="linkField"&&r.cardinality==="ONE",o=e.$op==="create"||i?"link":"replace";e[t]=n.map(s=>{if(typeof s=="string"){if(s.startsWith("_:"))return {$tempId:s,$op:o};let{isPrefixed:a,obj:l}=Hn(s);return a?{...l,$op:o}:{$id:s,$op:o}}return s});},Kn=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]],i=e.$op==="create"?"link":"replace";return e[t]=n.map(o=>{if(typeof o=="string"){if(o.startsWith("_:"))return {$tempId:o,$op:i};let{isPrefixed:s,obj:a}=Hn(o);if(s)return {...a,$op:i};if(r.contentType==="FLEX")return o;throw new Error("[Wrong format] Field of contentType REF can't use strings as references unless they follow the format `$thing:$id`")}if(typeof o=="object"&&"$thing"in o||r.contentType==="FLEX")return o;throw new Error("[Wrong format] Field of contentType REF can use prefixed id strings, tempIds or objects indicating their $thing")}),e[t]};var Xn=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=qn(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:Mn(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${je()}`}},...i}});e.$root=isArray(e.$root)?n:n[0];};var Nt=(e,t)=>{let r=t[St];return isSet(r)?r.has("clean")?(Reflect.set(t,St,r.add("clean")),true):false:(Reflect.set(t,St,new Set(["clean"])),true)};var Zn=(e,t,r)=>{if(Nt("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(isObject(i)&&"$id"in i&&isArray(i.$id)){let o=i;if(V(r,o),!o.$bzId)throw new Error("[Internal Error] No bzId found");return o.$id.map((s,a)=>({...Ie(o),$id:s,$bzId:`${o.$bzId}_${a}`,...xe(o)}))}return i});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Gn=(e,t,r)=>{let n=At(t,r),[i]=n;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Oe]:r};};var it=e=>{if(Array.isArray(e)){for(let t of e)if(it(t))return true;return false}if(e.$fields)return true;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&it(e[t]))return true}return false};var aa=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Nt("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);},hr=(e,t,r)=>{let n={$rootWrap:{$root:e}},i=it(Array.isArray(e)?e:[e]),o=produce(n,s=>traverse(s,({value:a,parent:l,key:d,meta:c})=>{if(!(!l||!d)&&isObject(a)){let u=c.nodePath?.split(".")||[];if(u.some(h=>h.startsWith("%"))||ht in a)return;if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let h=["$fields","$dbNode","$filter"],$=u.at(-1),E=u.at(-2);if(d==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($||"")&&!h.includes(E||"")&&!$?.startsWith("%")&&!E?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let p=a,f=u.includes("$filter");"$filter"in p&&p.$filter&&(p.$filter=_e(p.$filter,p.$thing,t));for(let h of Object.keys(p)){if(aa(p,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))continue;let $=h!=="$root"?ir(t,p,h):{[v]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);let{fieldType:E}=$[v],y=["linkField","roleField"].includes(E),m=E==="refField",B=E==="rootField";if(E==="dataField"){continue}if((y||m)&&(p[h]===null?y&&Gn(p,h,$):y?Jn(p,h,$):Kn(p,h,$)),B){if(!("$root"in p))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Xn(p,t);}if((y||m)&&Wn(p,h,$,u),(y||m)&&(_n(p,h,$,t),Cn(p,p[h],t)),y||B){Zn(p,h,t),In(p,h,t);let g=isArray(p[h])?p[h]:[p[h]];for(let T of g){let w=V(t,T),{unidentifiedFields:M,usedLinkFields:D,usedFields:j,fields:K}=ge(w,T);for(let ce of j)if(!K.includes(ce))throw new Error(`[Schema] Field ${ce} not found in the schema`);if(M.length>0)throw new Error(`Unknown fields: [${M.join(",")}] in ${JSON.stringify(a)}`);if(D.length>1){let ce=w.linkFields?.filter(se=>D.includes(se.path));if(ce)for(let se=0;se<ce.length;se++){let I=ce[se];for(let A=0;A<ce.length;A++){let Y=ce[A];if(se!==A&&I.target!==Y.target&&I.relation===Y.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}}}}i||(Vn(p,h,t,r),Un(p,h,t,r));}}}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var It=(e,t)=>{if(!t)return;let r=da(t);return ua(r,e.query)},da=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),ua=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let i=n;Object.keys(i).forEach(o=>{(i[o]===void 0||i[o]===null||isArray(i[o])&&i[o].length===0)&&(t?.returnNulls?i[o]=null:delete i[o]),i[o]===void 0&&delete i[o];}),Object.getOwnPropertySymbols(i).forEach(o=>{delete i[o];}),t?.noMetadata===true&&Object.keys(i).forEach(o=>{o.startsWith("$")&&delete i[o];});}}));var kt=async(e,t,r)=>r?(o=>produce(o,s=>traverse(s,({value:a})=>{if(isObject(a)){let l=a;if(!l.$thing)return;if(l.$thing){let d=V(e,l),{virtualFields:c}=d,u=l[oe];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let p=getNodeByPath(t,u);if(p.$fieldType==="ref")return;let f=p.$fields.map($=>$.$path),h=p.$excludedFields;c.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let E=d.dataFields?.find(y=>y.path===$);if(E?.default){let y=nt({currentThing:l,fieldSchema:E,mandatoryDependencies:true});l[$]=y;}else if(l[$]===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 l[$];});}}})))(r):void 0;var yt={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Le=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(s=>{let l=Object.keys(s).reduce((d,c)=>{let u=s[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...d,[c]:void 0,[yt[c]]:Le(u,t,r)};if(c==="$id")return {...d,$id:void 0,[yt[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return d;if(c==="$exists")return {...d,$exists:void 0,[yt[c]]:u};if(c==="$eq")return {...d,$eq:void 0,[yt[c]]:u};if(c==="$in")return {...d,$in:void 0,[yt[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let p=t in r.entities?r.entities[t]:r.relations[t],[f,h]=Lt(p,c);if(f==="idField"){if(p.idFields.length>1)throw new Error("Multiple id fields not supported");return {...d,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(f==="dataField")return {...d,[c]:Le(u,t,r)};if(f==="linkField"||f==="roleField"){let E=h[Ne].queryPath;return {...d,[E]:Le(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return n?o:o[0]},be=e=>{if(e==null)return "";let t=Object.entries(e),r=[];for(let[n,i]of t){if(["$OR","$AND","$!"].includes(n)){let o=n.replace("$",""),s=Array.isArray(i)?i.map(a=>be(a)):[be(i)];o==="!"?r.push(`!(${s.join(" AND ")})`):r.push(`(${s.join(` ${o} `)})`);continue}if(isObject(i))if(n.includes("<-")||n.includes("->")){let o=be(i);r.push(`${n}[WHERE ${o}]`);}else if(n.startsWith("$parent.[")){let o=be(i),s=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${s})[WHERE id && ${o}]`);}else if(n.startsWith("$parent")){let o=be(i),s=n.replace("$parent.","");r.push(`fn::as_array(${s})[WHERE id && ${o}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let o=Object.keys(i);if(o.length===1&&o[0].startsWith("$")){let[s]=o,a=i[s];if(s==="$exists")if(a===true)r.push(`${n} IS NOT NONE`);else if(a===false)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${a}`);else {let l=s.replace("$","");if(Array.isArray(a))r.push(`${n} ${l} [${a.map(d=>d===null?"NONE":`'${d}'`).join(", ")}]`);else if(isObject(a)){let d=be(a);r.push(`${n} ${l} ${d}`);}else r.push(`${n} ${l} ${a===null?"NONE":`'${a}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(i)){let o=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${o} [${i.map(s=>s===null?"NONE":`'${s}'`).join(", ")}]`);}else {let o=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${o} ${i===null?"NONE":`'${i}'`}`);}}return r.join(" AND ")},ot=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:i}=r;return `${n}${i?" DESC":" ASC"}`}).join(", ")}`;var oi=e=>{let{queries:t,schema:r}=e;return t.map(n=>ga({query:n,schema:r}))},ga=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=[];d.push("SELECT");let c=$r({parentQuery:t,queries:i,level:1,schema:r});c&&d.push(c);let u=r.entities[n]||r.relations[n];if(!u)throw new Error(`Schema for ${n} not found`);let f=(u.subTypes?[n,...u.subTypes]:[n]).map(h=>le(h));if(t.$id)if(typeof t.$id=="string")d.push(`FROM ${f.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=f.flatMap(E=>h?.map(y=>`${E}:\u27E8${y}\u27E9`));d.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else d.push(`FROM ${f.join(",")}`);if(o){let h=Le(o,n,r),$=be(h);d.push(`WHERE ${$}`);}return l&&d.push(ot(l)),typeof a=="number"&&d.push(`LIMIT ${a}`),typeof s=="number"&&d.push(`START ${s}`),d.join(`
94
+ `)},$r=e=>{let{queries:t,schema:r,level:n,parentQuery:i}=e,o=[],s=i[oe];return o.push(L(`"${s}" as \`$$queryPath\``,n)),o.push(L("record::id(id) as `$id`",n)),o.push(L("record::tb(id) as `$thing`",n)),t.forEach(a=>{let l=Ea({query:a,level:n,schema:r});l&&o.push(l);}),o.length===0?null:o.join(`,
95
+ `)},Ea=e=>{let{query:t,schema:r,level:n}=e;if(t.$fieldType==="data")return Ba({query:t,level:n});if(t.$fieldType==="ref")throw new Error("Ref fields are not supported in this context");return t.$fieldType==="link"?Fa({query:t,level:n,schema:r}):t.$fieldType==="role"?ba({query:t,level:n,schema:r}):null},Ba=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?L(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?L(`\`${t.$path}\``,r):L(`\`${t.$path}\` AS \`${t.$as}\``,r)},Fa=e=>{let{query:t,schema:r,level:n}=e,{$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=[];d.push(L("(",n));let c=n+1;d.push(L("SELECT",c));let u=$r({parentQuery:t,queries:i,level:c+1,schema:r});u&&d.push(u);let p=t[pe][Ne].queryPath;if(d.push(L(`FROM ${p}`,c)),o){let f=Le(o,t.$thing,r),h=be(f);d.push(`WHERE ${h}`);}return l&&d.push(L(ot(l),c)),typeof a=="number"&&d.push(L(`LIMIT ${a}`,c)),typeof s=="number"&&d.push(L(`START ${s}`,c)),d.push(L(`) AS \`${t.$as}\``,n)),d.join(`
96
+ `)},ba=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let i=[];i.push(L("(",n));let o=n+1;i.push(L("SELECT",o));let s=o+1,a=$r({parentQuery:t,queries:t.$fields,level:s,schema:r});a&&i.push(a);let l=t[pe][Ne].queryPath;if(i.push(L(`FROM ${l}`,o)),t.$filter){let d=Le(t.$filter,t.$playedBy.thing,r),c=be(d);i.push(`WHERE ${c}`);}return i.push(L(`) AS \`${t.$as}\``,n)),i.join(`
97
+ `)};var si=e=>{let{queries:t,schema:r}=e;return t.map(n=>Sa({query:n,schema:r}))},Sa=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let c=t[oe],u=mr(c),p=ai(i.filter(T=>T.$fieldType==="data")),f=li(i.filter(T=>T.$fieldType==="link"||T.$fieldType==="role"),r),h=ci(i.filter(T=>T.$fieldType==="ref")),$=[...u,...p,...f,...h].join(`,
98
+ `),E=wa(t,d),y=o?`WHERE id AND (${be(Le(o,n,r))})`:"WHERE id",m=l?ot(l):"",B=typeof a=="number"?`LIMIT ${a}`:"",g=typeof s=="number"?`START ${s}`:"";return `SELECT ${$} ${E} ${y} ${m} ${B} ${g}`},wa=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(s=>le(s)),i=(s,a)=>`${s}:\`${a}\``,o=s=>n.flatMap(a=>s.map(l=>i(a,l))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${o([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${o(e.$id)}`;throw new Error("Invalid $id")},mr=e=>[`"${e}" as \`$$queryPath\``,"id && record::id(id) || null as `$id`","id && record::tb(id) || null as `$thing`"],ai=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}\``),li=(e,t)=>e.map(r=>{if(!r[oe])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(r)}`);let n=mr(r[oe]),i=ai(r.$fields.filter(f=>f.$fieldType==="data")),o=li(r.$fields.filter(f=>f.$fieldType==="link"||f.$fieldType==="role"),t),s=ci(r.$fields.filter(f=>f.$fieldType==="ref")),a=[...n,...i,...o,...s].filter(Boolean).join(`,
99
+ `),l=`FROM $parent.\`${r[pe].path}\`[*]`,d=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${be(Le(r.$filter,r.$thing,t))})`:"WHERE id",c=r.$sort?ot(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",p=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${l} ${d} ${c} ${u} ${p} ) AS \`${r.$as}\``}).filter(r=>r),ci=e=>e.map(t=>{if(!t[oe])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(t)}`);let r=mr(t[oe]);if(t.$fields?.some(s=>isObject(s)))throw new Error("[Unsupported]: Can't query nested ref fields yet");let i=[...r,"id && null || $this as `$value`",...t.$justId?"":t.$fields?.map(s=>`\u27E8${s}\u27E9`)||["*"]].join(`,
100
+ `),o=`FROM $parent.\`${t[pe].dbPath}\``;return `( SELECT ${i} ${o}) AS \`${t.$as}\``});var ui=e=>{let{res:t,queries:r,schema:n}=e;return t.map((o,s)=>pi(r[s],o,n))},pi=(e,t,r)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return yr(e,t[0],r)}if(t.length>=1)return t.map(n=>yr(e,n,r))}else throw new Error("res is unexpectedly not an array")},yr=(e,t,r)=>{let n=t.$thing||t.tb,i=n in r.entities?"entity":n in r.relations?"relation":"error";if(i==="error")throw new Error(`[Internal] The $thing ${n} is not defined in the schema.`);let o={[oe]:t.$$queryPath,$id:t.$id,$thing:zr(n),$thingType:i};return e.$fields.forEach(s=>{let a=s.$as,l=t[a];s.$path==="id"&&e.$idNotIncluded||(o[a]=Ma(s,l,r));}),o},Ma=(e,t,r)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:n}=e[pe];return di(t,n)??null}if(e.$fieldType==="ref"){let i=(isArray(t)?t:[t]).map(s=>{if(s.$thing){let a=ee(r,s.$thing),[l]=a.idFields;if(e.$justId)return s.$id;let d=u=>u&&typeof u=="object"&&"id"in u&&"tb"in u?u.id:u;return {...mapEntries(s,(u,p)=>isArray(p)?[u,p.map(f=>d(f))]:[u,d(p)]),[oe]:s.$$queryPath,[l]:s.$id}}return s.$value?di(s.$value,"FLEX"):s}),{cardinality:o}=e[pe];return o==="ONE"?i[0]:i}return e.$justId?e.$filterByUnique||e[pe].cardinality==="ONE"?t[0]?.$id??null:t?.map(n=>n.$id)??[]:e.$filterByUnique||e[pe].cardinality==="ONE"?yr(e,t[0],r):pi(e,t,r)},di=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(i=>new Date(i).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(i=>isDate(i)?new Date(i).toISOString():i);return isArray(e)?n:n[0]}return e};var hi=async e=>{let{client:t,queries:r,config:n}=e,i=`
101
101
  BEGIN TRANSACTION;
102
102
  ${r.join(";")};
103
103
  COMMIT TRANSACTION;
104
- `;return n.query?.debugger&&Z(`batchedQuery[${G}]`,JSON.stringify({batchedQuery:i})),await t.query(i)};var Aa=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,hi=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,st=x("error","error",q((e,t)=>({...e,error:t.error}))),Oa=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),rt(e.bql.raw,e.schema)),x("done","build",q(Aa)),st),build:U(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return ii({queries:e.bql.queries??[],schema:e.schema});if(t==="refs")return oi({queries:e.bql.queries??[],schema:e.schema})},x("done","run",q((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),st),run:U(async e=>pi({client:e.client,queries:Ee(e.surql.queries),config:e.config}),x("done","parse",q((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),st),parse:U(async e=>di({res:Ee(e.surql.res),queries:e.bql.queries??[],schema:e.schema,config:e.config}),x("done","postHooks",q((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),st),postHooks:U(async e=>Nt(e.schema,Ee(e.bql.queries),Ee(e.bql.res)),x("done","clean",q(hi)),st),clean:U(async e=>Ot(e.config,Ee(e.bql.res)),x("done","success",q(hi)),st),success:me(),error:me()},e=>e),Na=async e=>new Promise((t,r)=>{Re(Oa,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),fi=async(e,t,r,n)=>Na({bql:{raw:e},surql:{},schema:t,config:r,client:n,error:null});var he=z$1.json(),Me=z$1.array(he),$i=z$1.strictObject({$exists:z$1.boolean().optional(),$eq:he.optional(),$neq:he.optional(),$gt:he.optional(),$lt:he.optional(),$gte:he.optional(),$lte:he.optional(),$contains:he.optional(),$containsNot:he.optional(),$in:Me.optional(),$nin:Me.optional(),$containsAll:Me.optional(),$containsAny:Me.optional(),$containsNone:Me.optional()}),at=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>at)).optional(),$not:z$1.lazy(()=>at).optional()}).catchall(z$1.union([he,Me,z$1.lazy(()=>z$1.union([Ke,z$1.array(Ke)]))]))),Ke=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>at)).optional(),$not:z$1.lazy(()=>at).optional(),$exists:z$1.boolean().optional(),$eq:he.optional(),$neq:he.optional(),$gt:he.optional(),$lt:he.optional(),$gte:he.optional(),$lte:he.optional(),$contains:he.optional(),$containsNot:he.optional(),$in:Me.optional(),$nin:Me.optional(),$containsAll:Me.optional(),$containsAny:Me.optional(),$containsNone:Me.optional()}).catchall(z$1.union([he,Me,z$1.lazy(()=>z$1.union([Ke,z$1.array(Ke)]))]))),mi=z$1.object({$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([at,z$1.array(at)]).optional(),$fields:z$1.array(z$1.union([z$1.string(),z$1.lazy(()=>Ia)])).optional(),$excludedFields:z$1.array(z$1.string()).optional(),$limit:z$1.number().optional(),$offset:z$1.number().optional(),$sort:z$1.array(z$1.union([z$1.object({field:z$1.string(),desc:z$1.boolean().optional()}),z$1.string()])).optional()}),Ia=mi.extend({$path:z$1.string(),$as:z$1.string().optional()}),yi=mi.extend({$thing:z$1.string().optional(),$entity:z$1.string().optional(),$relation:z$1.string().optional()}).superRefine((e,t)=>{!e.$thing&&!e.$entity&&!e.$relation&&t.addIssue({code:"custom",message:"Query must contain at least one of: $thing, $entity, or $relation",path:["$thing"]});}).transform(e=>{let{$thing:t,$entity:r,$relation:n,...i}=e;return {...i,$thing:t??r??n}});var gi=(e,t,r)=>{let n=t[e.$thing],i=Ei({fields:e.$fields,thing:n,schema:t,metadata:r}),o=e.$filter?lt(e.$filter,n,t):void 0,s=Array.isArray(e.$id)?e.$id:e.$id?[e.$id]:[],a=s.length===1||Br(n,o)?"ONE":"MANY";return {source:s.length>0?{type:"record_pointer",thing:[n.name,...n.subTypes],ids:s}:{type:"table_scan",thing:[n.name,...n.subTypes]},projection:i,filter:o,limit:Ti(e.$limit),offset:Si(e.$offset),sort:wi(i,Fi(e.$sort)),cardinality:a}},Ei=e=>{let{fields:t,thing:r,schema:n,metadata:i}=e,o=[];if(i&&(o.push({type:"metadata",path:"$id"}),o.push({type:"metadata",path:"$thing"})),!t){for(let s of Object.values(r.fields))o.push(Er(s));return {fields:o}}for(let s of t){if(typeof s=="string"){if(s==="$id"||s==="$thing"){o.push({type:"metadata",path:s});continue}let u=r.fields[s];if(!u)throw new Error(`Field ${s} not found in ${r.name}`);o.push(Er(u));continue}if(s.$path==="$id"||s.$path==="$thing"){o.push({type:"metadata",path:s.$path,alias:s.$as});continue}let a=r.fields[s.$path];if(!a)throw new Error(`Field ${s} not found in ${r.name}`);if(a.type==="constant"||a.type==="computed")continue;if(a.type==="data"||a.type==="ref"){o.push(Er(a,s.$as));continue}let l=n[a.opposite.thing],d=Ei({fields:s.$fields,thing:l,schema:n,metadata:i}),c="$filter"in s&&s.$filter?lt(s.$filter,l,n):void 0;o.push({type:"nested_reference",path:s.$path,projection:d,cardinality:typeof s.$id=="string"||Br(l,c)?"ONE":a.cardinality,alias:s.$as,ids:typeof s.$id=="string"?[s.$id]:s.$id,filter:c,limit:Ti(s.$limit),offset:Si(s.$offset),sort:wi(d,Fi(s.$sort))});}return {fields:o}},Er=(e,t)=>e.type==="data"?{type:"data",path:e.name,alias:t}:e.type==="ref"&&e.contentType==="FLEX"?{type:"flex",path:e.name,cardinality:e.cardinality,alias:t}:{type:"reference",path:e.name,cardinality:e.cardinality,alias:t},lt=(e,t,r)=>Array.isArray(e)?{type:"or",filters:e.map(o=>lt(o,t,r)).filter(o=>!!o)}:{type:"and",filters:ka(e,t,r)},ka=(e,t,r)=>Object.entries(e).map(([n,i])=>{if(n==="$not"&&e.$not)return Ca(e.$not,t,r);if(n==="$or"&&e.$or)return Pa(e.$or,t,r);let o=t.fields[n];if(!o)throw new Error(`Field ${n} not found in ${t.name}`);if(o.type==="constant"||o.type==="computed")throw new Error(`Filtering on constant or computed field ${n} is not supported`);if(i!==void 0)return o.type==="data"?qa(o,i):o.type==="ref"?xa(o,i):Bi(o,i,r)}).filter(n=>n!==void 0),Ca=(e,t,r)=>{let n=lt(e,t,r);return n?{type:"not",filter:n}:void 0},Pa=(e,t,r)=>lt(e,t,r),qa=(e,t)=>{let r=$i.safeParse(t);if(r.success){let n=[];for(let[i,o]of Object.entries(r.data)){if(i==="$exists"){n.push({type:"null",op:o?"IS NOT":"IS",left:e.name,tunnel:false});continue}if((i==="$eq"||i==="$ne")&&o===null){n.push({type:"null",op:i==="$eq"?"IS":"IS NOT",left:e.name,tunnel:false});continue}let s=ja[i];if(s){n.push({type:"scalar",op:s,left:e.name,right:o});continue}let a=bi[i];if(a){n.push({type:"list",op:a,left:e.name,right:o});continue}throw new Error(`Invalid filter operation: ${i}`)}return {type:"and",filters:n}}return Array.isArray(t)?e.cardinality==="ONE"?{type:"list",op:"IN",left:e.name,right:t}:{type:"list",op:"CONTAINSANY",left:e.name,right:t}:e.cardinality==="ONE"?t===null?{type:"null",op:"IS",left:e.name,tunnel:false}:{type:"scalar",op:"=",left:e.name,right:t}:{type:"scalar",op:"CONTAINS",left:e.name,right:t}},xa=(e,t)=>{if(e.contentType==="REF"){if(e.cardinality==="ONE"){if(typeof t=="string")return {type:"ref",op:"IN",left:e.name,right:[t],tunnel:false};if(kt.safeParse(t).success)return {type:"ref",op:"IN",left:e.name,right:t,tunnel:false};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}if(typeof t=="string")return {type:"ref",op:"CONTAINSANY",left:e.name,right:[t],tunnel:false};if(kt.safeParse(t).success)return {type:"ref",op:"CONTAINSANY",left:e.name,right:t,tunnel:false};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}throw new Error("Filtering by FLEX reference is not supported")},Bi=(e,t,r)=>{let n=e.type==="link"&&e.target==="role";if(t===null)return {type:"null",op:"IS",left:e.name,tunnel:n};if(typeof t=="string")return {type:"ref",op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:[t],tunnel:n};if(kt.safeParse(t).success)return {type:"ref",op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:t,tunnel:n};let i=It.union([Ke,It.array(Ke)]).safeParse(t);if(i.error)throw new Error(`Invalid nested filter: ${i.error.message}`);let o=r[e.opposite.thing];if(!o)throw new Error(`Opposite thing ${e.opposite.thing} not found`);let s=[e.opposite.thing,...o.subTypes];if(Array.isArray(i.data))return {type:"or",filters:i.data.map(T=>Bi(e,T,r))};let{$eq:a,$ne:l,$contains:d,$containsNot:c,$in:u,$nin:p,$containsAll:f,$containsAny:h,$containsNone:$,...E}=i.data;for(let g of ["$gt","$lt","$gte","$lte"])if(E[g])throw new Error(`Filtering ${e.type} field with ${g} operator is not supported`);let m=[];for(let g of ["$exists","$eq","$ne","$contains","$containsNot"]){let T=i.data[g];if(T!==void 0){if(g==="$exists"){m.push({type:"null",op:T?"IS NOT":"IS",left:e.name,tunnel:n});continue}if((g==="$eq"||g==="$ne")&&T===null){m.push({type:"null",op:g==="$eq"?"IS":"IS NOT",left:e.name,tunnel:n});continue}if(typeof T!="string")throw new Error(`Filter value for ${e.type} field with operator ${g} must be a string`);m.push({type:"ref",op:g==="$eq"||g==="$contains"?"IN":"NOT IN",left:e.name,right:[T],thing:s,tunnel:n});}}for(let g of ["$in","$nin","$containsAll","$containsAny","$containsNone"]){let T=i.data[g];if(T===void 0)continue;let w=kt.safeParse(T);if(!w.success)throw new Error(`Filter value for ${e.type} field with operator ${g} must be a string array`);let Q=bi[g];if(!Q)throw new Error(`Invalid list operator: ${g}`);m.push({type:"ref",op:Q,left:e.name,right:w.data,thing:s,tunnel:n});}let y=r[e.opposite.thing];if(!y)throw new Error(`Unknown thing: ${e.opposite.thing}`);let B=lt(E,y,r);return B&&m.push({type:"nested",path:e.name,filter:B,cardinality:e.cardinality}),{type:"and",filters:m}},Br=(e,t)=>{if(!t)return false;if(t.type==="scalar"){if(t.op!=="=")return false;let r=e.fields[t.left];if(!r)throw new Error(`Field ${t.left} not found in ${e.name}`);return r.type==="data"&&r.unique}if(t.type==="list"){if(t.op!=="IN"||t.right.length>1)return false;let r=e.fields[t.left];if(!r)throw new Error(`Field ${t.left} not found in ${e.name}`);return r.type==="data"&&r.unique}return t.type==="and"?t.filters.some(r=>Br(e,r)):false},Fi=e=>{if(!(!e||e.length===0))return e.map(t=>typeof t=="string"?{field:t,desc:false}:{field:t.field,desc:t.desc??false})},ja={$eq:"=",$ne:"!=",$gt:">",$lt:"<",$gte:">=",$lte:"<=",$contains:"CONTAINS",$containsNot:"CONTAINSNOT"},bi={$in:"IN",$nin:"NOT IN",$containsAll:"CONTAINSALL",$containsAny:"CONTAINSANY",$containsNone:"CONTAINSNONE"},kt=It.array(It.string()),Ti=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid limit: ${e}`);return e},Si=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid offset: ${e}`);return e},wi=(e,t)=>{if(!t||t.length===0)return;let r=new Set(e.fields.map(n=>n.type==="metadata"?n.path:n.alias??n.path));for(let n of t)if(!r.has(n.field))throw new Error(`Missing sorter field in the selected fields: ${n.field}`);return t};var Ri=(e,t)=>{let r=[],n=e.cardinality==="MANY"?0:1;e.cardinality==="ONE"&&r.push("array::first("),r.push(Li(e.projection,n,t)),r.push(Mi(e.source,n,t));let i=e.filter&&Ve(e.filter,t);return i&&r.push(X(`WHERE ${i}`,n)),e.sort&&e.sort.length>0&&r.push(Qi(e.sort,n)),e.limit!==void 0&&r.push(X(`LIMIT ${e.limit}`,n)),e.offset!==void 0&&r.push(X(`START ${e.offset}`,n)),e.cardinality==="ONE"&&r.push(")"),r.join(`
105
- `)},Li=(e,t,r)=>{let n=[],i=t+1;for(let s of e.fields)s.type==="metadata"?n.push(_a(s,i)):s.type==="data"?n.push(za(s,i)):s.type==="reference"?n.push(Va(s,i)):s.type==="nested_reference"?n.push(Ua(s,i,r)):s.type==="flex"&&n.push(Wa(s,i));let o=[];return o.push(X("SELECT",t)),o.push(n.join(`,
104
+ `;return n.query?.debugger&&Z(`batchedQuery[${G}]`,JSON.stringify({batchedQuery:i})),await t.query(i)};var Qa=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,fi=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,st=x("error","error",q((e,t)=>({...e,error:t.error}))),Da=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),rt(e.bql.raw,e.schema)),x("done","build",q(Qa)),st),build:U(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return oi({queries:e.bql.queries??[],schema:e.schema});if(t==="refs")return si({queries:e.bql.queries??[],schema:e.schema})},x("done","run",q((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),st),run:U(async e=>hi({client:e.client,queries:Ee(e.surql.queries),config:e.config}),x("done","parse",q((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),st),parse:U(async e=>ui({res:Ee(e.surql.res),queries:e.bql.queries??[],schema:e.schema,config:e.config}),x("done","postHooks",q((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),st),postHooks:U(async e=>kt(e.schema,Ee(e.bql.queries),Ee(e.bql.res)),x("done","clean",q(fi)),st),clean:U(async e=>It(e.config,Ee(e.bql.res)),x("done","success",q(fi)),st),success:me(),error:me()},e=>e),Aa=async e=>new Promise((t,r)=>{Re(Da,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),$i=async(e,t,r,n)=>Aa({bql:{raw:e},surql:{},schema:t,config:r,client:n,error:null});var fe=z.json(),Me=z.array(fe),mi=z.strictObject({$exists:z.boolean().optional(),$eq:fe.optional(),$neq:fe.optional(),$gt:fe.optional(),$lt:fe.optional(),$gte:fe.optional(),$lte:fe.optional(),$contains:fe.optional(),$containsNot:fe.optional(),$in:Me.optional(),$nin:Me.optional(),$containsAll:Me.optional(),$containsAny:Me.optional(),$containsNone:Me.optional()}),at=z.lazy(()=>z.object({$or:z.array(z.lazy(()=>at)).optional(),$not:z.lazy(()=>at).optional()}).catchall(z.union([fe,Me,z.lazy(()=>z.union([Ye,z.array(Ye)]))]))),Ye=z.lazy(()=>z.object({$or:z.array(z.lazy(()=>at)).optional(),$not:z.lazy(()=>at).optional(),$exists:z.boolean().optional(),$eq:fe.optional(),$neq:fe.optional(),$gt:fe.optional(),$lt:fe.optional(),$gte:fe.optional(),$lte:fe.optional(),$contains:fe.optional(),$containsNot:fe.optional(),$in:Me.optional(),$nin:Me.optional(),$containsAll:Me.optional(),$containsAny:Me.optional(),$containsNone:Me.optional()}).catchall(z.union([fe,Me,z.lazy(()=>z.union([Ye,z.array(Ye)]))]))),yi=z.object({$id:z.union([z.string(),z.array(z.string())]).optional(),$filter:z.union([at,z.array(at)]).optional(),$fields:z.array(z.union([z.string(),z.lazy(()=>Oa)])).optional(),$excludedFields:z.array(z.string()).optional(),$limit:z.number().optional(),$offset:z.number().optional(),$sort:z.array(z.union([z.object({field:z.string(),desc:z.boolean().optional()}),z.string()])).optional()}),Oa=yi.extend({$path:z.string(),$as:z.string().optional()}),gi=yi.extend({$thing:z.string().optional(),$entity:z.string().optional(),$relation:z.string().optional()}).superRefine((e,t)=>{!e.$thing&&!e.$entity&&!e.$relation&&t.addIssue({code:"custom",message:"Query must contain at least one of: $thing, $entity, or $relation",path:["$thing"]});}).transform(e=>{let{$thing:t,$entity:r,$relation:n,...i}=e;return {...i,$thing:t??r??n}});var Ei=(e,t,r)=>{let n=t[e.$thing],i=Bi({fields:e.$fields,thing:n,schema:t,metadata:r}),o=e.$filter?lt(e.$filter,n,t):void 0,s=Array.isArray(e.$id)?e.$id:e.$id?[e.$id]:[],a=s.length===1||Er(n,o)?"ONE":"MANY";return {source:s.length>0?{type:"record_pointer",thing:[n.name,...n.subTypes],ids:s}:{type:"table_scan",thing:[n.name,...n.subTypes]},projection:i,filter:o,limit:Si(e.$limit),offset:wi(e.$offset),sort:Ri(i,bi(e.$sort)),cardinality:a}},Bi=e=>{let{fields:t,thing:r,schema:n,metadata:i}=e,o=[];if(i&&(o.push({type:"metadata",path:"$id"}),o.push({type:"metadata",path:"$thing"})),!t){for(let s of Object.values(r.fields))o.push(gr(s));return {fields:o}}for(let s of t){if(typeof s=="string"){if(s==="$id"||s==="$thing"){o.push({type:"metadata",path:s});continue}let u=r.fields[s];if(!u)throw new Error(`Field ${s} not found in ${r.name}`);o.push(gr(u));continue}if(s.$path==="$id"||s.$path==="$thing"){o.push({type:"metadata",path:s.$path,alias:s.$as});continue}let a=r.fields[s.$path];if(!a)throw new Error(`Field ${s} not found in ${r.name}`);if(a.type==="constant"||a.type==="computed")continue;if(a.type==="data"||a.type==="ref"){o.push(gr(a,s.$as));continue}let l=n[a.opposite.thing],d=Bi({fields:s.$fields,thing:l,schema:n,metadata:i}),c="$filter"in s&&s.$filter?lt(s.$filter,l,n):void 0;o.push({type:"nested_reference",path:s.$path,projection:d,cardinality:typeof s.$id=="string"||Er(l,c)?"ONE":a.cardinality,alias:s.$as,ids:typeof s.$id=="string"?[s.$id]:s.$id,filter:c,limit:Si(s.$limit),offset:wi(s.$offset),sort:Ri(d,bi(s.$sort))});}return {fields:o}},gr=(e,t)=>e.type==="data"?{type:"data",path:e.name,alias:t}:e.type==="ref"&&e.contentType==="FLEX"?{type:"flex",path:e.name,cardinality:e.cardinality,alias:t}:{type:"reference",path:e.name,cardinality:e.cardinality,alias:t},lt=(e,t,r)=>Array.isArray(e)?{type:"or",filters:e.map(o=>lt(o,t,r)).filter(o=>!!o)}:{type:"and",filters:Na(e,t,r)},Na=(e,t,r)=>Object.entries(e).map(([n,i])=>{if(n==="$not"&&e.$not)return Ia(e.$not,t,r);if(n==="$or"&&e.$or)return ka(e.$or,t,r);let o=t.fields[n];if(!o)throw new Error(`Field ${n} not found in ${t.name}`);if(o.type==="constant"||o.type==="computed")throw new Error(`Filtering on constant or computed field ${n} is not supported`);if(i!==void 0)return o.type==="data"?Ca(o,i):o.type==="ref"?Pa(o,i):Fi(o,i,r)}).filter(n=>n!==void 0),Ia=(e,t,r)=>{let n=lt(e,t,r);return n?{type:"not",filter:n}:void 0},ka=(e,t,r)=>lt(e,t,r),Ca=(e,t)=>{let r=mi.safeParse(t);if(r.success){let n=[];for(let[i,o]of Object.entries(r.data)){if(i==="$exists"){n.push({type:"null",op:o?"IS NOT":"IS",left:e.name,tunnel:false});continue}if((i==="$eq"||i==="$ne")&&o===null){n.push({type:"null",op:i==="$eq"?"IS":"IS NOT",left:e.name,tunnel:false});continue}let s=qa[i];if(s){n.push({type:"scalar",op:s,left:e.name,right:o});continue}let a=Ti[i];if(a){n.push({type:"list",op:a,left:e.name,right:o});continue}throw new Error(`Invalid filter operation: ${i}`)}return {type:"and",filters:n}}return Array.isArray(t)?e.cardinality==="ONE"?{type:"list",op:"IN",left:e.name,right:t}:{type:"list",op:"CONTAINSANY",left:e.name,right:t}:e.cardinality==="ONE"?t===null?{type:"null",op:"IS",left:e.name,tunnel:false}:{type:"scalar",op:"=",left:e.name,right:t}:{type:"scalar",op:"CONTAINS",left:e.name,right:t}},Pa=(e,t)=>{if(e.contentType==="REF"){if(e.cardinality==="ONE"){if(typeof t=="string")return {type:"ref",op:"IN",left:e.name,right:[t],tunnel:false};if(Pt.safeParse(t).success)return {type:"ref",op:"IN",left:e.name,right:t,tunnel:false};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}if(typeof t=="string")return {type:"ref",op:"CONTAINSANY",left:e.name,right:[t],tunnel:false};if(Pt.safeParse(t).success)return {type:"ref",op:"CONTAINSANY",left:e.name,right:t,tunnel:false};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}throw new Error("Filtering by FLEX reference is not supported")},Fi=(e,t,r)=>{let n=e.type==="link"&&e.target==="role";if(t===null)return {type:"null",op:"IS",left:e.name,tunnel:n};if(typeof t=="string")return {type:"ref",op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:[t],tunnel:n};if(Pt.safeParse(t).success)return {type:"ref",op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:t,tunnel:n};let i=Ct.union([Ye,Ct.array(Ye)]).safeParse(t);if(i.error)throw new Error(`Invalid nested filter: ${i.error.message}`);let o=r[e.opposite.thing];if(!o)throw new Error(`Opposite thing ${e.opposite.thing} not found`);let s=[e.opposite.thing,...o.subTypes];if(Array.isArray(i.data))return {type:"or",filters:i.data.map(T=>Fi(e,T,r))};let{$eq:a,$ne:l,$contains:d,$containsNot:c,$in:u,$nin:p,$containsAll:f,$containsAny:h,$containsNone:$,...E}=i.data;for(let g of ["$gt","$lt","$gte","$lte"])if(E[g])throw new Error(`Filtering ${e.type} field with ${g} operator is not supported`);let y=[];for(let g of ["$exists","$eq","$ne","$contains","$containsNot"]){let T=i.data[g];if(T!==void 0){if(g==="$exists"){y.push({type:"null",op:T?"IS NOT":"IS",left:e.name,tunnel:n});continue}if((g==="$eq"||g==="$ne")&&T===null){y.push({type:"null",op:g==="$eq"?"IS":"IS NOT",left:e.name,tunnel:n});continue}if(typeof T!="string")throw new Error(`Filter value for ${e.type} field with operator ${g} must be a string`);y.push({type:"ref",op:g==="$eq"||g==="$contains"?"IN":"NOT IN",left:e.name,right:[T],thing:s,tunnel:n});}}for(let g of ["$in","$nin","$containsAll","$containsAny","$containsNone"]){let T=i.data[g];if(T===void 0)continue;let w=Pt.safeParse(T);if(!w.success)throw new Error(`Filter value for ${e.type} field with operator ${g} must be a string array`);let M=Ti[g];if(!M)throw new Error(`Invalid list operator: ${g}`);y.push({type:"ref",op:M,left:e.name,right:w.data,thing:s,tunnel:n});}let m=r[e.opposite.thing];if(!m)throw new Error(`Unknown thing: ${e.opposite.thing}`);let B=lt(E,m,r);return B&&y.push({type:"nested",path:e.name,filter:B,cardinality:e.cardinality}),{type:"and",filters:y}},Er=(e,t)=>{if(!t)return false;if(t.type==="scalar"){if(t.op!=="=")return false;let r=e.fields[t.left];if(!r)throw new Error(`Field ${t.left} not found in ${e.name}`);return r.type==="data"&&r.unique}if(t.type==="list"){if(t.op!=="IN"||t.right.length>1)return false;let r=e.fields[t.left];if(!r)throw new Error(`Field ${t.left} not found in ${e.name}`);return r.type==="data"&&r.unique}return t.type==="and"?t.filters.some(r=>Er(e,r)):false},bi=e=>{if(!(!e||e.length===0))return e.map(t=>typeof t=="string"?{field:t,desc:false}:{field:t.field,desc:t.desc??false})},qa={$eq:"=",$ne:"!=",$gt:">",$lt:"<",$gte:">=",$lte:"<=",$contains:"CONTAINS",$containsNot:"CONTAINSNOT"},Ti={$in:"IN",$nin:"NOT IN",$containsAll:"CONTAINSALL",$containsAny:"CONTAINSANY",$containsNone:"CONTAINSNONE"},Pt=Ct.array(Ct.string()),Si=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid limit: ${e}`);return e},wi=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid offset: ${e}`);return e},Ri=(e,t)=>{if(!t||t.length===0)return;let r=new Set(e.fields.map(n=>n.type==="metadata"?n.path:n.alias??n.path));for(let n of t)if(!r.has(n.field))throw new Error(`Missing sorter field in the selected fields: ${n.field}`);return t};var Li=(e,t)=>{let r=[],n=e.cardinality==="MANY"?0:1;e.cardinality==="ONE"&&r.push("array::first("),r.push(Mi(e.projection,n,t)),r.push(Qi(e.source,n,t));let i=e.filter&&ze(e.filter,t);return i&&r.push(X(`WHERE ${i}`,n)),e.sort&&e.sort.length>0&&r.push(Di(e.sort,n)),e.limit!==void 0&&r.push(X(`LIMIT ${e.limit}`,n)),e.offset!==void 0&&r.push(X(`START ${e.offset}`,n)),e.cardinality==="ONE"&&r.push(")"),r.join(`
105
+ `)},Mi=(e,t,r)=>{let n=[],i=t+1;for(let s of e.fields)s.type==="metadata"?n.push(xa(s,i)):s.type==="data"?n.push(ja(s,i)):s.type==="reference"?n.push(_a(s,i)):s.type==="nested_reference"?n.push(Va(s,i,r)):s.type==="flex"&&n.push(za(s,i));let o=[];return o.push(X("SELECT",t)),o.push(n.join(`,
106
106
  `)),o.join(`
107
- `)},_a=(e,t)=>{if(e.path==="$id")return X(`record::id(id) AS ${te(e.alias??"$id")}`,t);if(e.path==="$thing")return X(`record::tb(id) AS ${te(e.alias??"$thing")}`,t);throw new Error(`Unsupported metadata field: ${e.path}`)},za=(e,t)=>{if(e.path==="id")return X(`record::id(id) AS ${te(e.alias??"id")}`,t);let r=te(e.path);return e.alias?X(`${r} AS ${te(e.alias)}`,t):X(r,t)},Va=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=te(r),s=te(n||r);return X(i==="ONE"?`array::first(SELECT VALUE record::id(id) FROM $this.${o}[*]) AS ${s}`:`(SELECT VALUE record::id(id) FROM $this.${o}[*]) AS ${s}`,t)},Ua=(e,t,r)=>{let n=[];e.cardinality==="MANY"?n.push(X("(",t)):n.push(X("array::first(",t)),n.push(Li(e.projection,t+1,r));let i=e.filter?Ve(e.filter,r):void 0;n.push(X(`FROM $this.${te(e.path)}[*]`,t+1));let o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(a=>`$${Te(r,a)}`);s.length===1?o.push(`record::id(id) = ${s[0]}`):o.push(`record::id(id) IN [${s.join(", ")}]`);}return i&&o.push(i),o.length>0&&n.push(X(`WHERE ${o.join(" AND ")}`,t+1)),e.sort&&e.sort.length>0&&n.push(Qi(e.sort,t+1)),e.limit!==void 0&&n.push(X(`LIMIT ${e.limit}`,t+1)),e.offset!==void 0&&n.push(X(`START ${e.offset}`,t+1)),n.push(X(`) AS ${te(e.alias||e.path)}`,t)),n.join(`
108
- `)},Wa=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=te(r),s=te(n||r);return X(i==="ONE"?`(IF ${o} THEN IF type::is::record(${o}) { record::id(${o}) } ELSE { ${o} } END) AS ${s}`:`(IF ${o} THEN ${o}.map(|$i| IF type::is::record($i) { record::id($i)} ELSE { $i }) END) AS ${s}`,t)},Mi=(e,t,r)=>{let n=[];switch(e.type){case "table_scan":{n.push(X(`FROM ${e.thing.map(te)}`,t));break}case "record_pointer":{let i=e.thing.flatMap(o=>e.ids.map(s=>`${te(o)}:${te(s)}`)).map(o=>`type::record($${Te(r,o)})`).join(", ");n.push(X(`FROM ${i}`,t));break}case "subquery":{n.push(X(e.cardinality==="MANY"?"FROM array::distinct(array::flatten(":"FROM (",t)),e.oppositePath,n.push(X(`SELECT VALUE ${te(e.oppositePath)}`,t+1)),n.push(Mi(e.source,t+1,r));let i=e.filter?Ve(e.filter,r):void 0;i&&n.push(X(`WHERE ${i}`,t+1)),n.push(X(e.cardinality==="MANY"?"))":")",t));break}}return n.join(`
109
- `)},Ve=(e,t,r)=>{let n=r??"";switch(e.type){case "scalar":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${te(e.left)}`,o=Te(t,e.right);return `${i} ${e.op} $${o}`}case "list":{let i=e.right.map(s=>`$${Te(t,s)}`).join(", ");return `${`${n}${te(e.left)}`} ${e.op} [${i}]`}case "ref":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${te(e.left)}`;if(e.thing){let o=e.thing.flatMap(s=>e.right.map(a=>{let l=`${te(s)}:${te(a)}`;return `type::record($${Te(t,l)})`}));if(o.length===1){let s=o[0];if(e.op==="IN")return `${i} = ${s}`;if(e.op==="NOT IN")return `${i} != ${s}`;if(e.op==="CONTAINSANY")return `${s} IN ${i}`;if(e.op==="CONTAINSNONE")return `${s} NOT IN ${i}`}return `${i} ${e.op} [${o.join(", ")}]`}if(e.right.length===1){if(e.op==="IN")return e.tunnel?`(array::first(${i}) && record::id(array::first(${i})) = $${Te(t,e.right[0])})`:`${i} && record::id(${i}) = $${Te(t,e.right[0])}`;if(e.op==="NOT IN")return e.tunnel?`(!array::first(${i}) || record::id(array::first(${i})) != $${Te(t,e.right[0])})`:`${i} && record::id(${i}) != $${Te(t,e.right[0])}`;if(e.op==="CONTAINSANY")return e.tunnel?`$${Te(t,e.right[0])} IN ${i}.map(|$i| record::id($i))`:`$${Te(t,e.right[0])} IN (${i} ?: []).map(|$i| record::id($i))`;if(e.op==="CONTAINSNONE")return e.tunnel?`$${Te(t,e.right[0])} NOT IN ${i}.map(|$i| record::id($i))`:`$${Te(t,e.right[0])} NOT IN (${i} ?: []).map(|$i| record::id($i))`}return e.tunnel?`${i}.map(|$i| record::id($i)) ${e.op} [${e.right.map(o=>`$${Te(t,o)}`).join(", ")}]`:`(${i} ?: []).map(|$i| record::id($i)) ${e.op} [${e.right.map(o=>`$${Te(t,o)}`).join(", ")}]`}case "null":return e.tunnel?`array::len(${n}${te(e.left)}) = 0`:`${n}${te(e.left)} ${e.op} NONE`;case "and":{let i=e.filters.map(o=>{let s=Ve(o,t,r);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" AND "):void 0}case "or":{let i=e.filters.map(o=>{let s=Ve(o,t,r);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" OR "):void 0}case "not":{let i=Ve(e.filter,t,r);return i?`NOT(${i})`:void 0}case "nested":{let i=`${n}${te(e.path)}`;if(e.cardinality==="ONE")return Ve(e.filter,t,`${i}.`);let o=Ve(e.filter,t);return o?`${i}[WHERE ${o}]`:void 0}}},Qi=(e,t)=>{let r=e.map(n=>`${te(n.field)} ${n.desc?"DESC":"ASC"}`).join(", ");return X(`ORDER BY ${r}`,t)},X=(e,t)=>`${" ".repeat(t*2)}${e}`,Te=(e,t)=>{let r=sr();for(;e[r]!==void 0;)r=sr();return e[r]=t,r},te=e=>{let t=e.replace(/⟩/g,"\\\u27E9");return /^[^a-zA-Z]/.test(t)||/[^a-zA-Z0-9_]/.test(t)?`\u27E8${e}\u27E9`:e};var Oi=(e,t)=>{let r=Ci(e.source,t),n=e.filter?mt(e.filter):void 0,{source:i,filter:o}=Ni({source:e.source,filter:n,schema:t,thing:r});return {source:i,projection:ki(e.projection,t,r),filter:o,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Ni=e=>{let{source:t,filter:r,schema:n,thing:i}=e;if(t.type!=="table_scan")return {source:t,filter:r};let o=r?.type==="and"?r.filters:r?[r]:[];for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="scalar"&&a?.type!=="list")continue;let l=va(a,t);if(l)return {source:l,filter:Fr(o.filter((d,c)=>c!==s))}}for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="ref")continue;let l=Ha(a,n,i);if(l)return {source:l,filter:Fr(o.filter((d,c)=>c!==s))}}for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="nested")continue;let l=Ja(a,n,i);if(l)return {source:l,filter:Fr(o.filter((d,c)=>c!==s))}}return {source:t,filter:r?Ya(r,i):void 0}},va=(e,t)=>{if(e.left==="id"){if(e.op==="="&&typeof e.right=="string")return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:[e.right]};if(e.op==="IN"&&It.array(It.string()).safeParse(e.right).success)return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:e.right}}},Ha=(e,t,r)=>{let n=r.fields[e.left];if(!n)throw new Error(`Field ${e.left} not found in ${r.name}`);let i=Ii(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=br(o,t);return {type:"subquery",source:{type:"record_pointer",thing:[o,...l.subTypes],ids:e.right},oppositePath:s,cardinality:a}},Ja=(e,t,r)=>{let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);let i=Ii(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=br(o,t),d={type:"table_scan",thing:[o,...l.subTypes]},c=Ni({source:d,filter:e.filter,schema:t,thing:l});return {type:"subquery",source:c.source,oppositePath:s,cardinality:a,filter:c.filter}},Ii=(e,t,r)=>{if(!(e.type!=="link"&&e.type!=="role")){if(e.type==="role"){let n=t[e.opposite.thing]?.fields?.[e.opposite.path];if(n?.type!=="link")throw new Error(`Role field ${e.name} in relation ${r.name} is not played by a link field`);if(n.target!=="relation")return}return e.opposite}},ki=(e,t,r)=>({fields:e.fields.map(n=>Ka(n,t,r))}),Ka=(e,t,r)=>{if(e.type==="metadata"||e.type==="data"||e.type==="flex"||e.type==="reference")return e;let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);if(n.type!=="link"&&n.type!=="role")throw new Error(`Field ${e.path} is not a link or role field and can't be projected as nested reference`);let i=t[n.opposite.thing];if(!i)throw new Error(`Thing ${n.opposite.thing} not found in schema`);return {type:"nested_reference",path:e.path,projection:ki(e.projection,t,i),ids:e.ids,filter:e.filter?mt(e.filter):void 0,alias:e.alias,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},mt=e=>{if(e.type==="list"){if(e.right.length===0)return e.op==="IN"||e.op==="CONTAINSANY"?{type:"falsy"}:void 0;if(e.right.length===1)switch(e.op){case "IN":return {type:"scalar",op:"=",left:e.left,right:e.right[0]};case "NOT IN":return {type:"scalar",op:"!=",left:e.left,right:e.right[0]};case "CONTAINSALL":case "CONTAINSANY":return {type:"scalar",op:"CONTAINS",left:e.left,right:e.right[0]};case "CONTAINSNONE":return {type:"scalar",op:"CONTAINSNOT",left:e.left,right:e.right[0]}}}if(e.type==="ref"&&e.right.length===0)return e.op==="IN"||e.op==="CONTAINSALL"||e.op==="CONTAINSANY"?{type:"falsy"}:void 0;if(e.type==="and"||e.type==="or"){let t=e.filters.flatMap(i=>{let o=mt(i);return o===void 0?[]:o.type===e.type?o.filters:[o]});if(e.type==="and"&&t.some(i=>i.type==="falsy"))return {type:"falsy"};if(e.type==="or"&&(t=t.filter(i=>i.type!=="falsy")),t.length===0)return;if(t.length===1)return t[0];let n=t.map(i=>{if(i.type==="scalar")return {filter:i,score:Ct[i.op]??0};if(i.type==="list"){let o=Ct[i.op]??0;return {filter:i,score:o**i.right.length}}if(i.type==="ref"){let o=Ct[i.op]??0;return i.thing?{filter:i,score:o**(i.right.length*i.thing.length)}:{filter:i,score:o**i.right.length*.9}}return {filter:i,score:0}}).sort((i,o)=>o.score-i.score);return {type:e.type,filters:n.map(i=>i.filter)}}if(e.type==="not"){let t=mt(e.filter);if(t===void 0)return;if(t.type==="not")return t.filter;if(t.type==="scalar"){if(t.op==="=")return {type:"scalar",op:"!=",left:t.left,right:t.right};if(t.op==="!=")return {type:"scalar",op:"=",left:t.left,right:t.right}}return {type:"not",filter:t}}if(e.type==="nested"){let t=mt(e.filter);return t?{type:"nested",filter:t,path:e.path,cardinality:e.cardinality}:void 0}return e},Ct={"=":.9,">":.5,"<":.5,">=":.5,"<=":.5,IN:.5,"NOT IN":.5,CONTAINSALL:.3,CONTAINSANY:.4,CONTAINSNONE:.3},Ya=(e,t)=>{if(e.type==="and"){let r=Object.fromEntries(e.filters.map((i,o)=>{if(i.type!=="scalar")return;let s=Ct[i.op];if(s)return [i.left,{filter:i,index:o,score:s}]}).filter(i=>i!==void 0)),n=t.indexes.filter(i=>i.type!=="single").sort((i,o)=>o.fields.length-i.fields.length);if(n.length>0){let i=[];for(let s of n){let a=[];for(let l of s.fields){let d=r[l];if(!d||a.some(c=>c.index===d.index))break;a.push(d);}a.length>0&&i.push({filters:a,score:a.reduce((l,d)=>l+l*d.score,1)});}i.sort((s,a)=>a.score-s.score);let[o]=i;if(o&&o.score>1)return {type:"and",filters:[...o.filters.map(s=>s.filter),...e.filters.filter((s,a)=>!o.filters.some(l=>l.index===a))]}}}if(e.type==="and"||e.type==="or"){let n=e.filters.map((a,l)=>{if(a.type==="scalar"&&a.op==="="){let d=t.fields[a.left];if(Ai(d,t.indexes))return {filter:a,score:1,index:l}}else if(a.type==="list"&&a.op==="IN"){let d=t.fields[a.left];if(Ai(d,t.indexes)){let c=.5**(a.right.length-1);return {filter:a,score:c,index:l}}}return {filter:a,score:0,index:l}}).sort((a,l)=>l.score-a.score),[i]=n,o=i&&i.score!==0?i.filter:void 0,s=o?.type==="list"&&o.op==="IN"?{type:"or",filters:o.right.map(a=>({type:"scalar",op:"=",left:o.left,right:a}))}:o;return {type:e.type,filters:s?[s,...e.filters.filter((a,l)=>l!==i.index)]:e.filters}}return e},Fr=e=>{if(e.length!==0)return e.length===1?e[0]:{type:"and",filters:e}},Ai=(e,t)=>e.type==="role"||e.type==="link"||t.some(r=>r.type==="single"&&r.field===e.name||r.type==="composite"&&r.fields.includes(e.name)),br=(e,t)=>{let r=t[e];if(!r)throw new Error(`Thing ${e} not found in schema`);return r},Ci=(e,t)=>{if(e.type==="table_scan"||e.type==="record_pointer")return br(e.thing[0],t);let r=Ci(e.source,t),n=r.fields[e.oppositePath];if(!n)throw new Error(`Field ${e.oppositePath} not found in ${r.name}`);if(n.type==="constant"||n.type==="computed"||n.type==="data"||n.type==="ref")throw new Error(`Invalid source: ${JSON.stringify(e)}`);let i=t[n.opposite.thing];if(!i)throw new Error(`Thing ${n.opposite.thing} not found in schema`);return i};var Xa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Pi=e=>e==null,qi=e=>Array.isArray(e)&&e.length===0,xi=e=>{let{batch:t,results:r,schema:n,metadata:i,returnNulls:o}=e;return t.map((s,a)=>Za({query:s,result:r[a],schema:n,metadata:i,returnNulls:o}))},Za=e=>{let{query:t,result:r,schema:n,metadata:i,returnNulls:o}=e;if(!r)return r??null;let s=n[t.$thing];if(!s)throw new Error(`Thing ${t.$thing} not found in schema`);return Array.isArray(r)?o&&r.length===0?null:r.map(a=>Pt({query:t,result:a,thing:s,schema:n,metadata:i,returnNulls:o})):Pt({query:t,result:r,thing:s,schema:n,metadata:i,returnNulls:o})},Ga=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;return Array.isArray(r)?r.length===0?null:r.map(a=>Pt({query:t,result:a,thing:n,schema:i,metadata:o,returnNulls:s})):Pt({query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s})},Pt=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;if(!Xa(r))return null;let a={};o&&(a.$thing=r.$thing??null,a.$id=r.$id??null,a.$thingType=n.type);let l=t.$fields??Object.keys(n.fields);for(let d of l){let c=typeof d=="string"?d:d.$path,u=typeof d=="string"?d:d.$as??c;if(t.$excludedFields?.includes(c))continue;if(c==="$id"||c==="$thing"){a[u]=r[u]??null;continue}let p=n.fields[c];if(!p)throw new Error(`Field ${c} not found in ${n.name}`);if(p.type==="constant"){a[u]=p.value;continue}if(p.type==="computed"){a[u]=p.fn(r);continue}let f=r[u];if(p.type==="data"){if(!s&&Pi(f))continue;a[u]=f??null;continue}if(!s&&(Pi(f)||qi(f)))continue;if(typeof d=="string"||p.type==="ref"){a[u]=qi(f)?null:f??null;continue}let h=i[p.opposite.thing];a[u]=Ga({query:d,result:f,thing:h,schema:i,metadata:o,returnNulls:s});}return a};var ji=async e=>{let{client:t,queries:r,config:n,params:i}=e,o=`BEGIN TRANSACTION;
107
+ `)},xa=(e,t)=>{if(e.path==="$id")return X(`record::id(id) AS ${te(e.alias??"$id")}`,t);if(e.path==="$thing")return X(`record::tb(id) AS ${te(e.alias??"$thing")}`,t);throw new Error(`Unsupported metadata field: ${e.path}`)},ja=(e,t)=>{if(e.path==="id")return X(`record::id(id) AS ${te(e.alias??"id")}`,t);let r=te(e.path);return e.alias?X(`${r} AS ${te(e.alias)}`,t):X(r,t)},_a=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=te(r),s=te(n||r);return X(i==="ONE"?`array::first(SELECT VALUE record::id(id) FROM $this.${o}[*]) AS ${s}`:`(SELECT VALUE record::id(id) FROM $this.${o}[*]) AS ${s}`,t)},Va=(e,t,r)=>{let n=[];e.cardinality==="MANY"?n.push(X("(",t)):n.push(X("array::first(",t)),n.push(Mi(e.projection,t+1,r));let i=e.filter?ze(e.filter,r):void 0;n.push(X(`FROM $this.${te(e.path)}[*]`,t+1));let o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(a=>`$${Te(r,a)}`);s.length===1?o.push(`record::id(id) = ${s[0]}`):o.push(`record::id(id) IN [${s.join(", ")}]`);}return i&&o.push(i),o.length>0&&n.push(X(`WHERE ${o.join(" AND ")}`,t+1)),e.sort&&e.sort.length>0&&n.push(Di(e.sort,t+1)),e.limit!==void 0&&n.push(X(`LIMIT ${e.limit}`,t+1)),e.offset!==void 0&&n.push(X(`START ${e.offset}`,t+1)),n.push(X(`) AS ${te(e.alias||e.path)}`,t)),n.join(`
108
+ `)},za=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=te(r),s=te(n||r);return X(i==="ONE"?`(IF ${o} THEN IF type::is::record(${o}) { record::id(${o}) } ELSE { ${o} } END) AS ${s}`:`(IF ${o} THEN ${o}.map(|$i| IF type::is::record($i) { record::id($i)} ELSE { $i }) END) AS ${s}`,t)},Qi=(e,t,r)=>{let n=[];switch(e.type){case "table_scan":{n.push(X(`FROM ${e.thing.map(te)}`,t));break}case "record_pointer":{let i=e.thing.flatMap(o=>e.ids.map(s=>`${te(o)}:${te(s)}`)).map(o=>`type::record($${Te(r,o)})`).join(", ");n.push(X(`FROM ${i}`,t));break}case "subquery":{n.push(X(e.cardinality==="MANY"?"FROM array::distinct(array::flatten(":"FROM (",t)),e.oppositePath,n.push(X(`SELECT VALUE ${te(e.oppositePath)}`,t+1)),n.push(Qi(e.source,t+1,r));let i=e.filter?ze(e.filter,r):void 0;i&&n.push(X(`WHERE ${i}`,t+1)),n.push(X(e.cardinality==="MANY"?"))":")",t));break}}return n.join(`
109
+ `)},ze=(e,t,r)=>{let n=r??"";switch(e.type){case "scalar":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${te(e.left)}`,o=Te(t,e.right);return `${i} ${e.op} $${o}`}case "list":{let i=e.right.map(s=>`$${Te(t,s)}`).join(", ");return `${`${n}${te(e.left)}`} ${e.op} [${i}]`}case "ref":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${te(e.left)}`;if(e.thing){let o=e.thing.flatMap(s=>e.right.map(a=>{let l=`${te(s)}:${te(a)}`;return `type::record($${Te(t,l)})`}));if(o.length===1){let s=o[0];if(e.op==="IN")return `${i} = ${s}`;if(e.op==="NOT IN")return `${i} != ${s}`;if(e.op==="CONTAINSANY")return `${s} IN ${i}`;if(e.op==="CONTAINSNONE")return `${s} NOT IN ${i}`}return `${i} ${e.op} [${o.join(", ")}]`}if(e.right.length===1){if(e.op==="IN")return e.tunnel?`(array::first(${i}) && record::id(array::first(${i})) = $${Te(t,e.right[0])})`:`${i} && record::id(${i}) = $${Te(t,e.right[0])}`;if(e.op==="NOT IN")return e.tunnel?`(!array::first(${i}) || record::id(array::first(${i})) != $${Te(t,e.right[0])})`:`${i} && record::id(${i}) != $${Te(t,e.right[0])}`;if(e.op==="CONTAINSANY")return e.tunnel?`$${Te(t,e.right[0])} IN ${i}.map(|$i| record::id($i))`:`$${Te(t,e.right[0])} IN (${i} ?: []).map(|$i| record::id($i))`;if(e.op==="CONTAINSNONE")return e.tunnel?`$${Te(t,e.right[0])} NOT IN ${i}.map(|$i| record::id($i))`:`$${Te(t,e.right[0])} NOT IN (${i} ?: []).map(|$i| record::id($i))`}return e.tunnel?`${i}.map(|$i| record::id($i)) ${e.op} [${e.right.map(o=>`$${Te(t,o)}`).join(", ")}]`:`(${i} ?: []).map(|$i| record::id($i)) ${e.op} [${e.right.map(o=>`$${Te(t,o)}`).join(", ")}]`}case "null":return e.tunnel?`array::len(${n}${te(e.left)}) = 0`:`${n}${te(e.left)} ${e.op} NONE`;case "and":{let i=e.filters.map(o=>{let s=ze(o,t,r);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" AND "):void 0}case "or":{let i=e.filters.map(o=>{let s=ze(o,t,r);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" OR "):void 0}case "not":{let i=ze(e.filter,t,r);return i?`NOT(${i})`:void 0}case "nested":{let i=`${n}${te(e.path)}`;if(e.cardinality==="ONE")return ze(e.filter,t,`${i}.`);let o=ze(e.filter,t);return o?`${i}[WHERE ${o}]`:void 0}}},Di=(e,t)=>{let r=e.map(n=>`${te(n.field)} ${n.desc?"DESC":"ASC"}`).join(", ");return X(`ORDER BY ${r}`,t)},X=(e,t)=>`${" ".repeat(t*2)}${e}`,Te=(e,t)=>{let r=sr();for(;e[r]!==void 0;)r=sr();return e[r]=t,r},te=e=>{let t=e.replace(/⟩/g,"\\\u27E9");return /^[^a-zA-Z]/.test(t)||/[^a-zA-Z0-9_]/.test(t)?`\u27E8${e}\u27E9`:e};var Ni=(e,t)=>{let r=Pi(e.source,t),n=e.filter?gt(e.filter):void 0,{source:i,filter:o}=Ii({source:e.source,filter:n,schema:t,thing:r});return {source:i,projection:Ci(e.projection,t,r),filter:o,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Ii=e=>{let{source:t,filter:r,schema:n,thing:i}=e;if(t.type!=="table_scan")return {source:t,filter:r};let o=r?.type==="and"?r.filters:r?[r]:[];for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="scalar"&&a?.type!=="list")continue;let l=Ua(a,t);if(l)return {source:l,filter:Br(o.filter((d,c)=>c!==s))}}for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="ref")continue;let l=Wa(a,n,i);if(l)return {source:l,filter:Br(o.filter((d,c)=>c!==s))}}for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="nested")continue;let l=va(a,n,i);if(l)return {source:l,filter:Br(o.filter((d,c)=>c!==s))}}return {source:t,filter:r?Ja(r,i):void 0}},Ua=(e,t)=>{if(e.left==="id"){if(e.op==="="&&typeof e.right=="string")return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:[e.right]};if(e.op==="IN"&&Ct.array(Ct.string()).safeParse(e.right).success)return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:e.right}}},Wa=(e,t,r)=>{let n=r.fields[e.left];if(!n)throw new Error(`Field ${e.left} not found in ${r.name}`);let i=ki(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=Fr(o,t);return {type:"subquery",source:{type:"record_pointer",thing:[o,...l.subTypes],ids:e.right},oppositePath:s,cardinality:a}},va=(e,t,r)=>{let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);let i=ki(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=Fr(o,t),d={type:"table_scan",thing:[o,...l.subTypes]},c=Ii({source:d,filter:e.filter,schema:t,thing:l});return {type:"subquery",source:c.source,oppositePath:s,cardinality:a,filter:c.filter}},ki=(e,t,r)=>{if(!(e.type!=="link"&&e.type!=="role")){if(e.type==="role"){let n=t[e.opposite.thing]?.fields?.[e.opposite.path];if(n?.type!=="link")throw new Error(`Role field ${e.name} in relation ${r.name} is not played by a link field`);if(n.target!=="relation")return}return e.opposite}},Ci=(e,t,r)=>({fields:e.fields.map(n=>Ha(n,t,r))}),Ha=(e,t,r)=>{if(e.type==="metadata"||e.type==="data"||e.type==="flex"||e.type==="reference")return e;let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);if(n.type!=="link"&&n.type!=="role")throw new Error(`Field ${e.path} is not a link or role field and can't be projected as nested reference`);let i=t[n.opposite.thing];if(!i)throw new Error(`Thing ${n.opposite.thing} not found in schema`);return {type:"nested_reference",path:e.path,projection:Ci(e.projection,t,i),ids:e.ids,filter:e.filter?gt(e.filter):void 0,alias:e.alias,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},gt=e=>{if(e.type==="list"){if(e.right.length===0)return e.op==="IN"||e.op==="CONTAINSANY"?{type:"falsy"}:void 0;if(e.right.length===1)switch(e.op){case "IN":return {type:"scalar",op:"=",left:e.left,right:e.right[0]};case "NOT IN":return {type:"scalar",op:"!=",left:e.left,right:e.right[0]};case "CONTAINSALL":case "CONTAINSANY":return {type:"scalar",op:"CONTAINS",left:e.left,right:e.right[0]};case "CONTAINSNONE":return {type:"scalar",op:"CONTAINSNOT",left:e.left,right:e.right[0]}}}if(e.type==="ref"&&e.right.length===0)return e.op==="IN"||e.op==="CONTAINSALL"||e.op==="CONTAINSANY"?{type:"falsy"}:void 0;if(e.type==="and"||e.type==="or"){let t=e.filters.flatMap(i=>{let o=gt(i);return o===void 0?[]:o.type===e.type?o.filters:[o]});if(e.type==="and"&&t.some(i=>i.type==="falsy"))return {type:"falsy"};if(e.type==="or"&&(t=t.filter(i=>i.type!=="falsy")),t.length===0)return;if(t.length===1)return t[0];let n=t.map(i=>{if(i.type==="scalar")return {filter:i,score:qt[i.op]??0};if(i.type==="list"){let o=qt[i.op]??0;return {filter:i,score:o**i.right.length}}if(i.type==="ref"){let o=qt[i.op]??0;return i.thing?{filter:i,score:o**(i.right.length*i.thing.length)}:{filter:i,score:o**i.right.length*.9}}return {filter:i,score:0}}).sort((i,o)=>o.score-i.score);return {type:e.type,filters:n.map(i=>i.filter)}}if(e.type==="not"){let t=gt(e.filter);if(t===void 0)return;if(t.type==="not")return t.filter;if(t.type==="scalar"){if(t.op==="=")return {type:"scalar",op:"!=",left:t.left,right:t.right};if(t.op==="!=")return {type:"scalar",op:"=",left:t.left,right:t.right}}return {type:"not",filter:t}}if(e.type==="nested"){let t=gt(e.filter);return t?{type:"nested",filter:t,path:e.path,cardinality:e.cardinality}:void 0}return e},qt={"=":.9,">":.5,"<":.5,">=":.5,"<=":.5,IN:.5,"NOT IN":.5,CONTAINSALL:.3,CONTAINSANY:.4,CONTAINSNONE:.3},Ja=(e,t)=>{if(e.type==="and"){let r=Object.fromEntries(e.filters.map((i,o)=>{if(i.type!=="scalar")return;let s=qt[i.op];if(s)return [i.left,{filter:i,index:o,score:s}]}).filter(i=>i!==void 0)),n=t.indexes.filter(i=>i.type!=="single").sort((i,o)=>o.fields.length-i.fields.length);if(n.length>0){let i=[];for(let s of n){let a=[];for(let l of s.fields){let d=r[l];if(!d||a.some(c=>c.index===d.index))break;a.push(d);}a.length>0&&i.push({filters:a,score:a.reduce((l,d)=>l+l*d.score,1)});}i.sort((s,a)=>a.score-s.score);let[o]=i;if(o&&o.score>1)return {type:"and",filters:[...o.filters.map(s=>s.filter),...e.filters.filter((s,a)=>!o.filters.some(l=>l.index===a))]}}}if(e.type==="and"||e.type==="or"){let n=e.filters.map((a,l)=>{if(a.type==="scalar"&&a.op==="="){let d=t.fields[a.left];if(Oi(d,t.indexes))return {filter:a,score:1,index:l}}else if(a.type==="list"&&a.op==="IN"){let d=t.fields[a.left];if(Oi(d,t.indexes)){let c=.5**(a.right.length-1);return {filter:a,score:c,index:l}}}return {filter:a,score:0,index:l}}).sort((a,l)=>l.score-a.score),[i]=n,o=i&&i.score!==0?i.filter:void 0,s=o?.type==="list"&&o.op==="IN"?{type:"or",filters:o.right.map(a=>({type:"scalar",op:"=",left:o.left,right:a}))}:o;return {type:e.type,filters:s?[s,...e.filters.filter((a,l)=>l!==i.index)]:e.filters}}return e},Br=e=>{if(e.length!==0)return e.length===1?e[0]:{type:"and",filters:e}},Oi=(e,t)=>e.type==="role"||e.type==="link"||t.some(r=>r.type==="single"&&r.field===e.name||r.type==="composite"&&r.fields.includes(e.name)),Fr=(e,t)=>{let r=t[e];if(!r)throw new Error(`Thing ${e} not found in schema`);return r},Pi=(e,t)=>{if(e.type==="table_scan"||e.type==="record_pointer")return Fr(e.thing[0],t);let r=Pi(e.source,t),n=r.fields[e.oppositePath];if(!n)throw new Error(`Field ${e.oppositePath} not found in ${r.name}`);if(n.type==="constant"||n.type==="computed"||n.type==="data"||n.type==="ref")throw new Error(`Invalid source: ${JSON.stringify(e)}`);let i=t[n.opposite.thing];if(!i)throw new Error(`Thing ${n.opposite.thing} not found in schema`);return i};var Ka=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qi=e=>e==null,xi=e=>Array.isArray(e)&&e.length===0,ji=e=>{let{batch:t,results:r,schema:n,metadata:i,returnNulls:o}=e;return t.map((s,a)=>Ya({query:s,result:r[a],schema:n,metadata:i,returnNulls:o}))},Ya=e=>{let{query:t,result:r,schema:n,metadata:i,returnNulls:o}=e;if(!r)return r??null;let s=n[t.$thing];if(!s)throw new Error(`Thing ${t.$thing} not found in schema`);return Array.isArray(r)?o&&r.length===0?null:r.map(a=>xt({query:t,result:a,thing:s,schema:n,metadata:i,returnNulls:o})):xt({query:t,result:r,thing:s,schema:n,metadata:i,returnNulls:o})},Xa=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;return Array.isArray(r)?r.length===0?null:r.map(a=>xt({query:t,result:a,thing:n,schema:i,metadata:o,returnNulls:s})):xt({query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s})},xt=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;if(!Ka(r))return null;let a={};o&&(a.$thing=r.$thing??null,a.$id=r.$id??null,a.$thingType=n.type);let l=t.$fields??Object.keys(n.fields);for(let d of l){let c=typeof d=="string"?d:d.$path,u=typeof d=="string"?d:d.$as??c;if(t.$excludedFields?.includes(c))continue;if(c==="$id"||c==="$thing"){a[u]=r[u]??null;continue}let p=n.fields[c];if(!p)throw new Error(`Field ${c} not found in ${n.name}`);if(p.type==="constant"){a[u]=p.value;continue}if(p.type==="computed"){a[u]=p.fn(r);continue}let f=r[u];if(p.type==="data"){if(!s&&qi(f))continue;a[u]=f??null;continue}if(!s&&(qi(f)||xi(f)))continue;if(typeof d=="string"||p.type==="ref"){a[u]=xi(f)?null:f??null;continue}let h=i[p.opposite.thing];a[u]=Xa({query:d,result:f,thing:h,schema:i,metadata:o,returnNulls:s});}return a};var _i=async e=>{let{client:t,queries:r,config:n,params:i}=e,o=`BEGIN TRANSACTION;
110
110
  ${r.join(`;
111
111
  `)};
112
- COMMIT TRANSACTION;`;return n.query?.debugger&&Z(`batchedQuery[${G}]`,JSON.stringify({batchedQuery:o})),await t.query(o,i)};var _i=async(e,t,r,n)=>{let i=nanoid(3);if(e.length===0)return [];let o=performance.now(),s=e.map(E=>yi.parse(E));fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/bqlQueries"],`> runSurrealDbQueryMachine2/bqlQueries ${i}
113
- `,JSON.stringify(s));let a=s.map(E=>gi(E,t,!r.query?.noMetadata));fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/logicalQueries"],`> runSurrealDbQueryMachine2/logicalQueries ${i}
114
- `,JSON.stringify(a));let l=a.map(E=>Oi(E,t));fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/optimizedQueries"],`> runSurrealDbQueryMachine2/optimizedQueries ${i}
115
- `,JSON.stringify(l));let d={},c=l.map(E=>Ri(E,d));fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/params"],`> runSurrealDbQueryMachine2/params ${i}
116
- `,JSON.stringify(d)),fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/surqlQueries"],`> runSurrealDbQueryMachine2/surqlQueries ${i}
117
- `,JSON.stringify(c));let u=performance.now(),p=await ji({client:n,queries:c,config:r,params:d}),f=performance.now();fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/queryDuration"],`> runSurrealDbQueryMachine2/queryDuration ${i}
118
- `,`${(f-u).toFixed(2)}ms`),fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/result"],`> runSurrealDbQueryMachine2/result ${i}
119
- `,JSON.stringify(p));let h=xi({batch:s,results:p,schema:t,metadata:!r.query?.noMetadata,returnNulls:!!r.query?.returnNulls});fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/finalResult"],`> runSurrealDbQueryMachine2/finalResult ${i}
120
- `,h);let $=performance.now();return fe(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/duration"],`> runSurrealDbQueryMachine2/duration ${i}
121
- `,`${($-o).toFixed(2)}ms`),h};var qt=e=>{let{$filter:t,$var:r,$thing:n,schema:i,depth:o}=e,s=il(t,ee(i,n)),{$not:a,...l}=s,d=[];if(Sr(a)){let u=Tr(a,r,n,i,o,true);d.push(...u);}else if(a!==void 0)throw new Error("$not must be a PositiveFilter object");let c=Tr(l,r,n,i,o,false);return d.push(...c),d.join(`
122
- `)},Tr=(e,t,r,n,i,o)=>{let s=ee(n,r),a=[];for(let[l,d]of Object.entries(e)){if(l.startsWith("$")){let p=l.toLowerCase();if(p==="$and"||p==="$or"){let h=(isArray(d)?d:[d]).map(E=>{if(Sr(E))return Tr(E,t,r,n,i+1,o).join(`
112
+ COMMIT TRANSACTION;`;return n.query?.debugger&&Z(`batchedQuery[${G}]`,JSON.stringify({batchedQuery:o})),await t.query(o,i)};var Vi=async(e,t,r,n)=>{let i=nanoid(3);if(e.length===0)return [];let o=performance.now(),s=e.map(E=>gi.parse(E));ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/bqlQueries"],`> runSurrealDbQueryMachine2/bqlQueries ${i}
113
+ `,JSON.stringify(s));let a=s.map(E=>Ei(E,t,!r.query?.noMetadata));ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/logicalQueries"],`> runSurrealDbQueryMachine2/logicalQueries ${i}
114
+ `,JSON.stringify(a));let l=a.map(E=>Ni(E,t));ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/optimizedQueries"],`> runSurrealDbQueryMachine2/optimizedQueries ${i}
115
+ `,JSON.stringify(l));let d={},c=l.map(E=>Li(E,d));ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/params"],`> runSurrealDbQueryMachine2/params ${i}
116
+ `,JSON.stringify(d)),ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/surqlQueries"],`> runSurrealDbQueryMachine2/surqlQueries ${i}
117
+ `,JSON.stringify(c));let u=performance.now(),p=await _i({client:n,queries:c,config:r,params:d}),f=performance.now();ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/queryDuration"],`> runSurrealDbQueryMachine2/queryDuration ${i}
118
+ `,`${(f-u).toFixed(2)}ms`),ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/result"],`> runSurrealDbQueryMachine2/result ${i}
119
+ `,JSON.stringify(p));let h=ji({batch:s,results:p,schema:t,metadata:!r.query?.noMetadata,returnNulls:!!r.query?.returnNulls});ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/finalResult"],`> runSurrealDbQueryMachine2/finalResult ${i}
120
+ `,h);let $=performance.now();return ue(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/duration"],`> runSurrealDbQueryMachine2/duration ${i}
121
+ `,`${($-o).toFixed(2)}ms`),h};var jt=e=>{let{$filter:t,$var:r,$thing:n,schema:i,depth:o}=e,s=rl(t,ee(i,n)),{$not:a,...l}=s,d=[];if(Tr(a)){let u=br(a,r,n,i,o,true);d.push(...u);}else if(a!==void 0)throw new Error("$not must be a PositiveFilter object");let c=br(l,r,n,i,o,false);return d.push(...c),d.join(`
122
+ `)},br=(e,t,r,n,i,o)=>{let s=ee(n,r),a=[];for(let[l,d]of Object.entries(e)){if(l.startsWith("$")){let p=l.toLowerCase();if(p==="$and"||p==="$or"){let h=(isArray(d)?d:[d]).map(E=>{if(Tr(E))return br(E,t,r,n,i+1,o).join(`
123
123
  `);throw new Error(`Invalid subfilter in ${p}: ${JSON.stringify(E)}`)}),$=h.join(p==="$and"?`
124
- `:" } or { ");p==="$or"&&h.length>1?a.push(L(`{ ${$} };`,i)):a.push(L($,i));continue}continue}if(s.dataFields?.find(p=>p.dbPath===l||p.path===l)){let p=tl(l,d,t,i,o);a.push(...p);continue}let u=s.linkFields?.find(p=>p.path===l);if(u){let p=rl(u,d,t,n,i,o);a.push(...p);continue}if(s.thingType==="relation"){let p=s.roles[l];if(p){let f=nl(p,d,t,r,n,i,o);a.push(...f);continue}}throw new Error(`"${r}" does not have property "${l}"`)}return a},tl=(e,t,r,n,i)=>{let o=[];if(isObject(t)&&!isArray(t))for(let[s,a]of Object.entries(t)){let l=s.toLowerCase(),d="";switch(l){case "$eq":d=`$${r} has ${e} ${Se(a)};`;break;case "$ne":d=`not { $${r} has ${e} ${Se(a)}; };`;break;case "$in":{if(!isArray(a))throw new Error("Value for $in operator must be an array");let c=a.map(u=>`$${r} has ${e} ${Se(u)};`);d=gt(c),i&&(d=`not { ${d} };`);break}case "$nin":if(!isArray(a))throw new Error("Value for $nin operator must be an array");for(let c of a){let u=`not { $${r} has ${e} ${Se(c)}; };`;o.push(L(u,n));}continue;case "$exists":if(a===true)d=`$${r} has ${e} $${e}_${v4()};`;else if(a===false)d=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${a}`);break;default:throw new Error(`Unsupported operator "${s}" for data field "${e}"`)}i&&(d=`not { ${d} };`),o.push(L(d,n));}else if(isArray(t)){let s=t.map(l=>`$${r} has ${e} ${Se(l)};`),a=gt(s);a&&(i&&(a=`not { ${a} };`),o.push(L(a,n)));}else {let s=`$${r} has ${e} ${Se(t)};`;i&&(s=`not { ${s} };`),o.push(L(s,n));}return o},rl=(e,t,r,n,i,o)=>{let s=[],[a]=e.oppositeLinkFieldsPlayedBy,d=ee(n,a.thing).idFields?.[0];if(!d)throw new Error(`"${a.thing}" does not have an id field`);let c=`${a.thing}_${v4()}`,u="";if(e.target==="relation")if(t===null)u=o?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let p=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${d} ${Se(f)};`);u=gt(p),o&&(u=`not { ${u} };`);}else u=`(${e.plays}: $${r}) isa ${e.relation}, has ${d} ${Se(t)};`,o&&(u=`not { ${u} };`);else if(t===null)u=o?`$${c} isa ${a.thing}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${a.thing}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let p=t.map(f=>`$${c} isa ${a.thing}, has ${d} ${Se(f)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`);u=gt(p),o&&(u=`not { ${u} };`);}else u=`$${c} isa ${a.thing}, has ${d} ${Se(t)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`,o&&(u=`not { ${u} };`);return s.push(L(u,i)),s},nl=(e,t,r,n,i,o,s)=>{let a=[],[l]=e.playedBy||[],c=ee(i,l.thing).idFields?.[0];if(!c)throw new Error(`"${l.thing}" does not have an id field`);let u=`${l.thing}_${v4()}`,p=v4(),f=`${r}_${p}`;a.push(L(`$${f} isa ${n};`,o));let h="";if(t===null)h=`$${f} (${l.plays}: ${u});`,s?a.push(L(h,o)):a.push(L(`not { ${h} };`,o));else if(isArray(t)){let $=t.map(E=>`$${u} isa ${l.thing}, has ${c} ${Se(E)}; $${f} (${l.plays}: $${u});`);h=gt($),s?a.push(L(`not { ${h} };`,o)):a.push(L(h,o));}else h=`$${u} isa ${l.thing}, has ${c} ${Se(t)}; $${f} (${l.plays}: $${u});`,s?a.push(L(`not { ${h} };`,o)):a.push(L(h,o));return a.push(L(`$${r} is $${f};`,o)),a},gt=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},Se=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("|")})$"`:Se(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},il=(e,t)=>{let r={};if(t.dataFields?.forEach(s=>{s.path!==s.dbPath&&(r[s.path]=s.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...i}=e,o=zi(i,r);return n&&Sr(n)&&(o.$not=zi(n,r)),o},zi=(e,t)=>{let r={};return Object.entries(e).forEach(([n,i])=>{let o=t[n]||n;r[o]=i;}),r},Sr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var wr="___",Ui=async e=>{let{queries:t,schema:r}=e;return t.map(n=>ol({query:n,schema:r}))},ol=e=>{let{query:t,schema:r}=e,{$path:n,$thing:i,$filter:o,$fields:s,$sort:a,$offset:l,$limit:d,$id:c}=t;if(!n)throw new Error("Path is not defined");let u=[],p=t[oe];if(u.push("match"),u.push(`$${n} isa ${i};`),o||c){let $=Rt(r,t),E={...o,...c?{[$]:c}:{}},m=qt({$filter:E,$var:n,$thing:i,schema:r,depth:0});u.push(`
125
- ${m}`);}let f=Qr({schema:r,$thing:i,$var:n,$sort:a,depth:0});f&&u.push(f.match);let h=`M_${v4()}`;if(u.push(`?queryPath${h} = "${p}";`),u.push("fetch"),u.push(`?queryPath${h} as "queryPath";`),s){let $=s.filter(y=>y.$fieldType==="data");$&&$.length>0&&u.push(...Rr($,n,0));let E=s.filter(y=>y.$fieldType==="link");E&&E.length>0&&u.push(...Mr(E,n,n,0,r));let m=s.filter(y=>y.$fieldType==="role");m&&m.length>0&&u.push(...Lr(m,n,n,0,r));}return f&&u.push(f.sort),typeof l=="number"&&u.push(`
124
+ `:" } or { ");p==="$or"&&h.length>1?a.push(L(`{ ${$} };`,i)):a.push(L($,i));continue}continue}if(s.dataFields?.find(p=>p.dbPath===l||p.path===l)){let p=Ga(l,d,t,i,o);a.push(...p);continue}let u=s.linkFields?.find(p=>p.path===l);if(u){let p=el(u,d,t,n,i,o);a.push(...p);continue}if(s.thingType==="relation"){let p=s.roles[l];if(p){let f=tl(p,d,t,r,n,i,o);a.push(...f);continue}}throw new Error(`"${r}" does not have property "${l}"`)}return a},Ga=(e,t,r,n,i)=>{let o=[];if(isObject(t)&&!isArray(t))for(let[s,a]of Object.entries(t)){let l=s.toLowerCase(),d="";switch(l){case "$eq":d=`$${r} has ${e} ${Se(a)};`;break;case "$ne":d=`not { $${r} has ${e} ${Se(a)}; };`;break;case "$in":{if(!isArray(a))throw new Error("Value for $in operator must be an array");let c=a.map(u=>`$${r} has ${e} ${Se(u)};`);d=Bt(c),i&&(d=`not { ${d} };`);break}case "$nin":if(!isArray(a))throw new Error("Value for $nin operator must be an array");for(let c of a){let u=`not { $${r} has ${e} ${Se(c)}; };`;o.push(L(u,n));}continue;case "$exists":if(a===true)d=`$${r} has ${e} $${e}_${v4()};`;else if(a===false)d=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${a}`);break;default:throw new Error(`Unsupported operator "${s}" for data field "${e}"`)}i&&(d=`not { ${d} };`),o.push(L(d,n));}else if(isArray(t)){let s=t.map(l=>`$${r} has ${e} ${Se(l)};`),a=Bt(s);a&&(i&&(a=`not { ${a} };`),o.push(L(a,n)));}else {let s=`$${r} has ${e} ${Se(t)};`;i&&(s=`not { ${s} };`),o.push(L(s,n));}return o},el=(e,t,r,n,i,o)=>{let s=[],[a]=e.oppositeLinkFieldsPlayedBy,d=ee(n,a.thing).idFields?.[0];if(!d)throw new Error(`"${a.thing}" does not have an id field`);let c=`${a.thing}_${v4()}`,u="";if(e.target==="relation")if(t===null)u=o?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let p=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${d} ${Se(f)};`);u=Bt(p),o&&(u=`not { ${u} };`);}else u=`(${e.plays}: $${r}) isa ${e.relation}, has ${d} ${Se(t)};`,o&&(u=`not { ${u} };`);else if(t===null)u=o?`$${c} isa ${a.thing}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${a.thing}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let p=t.map(f=>`$${c} isa ${a.thing}, has ${d} ${Se(f)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`);u=Bt(p),o&&(u=`not { ${u} };`);}else u=`$${c} isa ${a.thing}, has ${d} ${Se(t)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`,o&&(u=`not { ${u} };`);return s.push(L(u,i)),s},tl=(e,t,r,n,i,o,s)=>{let a=[],[l]=e.playedBy||[],c=ee(i,l.thing).idFields?.[0];if(!c)throw new Error(`"${l.thing}" does not have an id field`);let u=`${l.thing}_${v4()}`,p=v4(),f=`${r}_${p}`;a.push(L(`$${f} isa ${n};`,o));let h="";if(t===null)h=`$${f} (${l.plays}: ${u});`,s?a.push(L(h,o)):a.push(L(`not { ${h} };`,o));else if(isArray(t)){let $=t.map(E=>`$${u} isa ${l.thing}, has ${c} ${Se(E)}; $${f} (${l.plays}: $${u});`);h=Bt($),s?a.push(L(`not { ${h} };`,o)):a.push(L(h,o));}else h=`$${u} isa ${l.thing}, has ${c} ${Se(t)}; $${f} (${l.plays}: $${u});`,s?a.push(L(`not { ${h} };`,o)):a.push(L(h,o));return a.push(L(`$${r} is $${f};`,o)),a},Bt=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},Se=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("|")})$"`:Se(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},rl=(e,t)=>{let r={};if(t.dataFields?.forEach(s=>{s.path!==s.dbPath&&(r[s.path]=s.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...i}=e,o=zi(i,r);return n&&Tr(n)&&(o.$not=zi(n,r)),o},zi=(e,t)=>{let r={};return Object.entries(e).forEach(([n,i])=>{let o=t[n]||n;r[o]=i;}),r},Tr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Sr="___",Wi=async e=>{let{queries:t,schema:r}=e;return t.map(n=>nl({query:n,schema:r}))},nl=e=>{let{query:t,schema:r}=e,{$path:n,$thing:i,$filter:o,$fields:s,$sort:a,$offset:l,$limit:d,$id:c}=t;if(!n)throw new Error("Path is not defined");let u=[],p=t[oe];if(u.push("match"),u.push(`$${n} isa ${i};`),o||c){let $=Mt(r,t),E={...o,...c?{[$]:c}:{}},y=jt({$filter:E,$var:n,$thing:i,schema:r,depth:0});u.push(`
125
+ ${y}`);}let f=Mr({schema:r,$thing:i,$var:n,$sort:a,depth:0});f&&u.push(f.match);let h=`M_${v4()}`;if(u.push(`?queryPath${h} = "${p}";`),u.push("fetch"),u.push(`?queryPath${h} as "queryPath";`),s){let $=s.filter(m=>m.$fieldType==="data");$&&$.length>0&&u.push(...wr($,n,0));let E=s.filter(m=>m.$fieldType==="link");E&&E.length>0&&u.push(...Lr(E,n,n,0,r));let y=s.filter(m=>m.$fieldType==="role");y&&y.length>0&&u.push(...Rr(y,n,n,0,r));}return f&&u.push(f.sort),typeof l=="number"&&u.push(`
126
126
  offset ${l};`),typeof d=="number"&&u.push(`
127
127
  limit ${d};`),u.join(`
128
- `)},Rr=(e,t,r)=>{let n=[],i=[],o=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][ue].contentType==="FLEX"&&o.push({path:e[c][ue].dbPath}),i.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=n.join(", "),l=`$metadata:{as:[${i.join(",")}]}`,d=[L(`$${t} as "${t}.${l}.$dataFields": ${s};`,r)];return o.length>0&&o.forEach(c=>{d.push(L(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),d},Lr=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:u,$filterByUnique:p,$thing:f,$sort:h,$offset:$,$limit:E}=a,m=a[oe],y=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(L(`"${r}.${y}.${a.$var}": {`,n)),s.push(L("match",o));let B=`${t}${wr}${a.$var}`;if(s.push(L(`$${B} isa ${a.$thing};`,o)),s.push(L(`$${t} (${a.$var}: $${t}${wr}${a.$var}) isa ${a.$intermediary};`,o)),a.$filter||a.$id){let T=Rt(i,a),w=a.$id?{[T]:a.$id}:{},Q={...a.$filter,...w};s.push(qt({$filter:Q,$var:B,$thing:a.$thing,schema:i,depth:o}));}let g=Qr({schema:i,$thing:f,$var:B,$sort:h,depth:o});if(g&&s.push(g.match),l){let T=`M_${v4()}`;s.push(L(`
129
- ?queryPath${T} = "${m}";`,o)),s.push(L("fetch",o)),s.push(L(`?queryPath${T} as "queryPath";`,o));let w=l?.filter(j=>j.$fieldType==="data");w&&w.length>0&&s.push(...Rr(w,B,o));let Q=l?.filter(j=>j.$fieldType==="link");Q&&Q.length>0&&s.push(...Mr(Q,B,`${t}.${a.$var}`,o,i));let O=l?.filter(j=>j.$fieldType==="role");O&&O.length>0&&s.push(...Lr(O,B,`${t}.${a.$var}`,o,i));}g&&s.push(g.sort),typeof $=="number"&&s.push(L(`offset ${$};`,o)),typeof E=="number"&&s.push(L(`limit ${E};`,o)),s.push(L("};",n));}return s},Mr=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:u,$filterByUnique:p,$playedBy:f,$thing:h,$sort:$,$offset:E,$limit:m}=a,y=a[oe],B=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(L(`"${r}.${B}.${a.$var}": {`,n)),s.push(L("match",o));let g=`${t}${wr}${a.$var}`;if(s.push(L(`$${g} isa ${a.$thing};`,o)),a.$filter||a.$id){let w=Rt(i,a),Q=a.$id?{[w]:a.$id}:{},O={...a.$filter,...Q};s.push(qt({$filter:O,$var:g,$thing:a.$thing,schema:i,depth:o}));}let T=Qr({schema:i,$thing:h,$var:g,$sort:$,depth:o});if(T&&s.push(T.match),a.$target==="role"?s.push(L(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${g}) isa ${a.$intermediary};`,o)):s.push(L(`$${g} (${a.$plays}: $${t});`,o)),l){let w=`M_${v4()}`;s.push(L(`?queryPath${w} = "${y}";`,o)),s.push(L("fetch",o)),s.push(L(`?queryPath${w} as "queryPath";`,o));let Q=l?.filter(K=>K.$fieldType==="data");Q&&Q.length>0&&s.push(...Rr(Q,g,o));let O=l?.filter(K=>K.$fieldType==="link");O&&O.length>0&&s.push(...Mr(O,g,`${t}.${a.$var}`,o,i));let j=l?.filter(K=>K.$fieldType==="role");j&&j.length>0&&s.push(...Lr(j,g,`${t}.${a.$var}`,o,i));}T&&s.push(T.sort),typeof E=="number"&&s.push(L(`offset ${E};`,o)),typeof m=="number"&&s.push(L(`limit ${m};`,o)),s.push(L("};",n));}return s},sl=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},Qr=e=>{let{$var:t,$thing:r,schema:n,$sort:i,depth:o}=e,s=ee(n,r),a=[],l=[];if(i?.forEach(d=>{let c=sl(d),u=s.dataFields?.find(h=>h.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let p=`${c.field}_${v4()}`;a.push(L("{",o)),a.push(L(`$${t} has ${u.dbPath} $${p}_1;`,o+1)),a.push(L("not {",o+1)),a.push(L(`$${t} has ${u.dbPath} $${p}_2;`,o+2)),a.push(L(`$${p}_2 < $${p}_1;`,o+2)),a.push(L("};",o+1)),a.push(L(`?${p}_ = $${p}_1;`,o+1)),a.push(L("} or {",o)),a.push(L(`not { $${t} has ${u.dbPath} $${p}_1; };`,o+1)),a.push(L(`?${p}_ = "~";`,o+1)),a.push(L("};",o)),a.push(L(`?${p} = ?${p}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${p} ${f}`);}),a.length!==0)return {match:a.join(""),sort:L(`sort ${l.join(", ")};`,o)}};var vi=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:i,rawTqlRes:o}=e;if(!t)throw new Error("BQL request not enriched");if(!o)throw new Error("TQL query not executed");return o.map((s,a)=>{let l=r[a],d=t[a];return ll(s,l,d,n,i)})},ll=(e,t,r,n,i)=>e.length===0?null:r.$filterByUnique?Wi(e[0],t,n,i):e.map(o=>Wi(o,t,n,i)),Wi=(e,t,r,n)=>{let{dataFields:i,currentSchema:o,linkFields:s,roleFields:a,schemaValue:l}=Dr(e,r),d=Ar(i,o,n),c=Nr(s,r,n),u=Or(a,r,n),p=t?.$fields?.every(h=>!o?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...u,...l,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?d.id:t.$id}:{},...p?Object.fromEntries(Object.entries(d).filter(([h])=>!o?.idFields?.includes(h))):d}},Dr=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),i=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");if(i?.length>0)for(let f of i){let h=f.replace(/\.\$multiVal$/,""),$=e[f][0][h].attribute;e[n][h]=$;}let o=e[n],s=n.split(".")[n.split(".").length-2];if(o.$metaData=s,o.length===0)throw new Error("No dataFields");let a=o.type,l={$thing:a.label,$thingType:a.root,[oe]:e.queryPath.value},d={[`$${l.$thingType}`]:l.$thing},c=z(t,d),u=r.filter(f=>{let h=Ee(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(f=>{let h=Ee(f.split(".").pop()),$=Ee(c.linkFields?.find(E=>E.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),p=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(f=>{let h=Ee(f.split(".").pop());return {$roleFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:o,schemaValue:l,currentSchema:c,linkFields:u,roleFields:p}},Ar=(e,t,r)=>{let{$metaData:n}=e,{as:i}=cl(n),o=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).flatMap(([s,a])=>{let l=t.dataFields?.find(p=>p.path===s||p.dbPath===s),d=s==="id",c=Array.isArray(i)?i.find(p=>p[s])?.[s]:s,u;if(l?.cardinality==="ONE"){if(u=a[0]?a[0].value:r.query?.returnNulls?null:void 0,l.contentType==="DATE"||l.contentType==="FLEX"&&a[0].type.value_type==="datetime"?u=u&&`${u}Z`:l.contentType==="JSON"&&(u=u&&JSON.parse(u)),d)return [[c,u],["$id",u]].filter(([p,f])=>f!==void 0)}else if(l?.cardinality==="MANY"){if(!isArray(a))throw new Error("Typedb fetch has changed its format");if(a.length===0)return r.query?.returnNulls?[[c,null]]:[];l.contentType==="DATE"?u=a.map(p=>`${p.value}Z`):l.contentType==="FLEX"?u=a.map(p=>p.type.value_type==="datetime"?`${p.value}Z`:p.value):l.contentType==="JSON"?u=a.map(p=>p.value&&JSON.parse(p.value)):u=a.map(p=>p.value);}return [[c,u]].filter(([p,f])=>f!==void 0)});return Object.fromEntries([...o])},Or=(e,t,r)=>{let n={};for(let i of e){let{$roleFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:u}=Hi(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:E,roleFields:m,schemaValue:y}=Dr(f,t),B=Ar(h,$,r);if(d==="T")return B.id;let g=Nr(E,t,r),T=Or(m,t,r),w={...B};if(c==="true"&&$?.idFields)for(let Q of $.idFields)delete w[Q];return {...w,...g,...T,...y}});p.length>0?n[l]=a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls&&(n[l]=null);}return n},Nr=(e,t,r)=>{let n={};for(let i of e){let{$linkFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:u}=Hi(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:E,roleFields:m,schemaValue:y}=Dr(f,t),B=Ar(h,$,r);if(d==="T")return B.id;let g=Nr(E,t,r),T=Or(m,t,r),w={...B};if(c==="true")for(let Q of $.idFields??[])delete w[Q];return {...w,...g,...T,...y}});n[l]=p.length>0?a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls?null:void 0;}return n},Hi=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,i=/filterByUnique:([a-zA-Z0-9_\-·]+)/,o=e.match(t),s=e.match(r),a=e.match(n),l=e.match(i);return {as:o?o[1]:null,justId:s?s[1]:null,idNotIncluded:a?a[1]:null,filterByUnique:l?l[1]:null}},cl=e=>{try{let r=(i=>{let o=i.replace("$metadata:","");return o=o.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),o=o.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,a,l)=>/^{.*}$/.test(l)?`:${l}`:`:${a}"${l}"`),o=o.replace(/\[([^\]]+)\]/g,(s,a)=>`[${a.split(",").map(l=>l.trim().startsWith("{")&&l.trim().endsWith("}")?l.trim():`"${l.trim()}"`).join(",")}]`),o})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var jt=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,i=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!i)throw new Error("Client not found");n=await i.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:i,session:n});}return {client:i,session:n}};var Ji=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,i=new TypeDBOptions;i.infer=true;let{session:o}=await jt(r,n),s=await o.transaction(TransactionType.READ,i),[a,l]=await tryit(parallel)(t.length,t,async d=>await s.query.fetch(d).collect());if(a){await s.rollback();let d=a;throw new Error(`Error running TQL query: ${d.errors}`)}return await s.close(),l};var $l=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Ir=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ml=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,yl=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,ct=x("error","error",q((e,t)=>({...e,error:t.error}))),gl=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),rt(e.bql.raw,e.schema)),x("done","build",q($l)),ct),build:U(async e=>Ui({queries:e.bql.queries??[],schema:e.schema}),x("done","run",q(ml)),ct),run:U(async e=>Ji({dbHandles:e.handles,tqlRequest:Ee(e.tql.queries),config:e.config}),x("done","parse",q(yl)),ct),parse:U(async e=>vi({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries??[],schema:e.schema,config:e.config,rawTqlRes:Ee(e.tql.res)}),x("done","postHooks",q(Ir)),ct),postHooks:U(async e=>Nt(e.schema,Ee(e.bql.queries),Ee(e.bql.res)),x("done","clean",q(Ir)),ct),clean:U(async e=>Ot(e.config,Ee(e.bql.res)),x("done","success",q(Ir)),ct),success:me(),error:me()},e=>e),El=async e=>new Promise((t,r)=>{Re(gl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Ki=async(e,t,r,n)=>El({bql:{raw:e},tql:{},schema:t,config:r,handles:n,error:null});var Bl=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Fl=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Yi=x("error","error",q((e,t)=>({...e,error:t.error}))),bl=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),rt(e.bql.raw,e.schema)),x("done","adapter",q(Bl)),Yi),adapter:U(async e=>{let t={};e.bql.raw?.forEach((a,l)=>{let d=e.bql.raw[l],c="$thing"in a?a.$thing:"$entity"in a?a.$entity:"$relation"in a?a.$relation:void 0;if(!c)throw new Error(`No $thing found in query ${JSON.stringify(a,null,2)}`);let u=ee(e.schema,c),{id:p}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[p]){let h=e.handles.typeDB?.get(p)?.client;if(!h)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[p]={db:"typeDB",client:h,rawBql:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[p]){let h=e.handles.surrealDB?.get(p)?.client;if(!h)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[p]={db:"surrealDB",client:h,rawBql:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let f=t[p];f.rawBql.push(d),f.indices.push(l);});let r=Object.values(t),n=r.map(a=>{if(a.db==="typeDB")return Ki(a.rawBql,e.schema,e.config,e.handles);if(a.db==="surrealDB")return e.config.query?.legacySurrealDBAdapter?fi(a.rawBql,e.schema,e.config,a.client):_i(a.rawBql,e.draftSchema,e.config,a.client);throw new Error(`Unsupported DB "${JSON.stringify(a,null,2)}"`)}),i=await Promise.all(n),o=r.flatMap((a,l)=>{let d=i[l];return a.indices.map((c,u)=>({index:c,result:d[u]}))});return o.sort((a,l)=>a.index<l.index?-1:a.index>l.index?1:0),o.map(({result:a})=>a)},x("done","success",q(Fl)),Yi),success:me(),error:me()},e=>e),Tl=async e=>new Promise((t,r)=>{Re(bl,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),dt=async(e,t,r,n,i)=>Tl({bql:{raw:e},schema:t,draftSchema:r,config:n,handles:i,error:null});var eo=async(e,t,r,n,i)=>{let o=Array.isArray(e)?e:[e],s=o.map(d=>kr(d,true)),l=(await dt(s,t,r,n,i)).bql.res;return o.map((d,c)=>{let u=ee(t,d.$thing);return ro({mut:d,node:l[c],schema:t,thing:u})})},to=new Set(["$op","$bzId","$parentKey"]),wl=new Set(["$relation","$entity","$id",...to]),kr=(e,t)=>{let r={};e.$fields?.forEach(i=>{typeof i=="string"?r[i]=i:r[i.$path]=i;});let n={};for(let i in e){if(to.has(i)||wl.has(i)&&!t)continue;let o=e[i];i.startsWith("$")?n[i]=o:Array.isArray(o)?o[0]&&typeof o[0]=="object"&&(r[i]={$path:i,...kr(o[0],false)}):isObject(o)&&(r[i]={$path:i,...kr(o,false)});}return n.$fields=Object.values(r),n},ro=e=>{let{mut:t,node:r,schema:n,thing:i}=e,o=io(i),s=Ll(r);if(Array.isArray(t))return t.map(l=>{let d=s[l.$id];return d?Xi({mut:l,node:d,schema:n,thing:i,...o}):l});let a=s[t.$id];return Xi({mut:t,node:a,schema:n,thing:i,...o})},Xi=e=>{let{mut:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,{$fields:l,...d}=t;if(!r)return d;let c=no({$fields:t.$fields,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}),u={...d,[et]:c};for(let p in t){if(p.startsWith("$"))continue;let f=t[p];if(o[p]||!f||typeof f!="object"){u[p]=f;continue}let $=s[p]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[p]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${p}"`);let E=ee(n,$);u[p]=ro({mut:f,schema:n,node:r[p],thing:E});}return u},no=e=>{let{$fields:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,l=t||Rl(i),d={$id:r.$id};return l.forEach(c=>{let u=typeof c!="string",p=u?c.$path:c,f=r[p];if(o[p]){d[p]=f;return}let $=s[p]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[p]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${p}"`);if(!u){f&&(d[p]=Array.isArray(f)?f.map(Zi):Zi(f));return}let E=ee(n,$),m=io(E);d[p]=Array.isArray(f)?f.map(y=>Gi({...m,$fields:c.$fields,value:y,schema:n,thing:E})):Gi({...m,$fields:c.$fields,value:f,schema:n,thing:E});}),d},Rl=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},Zi=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},Gi=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 no({...e,node:t})},io=e=>{let t=Object.fromEntries(e.dataFields?.map(i=>[i.path,i])||[]),r=Object.fromEntries(e.linkFields?.map(i=>[i.path,i])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},Ll=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 oo=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(s,a)=>{if(!s?.$thing)return;let{$op:l,$bzId:d,$tempId:c}=s,u=t.relations[s.$thing]||t.entities[s.$thing];if(!u)throw new Error(`[Internal] No schema found for ${s.$thing}`);let p=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:h,usedRoleFields:$,usedRefFields:E}=ge(u,s);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let y={...ye(s,B=>![...$,...h,...E].includes(B)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[Tt]:p}};r.things.push(y);}let m={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let y=ye(s,B=>isSymbol(B)||B.startsWith("$"));for(let B of $){if(isArray(s[B]))for(let T of s[B])n(T,{bzId:d,edgeField:B,tempId:c});else n(s[B],{bzId:d,edgeField:B,tempId:c});let g=(isArray(s[B])?s[B]:[s[B]]).filter(Boolean);for(let[T,w]of Object.entries(m)){let Q=g.filter(O=>w.includes(O.$op)).map(O=>O.$bzId);Q.length>0&&r.edges.push({...y,[B]:Q,$op:T});}}}if(h)for(let y of h){if(isArray(s[y]))for(let T of s[y])n(T,{bzId:d,edgeField:y,tempId:c});else n(s[y],{bzId:d,edgeField:y,tempId:c});let B=u.linkFields?.find(T=>T.path===y),g=isArray(s[y])?s[y]:[s[y]];if(B.target==="relation")for(let[T,w]of Object.entries(m)){let Q=g.filter(O=>w.includes(O.$op));for(let O of Q){let j=ye(O,K=>isSymbol(K)||K.startsWith("$"));r.edges.push({...j,[B.plays]:d,$op:T});}}if(B.target==="role"){let T={create:["link","create"],delete:["unlink","delete"],replace:["replace"]};for(let[w,Q]of Object.entries(T)){let O=g.filter(j=>Q.includes(j.$op));if(O.length!==0)for(let j of O){let K={$thing:B.relation,$thingType:"relation",$bzId:`arc_${j.$bzId}`,[B.plays]:d,[B.oppositeLinkFieldsPlayedBy[0].plays]:j.$bzId,$op:w};r.arcs.push(K);}}}}if(E)for(let y of E){if(isArray(s[y]))for(let w of s[y])n(w,{bzId:d,edgeField:y,tempId:c});else n(s[y],{bzId:d,edgeField:y,tempId:c});let B=(isArray(s[y])?s[y]:[s[y]]).filter(w=>w!=null),g=ye(s,w=>isSymbol(w)||w.startsWith("$")),T=B.map(w=>w.$op?`$\u27E8${w.$bzId}\u27E9`:Ge(w,"FLEX"));T.length>0&&r.references.push({...g,[y]:T,$op:"replace"});}},i=Array.isArray(e)?e:[e];for(let s of i)n(s);let o=[...r.edges].sort((s,a)=>{let l=["unlink","link"];return l.indexOf(s.$op)-l.indexOf(a.$op)});return {...r,edges:o}};var co=async(e,t)=>{let r=c=>{let u=[],p=[],f=m=>{if(m.$id)return m.$id;let y=z(t,m),{idFields:B}=y;if(!B)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=B;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let T=y.dataFields?.find(O=>O.path===g),w=nt({currentThing:m,fieldSchema:T,mandatoryDependencies:true}),Q=m[g]||m.$id||w;if(!Q)throw new Error(`no idValue: ${JSON.stringify(m)}`);return Q},h=m=>{if(m.$op==="create"){let y=f(m);if(u.find(B=>B.$id===y&&B.$op==="create"))throw new Error(`Duplicate id ${y} for node ${JSON.stringify(m)}`);u.push({...m,$id:y});return}m.$tempId&&m.$op==="match"||u.push(m);},$=m=>{if(m.$op==="create"){let y=f(m);if(u.find(B=>B.$id===y&&B.$op==="create"))throw new Error(`Duplicate id ${y} for edge ${JSON.stringify(m)}`);p.push({...m,$id:y});return}p.push(m);};return traverse(c,({value:m,parent:y,meta:B})=>{if(!isObject(m))return;let g=m;if(!B.nodePath?.includes(".$filter")&&g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(g)}`);let T=z(t,g),{dataFields:w,roleFields:Q,linkFields:O,refFields:j,usedFields:K}=ge(T,g),ce=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=K.filter(S=>w?.includes(S)),Y=K.filter(S=>Q?.includes(S)),b=K.filter(S=>O?.includes(S)),F=K.filter(S=>j?.includes(S));if(D.length>0)return "update";if(Y.length>0||b.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,w||[""])),$op:ce(),$bzId:g.$bzId};h(se);let I=g[Oe];if(I?.[J].fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...g,$op:"match"});}let D=I.$things.includes(g.$thing),Y=D?g.$bzId:`LT_${v4()}`,F=An(c,y,B).$bzId;if(!F)throw new Error("No parent id found");let S=()=>g.$op==="delete"?D?"match":"delete":g.$op==="unlink"?D?"unlink":"delete":g.$op==="link"||g.$op==="create"?D?"link":"create":g.$op==="replace"?"replace":"match",M=z(t,{$thing:I.relation,$thingType:"relation"});if(!Object.keys(M.roles).includes(I.plays))throw new Error(`[Wrong format] Field ${I.plays} is not a role of relation ${I.relation}`);let A={$bzId:Y,$thing:D?g.$thing:I.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:S(),...D?{}:{[I.path]:g.$bzId},[I.plays]:F,[Oe]:I,[We]:"linkField"};$(A),(g.$op==="unlink"||S()==="unlink")&&D&&$({$thing:I.relation,$thingType:"relation",$bzId:Y,$op:"match",[I.plays]:F,[Oe]:I,[We]:"linkField"});}if(g.$thingType==="relation"){let D=ye(g,(F,S)=>Q.includes(F)),Y=mapEntries(D,(F,S)=>isArray(S)?[F,S]:isObject(S)?[F,S.$bzId]:[F,S]),b=ye(m,(F,S)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(D).filter(F=>!F.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let F=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=z(t,g).roles,M=mapEntries(Y,(A,k)=>{let V=S[A]?.cardinality;if(!V)throw new Error(`Role ${A} not found in schema`);return Array.isArray(k)?V==="ONE"?k.length>1?[A,k.map(C=>C.$bzId||C)]:[A,k[0].$bzId||k[0]]:[A,k.map(C=>C.$bzId||C)]:[A,k.$bzId||k]}),R={...b,$thing:g.$thing,$thingType:"relation",$op:F(),...M,$bzId:g.$bzId,[We]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){Object.entries(D).forEach(([S,M])=>{let R=isArray(M)?M:[M],A=k=>k==="create"||k==="replace"?"link":k;R.forEach(k=>{if(!k)return;let V=A(k.$op);if(V==="replace")throw new Error("Not supported yet: replace on roleFields");let C={...b,$thing:g.$thing,$thingType:"relation",$op:V==="delete"?"unlink":V,[S]:k.$bzId,$bzId:g.$bzId,[We]:"roleField"};$(C);});});}}}}}),[u,p]},[n,i]=r(e),o=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let p=c.findIndex(f=>f.$bzId===u.$bzId);if(p===-1)return [...c,u];if(c[p].$op==="create"&&u.$op==="match")return c;if(c[p].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,p),u,...c.slice(p+1)];if(c[p].$op==="update"&&u.$op==="update")return [...c.slice(0,p),{...c[p],...u},...c.slice(p+1)];if(c[p].$op==="update"&&u.$op==="match"||c[p].$op==="match"&&u.$op==="update")return [...c.slice(0,p),{...c[p],...u,$op:"update"},...c.slice(p+1)];if(c[p].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[p].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[p].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[p].$op}. Current: ${u.$op}`)},[]),s=i.reduce((c,u)=>{let p=c.find(f=>(f.$id&&f.$id===u.$id||f.$bzId&&f.$bzId===u.$bzId)&&f.$thing===u.$thing&&f.$op===u.$op);if(p){let f={...p};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let E=p[$],m=u[$];Array.isArray(E)&&Array.isArray(m)?f[$]=Array.from(new Set([...E,...m])):!Array.isArray(E)&&Array.isArray(m)?E!==void 0?f[$]=Array.from(new Set([E,...m])):f[$]=m:Array.isArray(E)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...E,m]))):E!==null&&m!==null&&E!==void 0&&m!==void 0?f[$]=Array.from(new Set([E,m])):E==null&&(f[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===u.$id||$.$bzId&&$.$bzId===u.$bzId)&&$.$thing===u.$thing&&$.$op===u.$op)),f]}return [...c,u]},[]);o.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&s.filter(u=>u.$bzId===c.$bzId||u.$tempId&&u.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(On(c))}`)}});let a=[...o,...s],l=new Set(a.filter(c=>c.$tempId).map(c=>c.$tempId)),d=Array.from(l).filter(c=>!a.some(u=>u.$tempId===c&&u.$op==="create"));if(d.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${d.join(", ")}`);return {mergedThings:o,mergedEdges:s}};var Pr="___",Nl=Symbol.for("grandChildOfCreate"),uo=async(e,t,r,n,i)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],s=(b,F)=>Object.keys(b).filter(S=>!S.startsWith("$")&&!o.includes(S)&&b[S]!==void 0?F?!z(t,b).dataFields?.find(R=>R.path===S):true:false);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===false)return;let a=[];if(traverse(e,({parent:b,key:F,value:S})=>{b&&F&&!F.includes("$")&&!o.includes(F)&&isObject(b)?(Array.isArray(b[F])?b[F]:[b[F]]).forEach(R=>{if(isObject(R)){if(b.$op!=="create")a.includes(R.$op)||a.push(R.$op);else if(R.$op==="delete"||R.$op==="unlink")throw new Error(`Cannot ${R.$op} under a create`)}}):!b&&isObject(S)&&(a.includes(S.$op)||a.push(S.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let d=(b=>{let F=(S,M)=>{let R=[],A={},k=["$op","$bzId","$parentKey"],V=["$relation","$entity","$id",...k];for(let C in S)if(!k.includes(C)&&!(V.includes(C)&&!M))if(!C.includes("$")&&(isObject(S[C])||Array.isArray(S[C]))){let ae=Il(S[C]);if(Array.isArray(ae)&&ae.length>0)ae.forEach(De=>{let Ae={$path:C,...F(De),...De.$filter&&{$as:De.$bzId}};R.find(re=>re.$path===Ae.$path&&!re.$filter)||(R=[...R,Ae]);});else {let De={$path:C,...F(ae),...!ae.$filter&&{$as:ae.$bzId}};R=[...R,De];}}else A[C]=S[C];return {...A,$fields:R}};return b.map(S=>F(S,true))})(Array.isArray(e)?e:[e]),u=(await dt(d,t,r,{...n,query:{...n.query,returnNulls:true}},i)).bql.res,p=(b,F)=>{let S=b.$id||b.id||b.$bzId;if(b.$objectPath){let{$objectPath:M}=b,R=M?.beforePath||"root",A=Array.isArray(M.ids)?`[${M.ids}]`:M.ids;return {beforePath:`${R}.${A}___${M.key}`,ids:S,key:F}}return {beforePath:"root",ids:S,key:F}},f=(b,F)=>{let S=b?.beforePath||"root";if(typeof S!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let M=(Array.isArray(b?.ids)?`[${b?.ids}]`:b?.ids);return `${S}.${M}___${b?.key}`},h=b=>{if(b.includes("[")&&b.includes("]")){let[F,S,M]=b.split(/[[\]]/);return S.split(",").map(A=>`${F}${A}${M}`)}return [b]},$={};(b=>produce(b,F=>traverse(F,({key:S,parent:M})=>{if(M&&S&&M.$id&&!S.includes("$")){let R=p(M,S),A=f(R);if(Array.isArray(M[S])){let k=[];M[S].forEach(V=>{isObject(V)?(V.$objectPath=R,k.push(V.$id.toString())):V&&k.push(V.toString());}),$[A]={$objectPath:R,$ids:k};}else {let k=M[S];isObject(k)?($[A]={$objectPath:R,$ids:[k.$id.toString()]},k.$objectPath=R):k?$[A]={$objectPath:R,$ids:[k.toString()]}:k===null&&($[A]=null);}}})))(u||{});let m=b=>produce(b,F=>traverse(F,({key:S,value:M,parent:R})=>{R&&S&&!S.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(R)&&(Array.isArray(R[S])?R[S].forEach(A=>{typeof A!="string"&&(A.$objectPath=p(R,S),A.$parentIsCreate=R.$op==="create",A[Nl]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")]);}):isObject(R[S])&&(R[S].$parentIsCreate=R.$op==="create",R[S][Symbol.for("grandChildOfCreate")]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")],R[S].$objectPath=p(R,S)));})),y=m(e),B=b=>{let F=[];return b.forEach(M=>{if(!M.$id&&!M.id&&!M.$tempId)if(M.$filter){let R=f({...M.$objectPath,key:M.$bzId}),A=$[R];A&&(Array.isArray(A.$ids)?A.$ids:[A.$ids]).forEach(V=>{let C={...M,$id:V,$bzId:`T4_${v4()}`,$filterBzId:M.$bzId};F.push(C);});}else {let R=f(M.$objectPath),A=$[R];A?A?.$ids?.forEach(k=>{let V={...M,$id:k,$bzId:`T4_${v4()}`};F.push(V);}):F.push(M);}else F.push(M);}),F.map(M=>{let R={...M};return s(R,true).forEach(A=>{let k=Array.isArray(R[A])?R[A]:[R[A]],V=B(k);R[A]=V;}),R})},g=B(Array.isArray(y)?y:[y]),T=m(g),Q=(b=>{let F=S=>{let M=re=>{let ie=[],H=[],_=[];return re.forEach(W=>{let $e=s(W,true);if($e.length>0){let P=false;$e.forEach(v=>{(Array.isArray(W[v])?W[v]:[W[v]]).filter(de=>!de.$id&&!de.id&&typeof W=="object").length&&(P=true);}),P?ie.push(W):H.push(W);}else W.$id?_.push({...W,$bzId:W.$tempId||W.$bzId}):_.push({...W,$bzId:W.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ie,operationWithoutMultiples:H,otherOps:_}},{operationWithMultiples:R,operationWithoutMultiples:A,otherOps:k}=M(S),V=re=>{let H=(()=>{let v={};for(let Be in re){let ne=z(t,re);!Be.startsWith("$")&&ne.dataFields?.find(de=>de.path===Be)&&(v[Be]=re[Be]);}return v})(),_=Object.keys(re),W=s(re,true),$e=[],P=(v,Be)=>{if(v===W.length){let de={...Be};_.forEach(Fe=>{Fe.startsWith("$")&&(de[Fe]=re[Fe]);}),$e.push({...de,...H});return}let ne={...Be,[W[v]]:re[W[v]],...xe(Be),...H};P(v+1,ne),P(v+1,Be);};return P(0,{...xe(re)}),$e},C=[];return R.forEach(re=>{let ie=V(re),H=[];ie.forEach(_=>{let W=s(_,true);if(_.$op==="create")H.push(_);else if(_.$id){let $e=f(_.$objectPath),P=[];if(W.forEach(v=>{let Be=`${$e.includes("undefined")?"root":$e}.${_.$id}${Pr}${v}`,ne=$[Be];_[v].filter(Fe=>Fe.$op==="unlink"||Fe.$op==="delete"||Fe.$op==="update").length>0?ne?.$ids&&P.push({key:v,ids:ne.$ids}):P.push({key:v,ids:[""]});}),P.length===W.length&&!H.find(v=>v.$id===_.$id))H.push(_);else {let v={..._,$bzId:_.$tempId||`T4_${v4()}`};W.forEach(ne=>{let de=_[ne].filter(Fe=>Fe.$id);de.length>0?v[ne]=de:v[ne]=void 0;}),s(v,true).length>0&&H.push(v);}}else if(_.$objectPath){let $e=f(_.$objectPath),P=$[$e]?.$ids||[];P.forEach(v=>{let Be=[];W.forEach(ne=>{let de=`${$e}.${v}${Pr}${ne}`,Fe=$[de];Fe&&Be.push({key:ne,ids:Fe.$ids});}),W.length===0?P.filter(de=>!H.find(Fe=>Fe.$id===de)).forEach(de=>{H.push({..._,$id:de,$bzId:_.$tempId||`PQT2_${v4()}`});}):Be.length===W.length&&!H.find(ne=>ne.$id===v)&&(W.forEach(ne=>{let de=`${f(_.$objectPath)}.${v}${Pr}${ne}`,Fe=$[de]?.$ids||[],Do=_[ne].find(Xe=>!Xe.$id),Vr=[...Fe.map(Xe=>({...Do,$id:Xe,$objectPath:{beforePath:_.$objectPath.beforePath,ids:Xe,key:ne}})),..._[ne].filter(Xe=>Xe.$id)];Vr.length>0&&(_[ne]=Vr);}),H.push({..._,$id:v,$bzId:_.$tempId||`PQ3_${v4()}`}));});}else H.push(_);}),H.forEach(_=>{C.push(_);});}),[...C,...A,...k].filter(re=>s(re).length>0?true:re.$op!=="update").map(re=>{let ie={...re};return s(ie,true).forEach(H=>{let _=Array.isArray(ie[H])?ie[H]:[ie[H]],W=F(_);ie[H]=W;}),ie})};return F(b)})(Array.isArray(T)?T:[T]),O=b=>b.map(F=>{let S=s(F,true),M={...F};return S.forEach(R=>{let A=Array.isArray(F[R])?F[R]:[F[R]],k=[],V=[],C=[],ae={},De=or(t,F,R);A.filter(P=>P).forEach(P=>{P.$op==="replace"&&P.$id?(ae=P,Array.isArray(P.$id)?V=[...V,...P.$id]:V.push(P.$id)):P.$op==="create"&&De==="ONE"&&P.id?(ae=P,Array.isArray(P.id)?C=[...V,...P.id]:C.push(P.id)):k.push(P);});let Ae=f(ae.$objectPath),ie=h(Ae).map(P=>$[P]),H=[];ie.filter(P=>P!=null).forEach(P=>{H=[...H,...P?.$ids||[]];});let _=H.filter(P=>!V.includes(P)),W=V.filter(P=>!H.includes(P)),$e=xe(ae);_.length>0&&k.push({...ae,$op:"unlink",$id:_,$bzId:ae.$tempId||`T4_${v4()}`,id:void 0,...$e}),W.length>0&&W.forEach(P=>{k.push({...ae,$op:"link",$id:P,$bzId:ae.$tempId||`T5_${v4()}`,...$e});}),C.length>0&&C.forEach(P=>{k.push({...ae,$op:"create",id:P,$bzId:ae.$tempId||`T6_${v4()}`,...$e});}),M[R]=O(k);}),M}),j=m(O(m(Q)));(b=>produce(b,F=>traverse(F,S=>{let{key:M,value:R,parent:A,meta:k}=S;M&&A&&!M?.includes("$")&&M!=="$filter"&&!k.nodePath?.includes(".$filter.")&&(Array.isArray(R)||isObject(R))&&!Array.isArray(A)&&(Array.isArray(R)?R:[R]).forEach(C=>{let ae=C.$filter?{...C.$objectPath,key:C.$filterBzId}:C.$objectPath,De=f(ae),Ae=$[De],re=(_,W)=>_.every($e=>W.includes($e)),ie=C.$id?Array.isArray(C.$id)?re(C.$id,Ae?.$ids?Ae.$ids:[]):Ae?.$ids?.includes(C.$id):Ae,H=or(t,A,C.$objectPath.key);if(C.$op==="link"&&ie&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${f(C.$objectPath)}" because it is already occupied.`);if(C.$op)switch(C.$op){case "delete":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${C.$id}" because it is not linked to $id:"${A.$id}"`);break;case "update":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${C.$id}" because it is not linked to $id:"${A.$id}"`);break;case "unlink":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${C.$id}" because it is not linked to $id:"${A.$id}"`);break;case "link":if(ie)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${C.$id}" because it is already linked to $id:"${A.$id}"`);break;}});})))(j);let se=(b=>produce(b,F=>traverse(F,S=>{let{value:M,meta:R}=S;isObject(M)&&(M[Symbol.for("path")]=R.nodePath,M.$objectPath=void 0,M.$parentIsCreate=void 0);})))(j);return [...Array.isArray(se)?se:[se]].sort((b,F)=>b.$op==="create"&&F.$op!=="create"?-1:b.$op!=="create"&&F.$op==="create"?1:0)},Il=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var po=(e,t)=>produce(e,n=>zt(t,n)),zt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){for(let i of t)zt(e,i,r);return}let n=ee(e,r||t.$entity||t.$relation||t.$thing);for(let[i]of Object.entries(t))i.startsWith("$")||i.startsWith("%")||Cl(e,t,i,n);},Cl=(e,t,r,n)=>{let i=t[r];if(!i)return;let o=n.dataFields?.find(l=>l.path===r);if(o){o.contentType==="JSON"&&i!=null&&(t[r]=JSON.stringify(i));return}let s=n.linkFields?.find(l=>l.path===r);if(s){let l=s.oppositeLinkFieldsPlayedBy[0]?.thing;zt(e,i,l);return}if(!("refFields"in n&&n.refFields[r])&&n.thingType==="relation"){let l=n.roles[r];if(!l)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[d]=l.playedBy||[];if(!d)throw new Error(`Role ${l.path} in ${n} is not played by anything`);zt(e,i,d.thing);}};var ho=async(e,t)=>{let r=a=>{let{$filter:l,$thing:d,$bzId:c,$op:u,$id:p,$tempId:f}=a,h=ee(t,d),{usedDataFields:$}=ge(h,a),{idFields:E}=h,m=p||a[E[0]],y=(isArray(d)?d:[d]).map(le),B=ye(a,b=>b.startsWith("$")),g=ye(a,b=>!b.startsWith("$")),T=JSON.stringify(g),w=Object.entries(B).map(([b,F])=>b==="$tempId"?`'$tempId': '_:${F}'`:`'${b}': '${F}'`).join(","),Q=a[Tt],O=$.filter(b=>!E.includes(b)).map(b=>{let F=h.dataFields?.find(M=>M.path===b||M.dbPath===b);if(!F)throw new Error(`Data field schema not found for ${b}`);let S=a[b];return S===null?`${b} = NONE`:`${b} = ${Ge(S,F.contentType)}`}).filter(Boolean),j=`$\u27E8${f||c}\u27E9`,K=Q?.bzId?`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:m?isArray(m)?y.flatMap(b=>m.map(F=>`${b}:\u27E8${F}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${m}\u27E9`).join(", "):true,ce=(()=>{if(Q?.bzId){let b=`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return m?isArray(m)?`${b}[? $this.id() IN [${m.map(F=>`'${F}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${m}'] ]`:b}return m?isArray(m)?y.flatMap(b=>m.map(F=>`${b}:\u27E8${F}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${m}\u27E9`).join(", "):y.join(", ")})(),se=l?`WHERE ${be(Le(l,d,t))}`:"",I=O.length>0?`SET ${O.join(", ")}`:"",D=`VALUE (CREATE ONLY Delta SET input = ${T}, meta = {${w}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,Y="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return f?"":`LET ${j} = (SELECT VALUE id FROM ${ce} ${se});`;if(a.$op==="create"){if(isArray(m))throw new Error("Cannot create multiple things at once");let b=le(d);return `LET ${j} = (CREATE ONLY ${b}:\u27E8${m}\u27E9 ${I} RETURN ${D});`}if(a.$op==="update")return `LET ${j} = IF (${K}) THEN (UPDATE ${ce} ${I} ${se} RETURN ${D}) END;`;if(a.$op==="delete")return `LET ${j} = IF (${K}) THEN (DELETE ${ce} ${se} RETURN ${Y}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=ee(t,l),{usedRoleFields:f}=ge(p,a),h=`$\u27E8${u||d}\u27E9`,$="roles"in p?f.flatMap(y=>{let B=p.roles[y];if(!B)throw new Error(`Role field schema not found for ${y}`);let{cardinality:g}=B,T=isArray(a[y])?a[y].map(w=>`$\u27E8${w}\u27E9`):[`$\u27E8${a[y]}\u27E9`];if(g==="ONE"){if(T.length>1){let w=`array::filter(array::flatten([${T}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${y} = ((array::len(${w})==1) && ${w}[0]) || ${w}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${y} = ((type::is::array(${T[0]}) && array::len(${T[0]})==1) && ${T[0]}[0]) || ${T[0]}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(g==="MANY"){let w=`array::flatten([${T}])`;switch(c){case "link":return `${y} += ${w}`;case "unlink":return `${y} -= ${w}`;case "replace":return `${y} = ${w}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${g}`)}):[],E=$.length>0?`${$.join(", ")}`:"",m=E?`SET ${E}`:"";return `IF ${h} THEN (UPDATE ${h} ${m} RETURN VALUE id) END; ${h};`},i=a=>{let{$thing:l,$op:d}=a,c=ee(t,l),u=le(l),{usedRoleFields:p}=ge(c,a);if(!["create","delete"].includes(d))throw new Error("Arcs can only be created or deleted");let[f,h]=p,$=isArray(a[f])?a[f]:[a[f]],E=isArray(a[h])?a[h]:[a[h]];if(d==="create"){if(p.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let m=ye(a,j=>!j.startsWith("$")),B=`(CREATE ONLY Delta SET input = ${JSON.stringify(m)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,T=c.roles[f].cardinality==="MANY",Q=c.roles[h].cardinality==="MANY";return [`
128
+ `)},wr=(e,t,r)=>{let n=[],i=[],o=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][pe].contentType==="FLEX"&&o.push({path:e[c][pe].dbPath}),i.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=n.join(", "),l=`$metadata:{as:[${i.join(",")}]}`,d=[L(`$${t} as "${t}.${l}.$dataFields": ${s};`,r)];return o.length>0&&o.forEach(c=>{d.push(L(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),d},Rr=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:u,$filterByUnique:p,$thing:f,$sort:h,$offset:$,$limit:E}=a,y=a[oe],m=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(L(`"${r}.${m}.${a.$var}": {`,n)),s.push(L("match",o));let B=`${t}${Sr}${a.$var}`;if(s.push(L(`$${B} isa ${a.$thing};`,o)),s.push(L(`$${t} (${a.$var}: $${t}${Sr}${a.$var}) isa ${a.$intermediary};`,o)),a.$filter||a.$id){let T=Mt(i,a),w=a.$id?{[T]:a.$id}:{},M={...a.$filter,...w};s.push(jt({$filter:M,$var:B,$thing:a.$thing,schema:i,depth:o}));}let g=Mr({schema:i,$thing:f,$var:B,$sort:h,depth:o});if(g&&s.push(g.match),l){let T=`M_${v4()}`;s.push(L(`
129
+ ?queryPath${T} = "${y}";`,o)),s.push(L("fetch",o)),s.push(L(`?queryPath${T} as "queryPath";`,o));let w=l?.filter(j=>j.$fieldType==="data");w&&w.length>0&&s.push(...wr(w,B,o));let M=l?.filter(j=>j.$fieldType==="link");M&&M.length>0&&s.push(...Lr(M,B,`${t}.${a.$var}`,o,i));let D=l?.filter(j=>j.$fieldType==="role");D&&D.length>0&&s.push(...Rr(D,B,`${t}.${a.$var}`,o,i));}g&&s.push(g.sort),typeof $=="number"&&s.push(L(`offset ${$};`,o)),typeof E=="number"&&s.push(L(`limit ${E};`,o)),s.push(L("};",n));}return s},Lr=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:u,$filterByUnique:p,$playedBy:f,$thing:h,$sort:$,$offset:E,$limit:y}=a,m=a[oe],B=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(L(`"${r}.${B}.${a.$var}": {`,n)),s.push(L("match",o));let g=`${t}${Sr}${a.$var}`;if(s.push(L(`$${g} isa ${a.$thing};`,o)),a.$filter||a.$id){let w=Mt(i,a),M=a.$id?{[w]:a.$id}:{},D={...a.$filter,...M};s.push(jt({$filter:D,$var:g,$thing:a.$thing,schema:i,depth:o}));}let T=Mr({schema:i,$thing:h,$var:g,$sort:$,depth:o});if(T&&s.push(T.match),a.$target==="role"?s.push(L(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${g}) isa ${a.$intermediary};`,o)):s.push(L(`$${g} (${a.$plays}: $${t});`,o)),l){let w=`M_${v4()}`;s.push(L(`?queryPath${w} = "${m}";`,o)),s.push(L("fetch",o)),s.push(L(`?queryPath${w} as "queryPath";`,o));let M=l?.filter(K=>K.$fieldType==="data");M&&M.length>0&&s.push(...wr(M,g,o));let D=l?.filter(K=>K.$fieldType==="link");D&&D.length>0&&s.push(...Lr(D,g,`${t}.${a.$var}`,o,i));let j=l?.filter(K=>K.$fieldType==="role");j&&j.length>0&&s.push(...Rr(j,g,`${t}.${a.$var}`,o,i));}T&&s.push(T.sort),typeof E=="number"&&s.push(L(`offset ${E};`,o)),typeof y=="number"&&s.push(L(`limit ${y};`,o)),s.push(L("};",n));}return s},il=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},Mr=e=>{let{$var:t,$thing:r,schema:n,$sort:i,depth:o}=e,s=ee(n,r),a=[],l=[];if(i?.forEach(d=>{let c=il(d),u=s.dataFields?.find(h=>h.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let p=`${c.field}_${v4()}`;a.push(L("{",o)),a.push(L(`$${t} has ${u.dbPath} $${p}_1;`,o+1)),a.push(L("not {",o+1)),a.push(L(`$${t} has ${u.dbPath} $${p}_2;`,o+2)),a.push(L(`$${p}_2 < $${p}_1;`,o+2)),a.push(L("};",o+1)),a.push(L(`?${p}_ = $${p}_1;`,o+1)),a.push(L("} or {",o)),a.push(L(`not { $${t} has ${u.dbPath} $${p}_1; };`,o+1)),a.push(L(`?${p}_ = "~";`,o+1)),a.push(L("};",o)),a.push(L(`?${p} = ?${p}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${p} ${f}`);}),a.length!==0)return {match:a.join(""),sort:L(`sort ${l.join(", ")};`,o)}};var Hi=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:i,rawTqlRes:o}=e;if(!t)throw new Error("BQL request not enriched");if(!o)throw new Error("TQL query not executed");return o.map((s,a)=>{let l=r[a],d=t[a];return sl(s,l,d,n,i)})},sl=(e,t,r,n,i)=>e.length===0?null:r.$filterByUnique?vi(e[0],t,n,i):e.map(o=>vi(o,t,n,i)),vi=(e,t,r,n)=>{let{dataFields:i,currentSchema:o,linkFields:s,roleFields:a,schemaValue:l}=Qr(e,r),d=Dr(i,o,n),c=Or(s,r,n),u=Ar(a,r,n),p=t?.$fields?.every(h=>!o?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...u,...l,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?d.id:t.$id}:{},...p?Object.fromEntries(Object.entries(d).filter(([h])=>!o?.idFields?.includes(h))):d}},Qr=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),i=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");if(i?.length>0)for(let f of i){let h=f.replace(/\.\$multiVal$/,""),$=e[f][0][h].attribute;e[n][h]=$;}let o=e[n],s=n.split(".")[n.split(".").length-2];if(o.$metaData=s,o.length===0)throw new Error("No dataFields");let a=o.type,l={$thing:a.label,$thingType:a.root,[oe]:e.queryPath.value},d={[`$${l.$thingType}`]:l.$thing},c=V(t,d),u=r.filter(f=>{let h=Ee(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(f=>{let h=Ee(f.split(".").pop()),$=Ee(c.linkFields?.find(E=>E.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),p=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(f=>{let h=Ee(f.split(".").pop());return {$roleFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:o,schemaValue:l,currentSchema:c,linkFields:u,roleFields:p}},Dr=(e,t,r)=>{let{$metaData:n}=e,{as:i}=al(n),o=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).flatMap(([s,a])=>{let l=t.dataFields?.find(p=>p.path===s||p.dbPath===s),d=s==="id",c=Array.isArray(i)?i.find(p=>p[s])?.[s]:s,u;if(l?.cardinality==="ONE"){if(u=a[0]?a[0].value:r.query?.returnNulls?null:void 0,l.contentType==="DATE"||l.contentType==="FLEX"&&a[0].type.value_type==="datetime"?u=u&&`${u}Z`:l.contentType==="JSON"&&(u=u&&JSON.parse(u)),d)return [[c,u],["$id",u]].filter(([p,f])=>f!==void 0)}else if(l?.cardinality==="MANY"){if(!isArray(a))throw new Error("Typedb fetch has changed its format");if(a.length===0)return r.query?.returnNulls?[[c,null]]:[];l.contentType==="DATE"?u=a.map(p=>`${p.value}Z`):l.contentType==="FLEX"?u=a.map(p=>p.type.value_type==="datetime"?`${p.value}Z`:p.value):l.contentType==="JSON"?u=a.map(p=>p.value&&JSON.parse(p.value)):u=a.map(p=>p.value);}return [[c,u]].filter(([p,f])=>f!==void 0)});return Object.fromEntries([...o])},Ar=(e,t,r)=>{let n={};for(let i of e){let{$roleFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:u}=Ji(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:E,roleFields:y,schemaValue:m}=Qr(f,t),B=Dr(h,$,r);if(d==="T")return B.id;let g=Or(E,t,r),T=Ar(y,t,r),w={...B};if(c==="true"&&$?.idFields)for(let M of $.idFields)delete w[M];return {...w,...g,...T,...m}});p.length>0?n[l]=a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls&&(n[l]=null);}return n},Or=(e,t,r)=>{let n={};for(let i of e){let{$linkFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:u}=Ji(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:E,roleFields:y,schemaValue:m}=Qr(f,t),B=Dr(h,$,r);if(d==="T")return B.id;let g=Or(E,t,r),T=Ar(y,t,r),w={...B};if(c==="true")for(let M of $.idFields??[])delete w[M];return {...w,...g,...T,...m}});n[l]=p.length>0?a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls?null:void 0;}return n},Ji=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,i=/filterByUnique:([a-zA-Z0-9_\-·]+)/,o=e.match(t),s=e.match(r),a=e.match(n),l=e.match(i);return {as:o?o[1]:null,justId:s?s[1]:null,idNotIncluded:a?a[1]:null,filterByUnique:l?l[1]:null}},al=e=>{try{let r=(i=>{let o=i.replace("$metadata:","");return o=o.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),o=o.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,a,l)=>/^{.*}$/.test(l)?`:${l}`:`:${a}"${l}"`),o=o.replace(/\[([^\]]+)\]/g,(s,a)=>`[${a.split(",").map(l=>l.trim().startsWith("{")&&l.trim().endsWith("}")?l.trim():`"${l.trim()}"`).join(",")}]`),o})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var Vt=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,i=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!i)throw new Error("Client not found");n=await i.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:i,session:n});}return {client:i,session:n}};var Ki=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,i=new TypeDBOptions;i.infer=true;let{session:o}=await Vt(r,n),s=await o.transaction(TransactionType.READ,i),[a,l]=await tryit(parallel)(t.length,t,async d=>await s.query.fetch(d).collect());if(a){await s.rollback();let d=a;throw new Error(`Error running TQL query: ${d.errors}`)}return await s.close(),l};var hl=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Nr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,fl=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,$l=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,ct=x("error","error",q((e,t)=>({...e,error:t.error}))),ml=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),rt(e.bql.raw,e.schema)),x("done","build",q(hl)),ct),build:U(async e=>Wi({queries:e.bql.queries??[],schema:e.schema}),x("done","run",q(fl)),ct),run:U(async e=>Ki({dbHandles:e.handles,tqlRequest:Ee(e.tql.queries),config:e.config}),x("done","parse",q($l)),ct),parse:U(async e=>Hi({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries??[],schema:e.schema,config:e.config,rawTqlRes:Ee(e.tql.res)}),x("done","postHooks",q(Nr)),ct),postHooks:U(async e=>kt(e.schema,Ee(e.bql.queries),Ee(e.bql.res)),x("done","clean",q(Nr)),ct),clean:U(async e=>It(e.config,Ee(e.bql.res)),x("done","success",q(Nr)),ct),success:me(),error:me()},e=>e),yl=async e=>new Promise((t,r)=>{Re(ml,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Yi=async(e,t,r,n)=>yl({bql:{raw:e},tql:{},schema:t,config:r,handles:n,error:null});var gl=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,El=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Xi=x("error","error",q((e,t)=>({...e,error:t.error}))),Bl=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),rt(e.bql.raw,e.schema)),x("done","adapter",q(gl)),Xi),adapter:U(async e=>{let t={};e.bql.raw?.forEach((a,l)=>{let d=e.bql.raw[l],c="$thing"in a?a.$thing:"$entity"in a?a.$entity:"$relation"in a?a.$relation:void 0;if(!c)throw new Error(`No $thing found in query ${JSON.stringify(a,null,2)}`);let u=ee(e.schema,c),{id:p}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[p]){let h=e.handles.typeDB?.get(p)?.client;if(!h)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[p]={db:"typeDB",client:h,rawBql:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[p]){let h=e.handles.surrealDB?.get(p)?.client;if(!h)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[p]={db:"surrealDB",client:h,rawBql:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let f=t[p];f.rawBql.push(d),f.indices.push(l);});let r=Object.values(t),n=r.map(a=>{if(a.db==="typeDB")return Yi(a.rawBql,e.schema,e.config,e.handles);if(a.db==="surrealDB")return e.config.query?.legacySurrealDBAdapter?$i(a.rawBql,e.schema,e.config,a.client):Vi(a.rawBql,e.draftSchema,e.config,a.client);throw new Error(`Unsupported DB "${JSON.stringify(a,null,2)}"`)}),i=await Promise.all(n),o=r.flatMap((a,l)=>{let d=i[l];return a.indices.map((c,u)=>({index:c,result:d[u]}))});return o.sort((a,l)=>a.index<l.index?-1:a.index>l.index?1:0),o.map(({result:a})=>a)},x("done","success",q(El)),Xi),success:me(),error:me()},e=>e),Fl=async e=>new Promise((t,r)=>{Re(Bl,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),dt=async(e,t,r,n,i)=>Fl({bql:{raw:e},schema:t,draftSchema:r,config:n,handles:i,error:null});var to=async(e,t,r,n,i)=>{let o=Array.isArray(e)?e:[e],s=o.map(d=>Ir(d,true)),l=(await dt(s,t,r,n,i)).bql.res;return o.map((d,c)=>{let u=ee(t,d.$thing);return no({mut:d,node:l[c],schema:t,thing:u})})},ro=new Set(["$op","$bzId","$parentKey"]),Tl=new Set(["$relation","$entity","$id",...ro]),Ir=(e,t)=>{let r={};e.$fields?.forEach(i=>{typeof i=="string"?r[i]=i:r[i.$path]=i;});let n={};for(let i in e){if(ro.has(i)||Tl.has(i)&&!t)continue;let o=e[i];i.startsWith("$")?n[i]=o:Array.isArray(o)?o[0]&&typeof o[0]=="object"&&(r[i]={$path:i,...Ir(o[0],false)}):isObject(o)&&(r[i]={$path:i,...Ir(o,false)});}return n.$fields=Object.values(r),n},no=e=>{let{mut:t,node:r,schema:n,thing:i}=e,o=oo(i),s=wl(r);if(Array.isArray(t))return t.map(l=>{let d=s[l.$id];return d?Zi({mut:l,node:d,schema:n,thing:i,...o}):l});let a=s[t.$id];return Zi({mut:t,node:a,schema:n,thing:i,...o})},Zi=e=>{let{mut:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,{$fields:l,...d}=t;if(!r)return d;let c=io({$fields:t.$fields,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}),u={...d,[et]:c};for(let p in t){if(p.startsWith("$"))continue;let f=t[p];if(o[p]||!f||typeof f!="object"){u[p]=f;continue}let $=s[p]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[p]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${p}"`);let E=ee(n,$);u[p]=no({mut:f,schema:n,node:r[p],thing:E});}return u},io=e=>{let{$fields:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,l=t||Sl(i),d={$id:r.$id};return l.forEach(c=>{let u=typeof c!="string",p=u?c.$path:c,f=r[p];if(o[p]){d[p]=f;return}let $=s[p]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[p]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${p}"`);if(!u){f&&(d[p]=Array.isArray(f)?f.map(Gi):Gi(f));return}let E=ee(n,$),y=oo(E);d[p]=Array.isArray(f)?f.map(m=>eo({...y,$fields:c.$fields,value:m,schema:n,thing:E})):eo({...y,$fields:c.$fields,value:f,schema:n,thing:E});}),d},Sl=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},Gi=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},eo=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 io({...e,node:t})},oo=e=>{let t=Object.fromEntries(e.dataFields?.map(i=>[i.path,i])||[]),r=Object.fromEntries(e.linkFields?.map(i=>[i.path,i])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},wl=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 so=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(s,a)=>{if(!s?.$thing)return;let{$op:l,$bzId:d,$tempId:c}=s,u=t.relations[s.$thing]||t.entities[s.$thing];if(!u)throw new Error(`[Internal] No schema found for ${s.$thing}`);let p=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:h,usedRoleFields:$,usedRefFields:E}=ge(u,s);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let m={...ye(s,B=>![...$,...h,...E].includes(B)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[wt]:p}};r.things.push(m);}let y={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let m=ye(s,B=>isSymbol(B)||B.startsWith("$"));for(let B of $){if(isArray(s[B]))for(let T of s[B])n(T,{bzId:d,edgeField:B,tempId:c});else n(s[B],{bzId:d,edgeField:B,tempId:c});let g=(isArray(s[B])?s[B]:[s[B]]).filter(Boolean);for(let[T,w]of Object.entries(y)){let M=g.filter(D=>w.includes(D.$op)).map(D=>D.$bzId);M.length>0&&r.edges.push({...m,[B]:M,$op:T});}}}if(h)for(let m of h){if(isArray(s[m]))for(let T of s[m])n(T,{bzId:d,edgeField:m,tempId:c});else n(s[m],{bzId:d,edgeField:m,tempId:c});let B=u.linkFields?.find(T=>T.path===m),g=isArray(s[m])?s[m]:[s[m]];if(B.target==="relation")for(let[T,w]of Object.entries(y)){let M=g.filter(D=>w.includes(D.$op));for(let D of M){let j=ye(D,K=>isSymbol(K)||K.startsWith("$"));r.edges.push({...j,[B.plays]:d,$op:T});}}if(B.target==="role"){let T={create:["link","create"],delete:["unlink","delete"],replace:["replace"]};for(let[w,M]of Object.entries(T)){let D=g.filter(j=>M.includes(j.$op));if(D.length!==0)for(let j of D){let K={$thing:B.relation,$thingType:"relation",$bzId:`arc_${j.$bzId}`,[B.plays]:d,[B.oppositeLinkFieldsPlayedBy[0].plays]:j.$bzId,$op:w};r.arcs.push(K);}}}}if(E)for(let m of E){if(isArray(s[m]))for(let w of s[m])n(w,{bzId:d,edgeField:m,tempId:c});else n(s[m],{bzId:d,edgeField:m,tempId:c});let B=(isArray(s[m])?s[m]:[s[m]]).filter(w=>w!=null),g=ye(s,w=>isSymbol(w)||w.startsWith("$")),T=B.map(w=>w.$op?`$\u27E8${w.$bzId}\u27E9`:Ge(w,"FLEX"));T.length>0&&r.references.push({...g,[m]:T,$op:"replace"});}},i=Array.isArray(e)?e:[e];for(let s of i)n(s);let o=[...r.edges].sort((s,a)=>{let l=["unlink","link"];return l.indexOf(s.$op)-l.indexOf(a.$op)});return {...r,edges:o}};var uo=async(e,t)=>{let r=c=>{let u=[],p=[],f=y=>{if(y.$id)return y.$id;let m=V(t,y),{idFields:B}=m;if(!B)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[g]=B;if(!g)throw new Error(`no idField: ${JSON.stringify(y)}`);let T=m.dataFields?.find(D=>D.path===g),w=nt({currentThing:y,fieldSchema:T,mandatoryDependencies:true}),M=y[g]||y.$id||w;if(!M)throw new Error(`no idValue: ${JSON.stringify(y)}`);return M},h=y=>{if(y.$op==="create"){let m=f(y);if(u.find(B=>B.$id===m&&B.$op==="create"))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(y)}`);u.push({...y,$id:m});return}y.$tempId&&y.$op==="match"||u.push(y);},$=y=>{if(y.$op==="create"){let m=f(y);if(u.find(B=>B.$id===m&&B.$op==="create"))throw new Error(`Duplicate id ${m} for edge ${JSON.stringify(y)}`);p.push({...y,$id:m});return}p.push(y);};return traverse(c,({value:y,parent:m,meta:B})=>{if(!isObject(y))return;let g=y;if(!B.nodePath?.includes(".$filter")&&g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(g)}`);let T=V(t,g),{dataFields:w,roleFields:M,linkFields:D,refFields:j,usedFields:K}=ge(T,g),ce=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let A=K.filter(S=>w?.includes(S)),Y=K.filter(S=>M?.includes(S)),b=K.filter(S=>D?.includes(S)),F=K.filter(S=>j?.includes(S));if(A.length>0)return "update";if(Y.length>0||b.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,w||[""])),$op:ce(),$bzId:g.$bzId};h(se);let I=g[Oe];if(I?.[v].fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...g,$op:"match"});}let A=I.$things.includes(g.$thing),Y=A?g.$bzId:`LT_${v4()}`,F=Dn(c,m,B).$bzId;if(!F)throw new Error("No parent id found");let S=()=>g.$op==="delete"?A?"match":"delete":g.$op==="unlink"?A?"unlink":"delete":g.$op==="link"||g.$op==="create"?A?"link":"create":g.$op==="replace"?"replace":"match",Q=V(t,{$thing:I.relation,$thingType:"relation"});if(!Object.keys(Q.roles).includes(I.plays))throw new Error(`[Wrong format] Field ${I.plays} is not a role of relation ${I.relation}`);let O={$bzId:Y,$thing:A?g.$thing:I.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:S(),...A?{}:{[I.path]:g.$bzId},[I.plays]:F,[Oe]:I,[ve]:"linkField"};$(O),(g.$op==="unlink"||S()==="unlink")&&A&&$({$thing:I.relation,$thingType:"relation",$bzId:Y,$op:"match",[I.plays]:F,[Oe]:I,[ve]:"linkField"});}if(g.$thingType==="relation"){let A=ye(g,(F,S)=>M.includes(F)),Y=mapEntries(A,(F,S)=>isArray(S)?[F,S]:isObject(S)?[F,S.$bzId]:[F,S]),b=ye(y,(F,S)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(A).filter(F=>!F.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let F=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=V(t,g).roles,Q=mapEntries(Y,(O,k)=>{let z=S[O]?.cardinality;if(!z)throw new Error(`Role ${O} not found in schema`);return Array.isArray(k)?z==="ONE"?k.length>1?[O,k.map(C=>C.$bzId||C)]:[O,k[0].$bzId||k[0]]:[O,k.map(C=>C.$bzId||C)]:[O,k.$bzId||k]}),R={...b,$thing:g.$thing,$thingType:"relation",$op:F(),...Q,$bzId:g.$bzId,[ve]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(A).length>0){Object.entries(A).forEach(([S,Q])=>{let R=isArray(Q)?Q:[Q],O=k=>k==="create"||k==="replace"?"link":k;R.forEach(k=>{if(!k)return;let z=O(k.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");let C={...b,$thing:g.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[S]:k.$bzId,$bzId:g.$bzId,[ve]:"roleField"};$(C);});});}}}}}),[u,p]},[n,i]=r(e),o=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let p=c.findIndex(f=>f.$bzId===u.$bzId);if(p===-1)return [...c,u];if(c[p].$op==="create"&&u.$op==="match")return c;if(c[p].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,p),u,...c.slice(p+1)];if(c[p].$op==="update"&&u.$op==="update")return [...c.slice(0,p),{...c[p],...u},...c.slice(p+1)];if(c[p].$op==="update"&&u.$op==="match"||c[p].$op==="match"&&u.$op==="update")return [...c.slice(0,p),{...c[p],...u,$op:"update"},...c.slice(p+1)];if(c[p].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[p].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[p].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[p].$op}. Current: ${u.$op}`)},[]),s=i.reduce((c,u)=>{let p=c.find(f=>(f.$id&&f.$id===u.$id||f.$bzId&&f.$bzId===u.$bzId)&&f.$thing===u.$thing&&f.$op===u.$op);if(p){let f={...p};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let E=p[$],y=u[$];Array.isArray(E)&&Array.isArray(y)?f[$]=Array.from(new Set([...E,...y])):!Array.isArray(E)&&Array.isArray(y)?E!==void 0?f[$]=Array.from(new Set([E,...y])):f[$]=y:Array.isArray(E)&&!Array.isArray(y)?y!==void 0&&(f[$]=Array.from(new Set([...E,y]))):E!==null&&y!==null&&E!==void 0&&y!==void 0?f[$]=Array.from(new Set([E,y])):E==null&&(f[$]=y);}),[...c.filter($=>!(($.$id&&$.$id===u.$id||$.$bzId&&$.$bzId===u.$bzId)&&$.$thing===u.$thing&&$.$op===u.$op)),f]}return [...c,u]},[]);o.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&s.filter(u=>u.$bzId===c.$bzId||u.$tempId&&u.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(An(c))}`)}});let a=[...o,...s],l=new Set(a.filter(c=>c.$tempId).map(c=>c.$tempId)),d=Array.from(l).filter(c=>!a.some(u=>u.$tempId===c&&u.$op==="create"));if(d.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${d.join(", ")}`);return {mergedThings:o,mergedEdges:s}};var Cr="___",Al=Symbol.for("grandChildOfCreate"),po=async(e,t,r,n,i)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],s=(b,F)=>Object.keys(b).filter(S=>!S.startsWith("$")&&!o.includes(S)&&b[S]!==void 0?F?!V(t,b).dataFields?.find(R=>R.path===S):true:false);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===false)return;let a=[];if(traverse(e,({parent:b,key:F,value:S})=>{b&&F&&!F.includes("$")&&!o.includes(F)&&isObject(b)?(Array.isArray(b[F])?b[F]:[b[F]]).forEach(R=>{if(isObject(R)){if(b.$op!=="create")a.includes(R.$op)||a.push(R.$op);else if(R.$op==="delete"||R.$op==="unlink")throw new Error(`Cannot ${R.$op} under a create`)}}):!b&&isObject(S)&&(a.includes(S.$op)||a.push(S.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let d=(b=>{let F=(S,Q)=>{let R=[],O={},k=["$op","$bzId","$parentKey"],z=["$relation","$entity","$id",...k];for(let C in S)if(!k.includes(C)&&!(z.includes(C)&&!Q))if(!C.includes("$")&&(isObject(S[C])||Array.isArray(S[C]))){let ae=Ol(S[C]);if(Array.isArray(ae)&&ae.length>0)ae.forEach(De=>{let Ae={$path:C,...F(De),...De.$filter&&{$as:De.$bzId}};R.find(re=>re.$path===Ae.$path&&!re.$filter)||(R=[...R,Ae]);});else {let De={$path:C,...F(ae),...!ae.$filter&&{$as:ae.$bzId}};R=[...R,De];}}else O[C]=S[C];return {...O,$fields:R}};return b.map(S=>F(S,true))})(Array.isArray(e)?e:[e]),u=(await dt(d,t,r,{...n,query:{...n.query,returnNulls:true}},i)).bql.res,p=(b,F)=>{let S=b.$id||b.id||b.$bzId;if(b.$objectPath){let{$objectPath:Q}=b,R=Q?.beforePath||"root",O=Array.isArray(Q.ids)?`[${Q.ids}]`:Q.ids;return {beforePath:`${R}.${O}___${Q.key}`,ids:S,key:F}}return {beforePath:"root",ids:S,key:F}},f=(b,F)=>{let S=b?.beforePath||"root";if(typeof S!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let Q=(Array.isArray(b?.ids)?`[${b?.ids}]`:b?.ids);return `${S}.${Q}___${b?.key}`},h=b=>{if(b.includes("[")&&b.includes("]")){let[F,S,Q]=b.split(/[[\]]/);return S.split(",").map(O=>`${F}${O}${Q}`)}return [b]},$={};(b=>produce(b,F=>traverse(F,({key:S,parent:Q})=>{if(Q&&S&&Q.$id&&!S.includes("$")){let R=p(Q,S),O=f(R);if(Array.isArray(Q[S])){let k=[];Q[S].forEach(z=>{isObject(z)?(z.$objectPath=R,k.push(z.$id.toString())):z&&k.push(z.toString());}),$[O]={$objectPath:R,$ids:k};}else {let k=Q[S];isObject(k)?($[O]={$objectPath:R,$ids:[k.$id.toString()]},k.$objectPath=R):k?$[O]={$objectPath:R,$ids:[k.toString()]}:k===null&&($[O]=null);}}})))(u||{});let y=b=>produce(b,F=>traverse(F,({key:S,value:Q,parent:R})=>{R&&S&&!S.includes("$")&&(Array.isArray(Q)||isObject(Q))&&!Array.isArray(R)&&(Array.isArray(R[S])?R[S].forEach(O=>{typeof O!="string"&&(O.$objectPath=p(R,S),O.$parentIsCreate=R.$op==="create",O[Al]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")]);}):isObject(R[S])&&(R[S].$parentIsCreate=R.$op==="create",R[S][Symbol.for("grandChildOfCreate")]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")],R[S].$objectPath=p(R,S)));})),m=y(e),B=b=>{let F=[];return b.forEach(Q=>{if(!Q.$id&&!Q.id&&!Q.$tempId)if(Q.$filter){let R=f({...Q.$objectPath,key:Q.$bzId}),O=$[R];O&&(Array.isArray(O.$ids)?O.$ids:[O.$ids]).forEach(z=>{let C={...Q,$id:z,$bzId:`T4_${v4()}`,$filterBzId:Q.$bzId};F.push(C);});}else {let R=f(Q.$objectPath),O=$[R];O?O?.$ids?.forEach(k=>{let z={...Q,$id:k,$bzId:`T4_${v4()}`};F.push(z);}):F.push(Q);}else F.push(Q);}),F.map(Q=>{let R={...Q};return s(R,true).forEach(O=>{let k=Array.isArray(R[O])?R[O]:[R[O]],z=B(k);R[O]=z;}),R})},g=B(Array.isArray(m)?m:[m]),T=y(g),M=(b=>{let F=S=>{let Q=re=>{let ie=[],J=[],_=[];return re.forEach(W=>{let $e=s(W,true);if($e.length>0){let P=false;$e.forEach(H=>{(Array.isArray(W[H])?W[H]:[W[H]]).filter(de=>!de.$id&&!de.id&&typeof W=="object").length&&(P=true);}),P?ie.push(W):J.push(W);}else W.$id?_.push({...W,$bzId:W.$tempId||W.$bzId}):_.push({...W,$bzId:W.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ie,operationWithoutMultiples:J,otherOps:_}},{operationWithMultiples:R,operationWithoutMultiples:O,otherOps:k}=Q(S),z=re=>{let J=(()=>{let H={};for(let Be in re){let ne=V(t,re);!Be.startsWith("$")&&ne.dataFields?.find(de=>de.path===Be)&&(H[Be]=re[Be]);}return H})(),_=Object.keys(re),W=s(re,true),$e=[],P=(H,Be)=>{if(H===W.length){let de={...Be};_.forEach(Fe=>{Fe.startsWith("$")&&(de[Fe]=re[Fe]);}),$e.push({...de,...J});return}let ne={...Be,[W[H]]:re[W[H]],...xe(Be),...J};P(H+1,ne),P(H+1,Be);};return P(0,{...xe(re)}),$e},C=[];return R.forEach(re=>{let ie=z(re),J=[];ie.forEach(_=>{let W=s(_,true);if(_.$op==="create")J.push(_);else if(_.$id){let $e=f(_.$objectPath),P=[];if(W.forEach(H=>{let Be=`${$e.includes("undefined")?"root":$e}.${_.$id}${Cr}${H}`,ne=$[Be];_[H].filter(Fe=>Fe.$op==="unlink"||Fe.$op==="delete"||Fe.$op==="update").length>0?ne?.$ids&&P.push({key:H,ids:ne.$ids}):P.push({key:H,ids:[""]});}),P.length===W.length&&!J.find(H=>H.$id===_.$id))J.push(_);else {let H={..._,$bzId:_.$tempId||`T4_${v4()}`};W.forEach(ne=>{let de=_[ne].filter(Fe=>Fe.$id);de.length>0?H[ne]=de:H[ne]=void 0;}),s(H,true).length>0&&J.push(H);}}else if(_.$objectPath){let $e=f(_.$objectPath),P=$[$e]?.$ids||[];P.forEach(H=>{let Be=[];W.forEach(ne=>{let de=`${$e}.${H}${Cr}${ne}`,Fe=$[de];Fe&&Be.push({key:ne,ids:Fe.$ids});}),W.length===0?P.filter(de=>!J.find(Fe=>Fe.$id===de)).forEach(de=>{J.push({..._,$id:de,$bzId:_.$tempId||`PQT2_${v4()}`});}):Be.length===W.length&&!J.find(ne=>ne.$id===H)&&(W.forEach(ne=>{let de=`${f(_.$objectPath)}.${H}${Cr}${ne}`,Fe=$[de]?.$ids||[],Ao=_[ne].find(Ze=>!Ze.$id),Vr=[...Fe.map(Ze=>({...Ao,$id:Ze,$objectPath:{beforePath:_.$objectPath.beforePath,ids:Ze,key:ne}})),..._[ne].filter(Ze=>Ze.$id)];Vr.length>0&&(_[ne]=Vr);}),J.push({..._,$id:H,$bzId:_.$tempId||`PQ3_${v4()}`}));});}else J.push(_);}),J.forEach(_=>{C.push(_);});}),[...C,...O,...k].filter(re=>s(re).length>0?true:re.$op!=="update").map(re=>{let ie={...re};return s(ie,true).forEach(J=>{let _=Array.isArray(ie[J])?ie[J]:[ie[J]],W=F(_);ie[J]=W;}),ie})};return F(b)})(Array.isArray(T)?T:[T]),D=b=>b.map(F=>{let S=s(F,true),Q={...F};return S.forEach(R=>{let O=Array.isArray(F[R])?F[R]:[F[R]],k=[],z=[],C=[],ae={},De=or(t,F,R);O.filter(P=>P).forEach(P=>{P.$op==="replace"&&P.$id?(ae=P,Array.isArray(P.$id)?z=[...z,...P.$id]:z.push(P.$id)):P.$op==="create"&&De==="ONE"&&P.id?(ae=P,Array.isArray(P.id)?C=[...z,...P.id]:C.push(P.id)):k.push(P);});let Ae=f(ae.$objectPath),ie=h(Ae).map(P=>$[P]),J=[];ie.filter(P=>P!=null).forEach(P=>{J=[...J,...P?.$ids||[]];});let _=J.filter(P=>!z.includes(P)),W=z.filter(P=>!J.includes(P)),$e=xe(ae);_.length>0&&k.push({...ae,$op:"unlink",$id:_,$bzId:ae.$tempId||`T4_${v4()}`,id:void 0,...$e}),W.length>0&&W.forEach(P=>{k.push({...ae,$op:"link",$id:P,$bzId:ae.$tempId||`T5_${v4()}`,...$e});}),C.length>0&&C.forEach(P=>{k.push({...ae,$op:"create",id:P,$bzId:ae.$tempId||`T6_${v4()}`,...$e});}),Q[R]=D(k);}),Q}),j=y(D(y(M)));(b=>produce(b,F=>traverse(F,S=>{let{key:Q,value:R,parent:O,meta:k}=S;Q&&O&&!Q?.includes("$")&&Q!=="$filter"&&!k.nodePath?.includes(".$filter.")&&(Array.isArray(R)||isObject(R))&&!Array.isArray(O)&&(Array.isArray(R)?R:[R]).forEach(C=>{let ae=C.$filter?{...C.$objectPath,key:C.$filterBzId}:C.$objectPath,De=f(ae),Ae=$[De],re=(_,W)=>_.every($e=>W.includes($e)),ie=C.$id?Array.isArray(C.$id)?re(C.$id,Ae?.$ids?Ae.$ids:[]):Ae?.$ids?.includes(C.$id):Ae,J=or(t,O,C.$objectPath.key);if(C.$op==="link"&&ie&&J==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${f(C.$objectPath)}" because it is already occupied.`);if(C.$op)switch(C.$op){case "delete":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${C.$id}" because it is not linked to $id:"${O.$id}"`);break;case "update":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${C.$id}" because it is not linked to $id:"${O.$id}"`);break;case "unlink":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${C.$id}" because it is not linked to $id:"${O.$id}"`);break;case "link":if(ie)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${C.$id}" because it is already linked to $id:"${O.$id}"`);break;}});})))(j);let se=(b=>produce(b,F=>traverse(F,S=>{let{value:Q,meta:R}=S;isObject(Q)&&(Q[Symbol.for("path")]=R.nodePath,Q.$objectPath=void 0,Q.$parentIsCreate=void 0);})))(j);return [...Array.isArray(se)?se:[se]].sort((b,F)=>b.$op==="create"&&F.$op!=="create"?-1:b.$op!=="create"&&F.$op==="create"?1:0)},Ol=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var ho=(e,t)=>produce(e,n=>Ut(t,n)),Ut=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){for(let i of t)Ut(e,i,r);return}let n=ee(e,r||t.$entity||t.$relation||t.$thing);for(let[i]of Object.entries(t))i.startsWith("$")||i.startsWith("%")||Il(e,t,i,n);},Il=(e,t,r,n)=>{let i=t[r];if(!i)return;let o=n.dataFields?.find(l=>l.path===r);if(o){o.contentType==="JSON"&&i!=null&&(t[r]=JSON.stringify(i));return}let s=n.linkFields?.find(l=>l.path===r);if(s){let l=s.oppositeLinkFieldsPlayedBy[0]?.thing;Ut(e,i,l);return}if(!("refFields"in n&&n.refFields[r])&&n.thingType==="relation"){let l=n.roles[r];if(!l)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[d]=l.playedBy||[];if(!d)throw new Error(`Role ${l.path} in ${n} is not played by anything`);Ut(e,i,d.thing);}};var fo=async(e,t)=>{let r=a=>{let{$filter:l,$thing:d,$bzId:c,$op:u,$id:p,$tempId:f}=a,h=ee(t,d),{usedDataFields:$}=ge(h,a),{idFields:E}=h,y=p||a[E[0]],m=(isArray(d)?d:[d]).map(le),B=ye(a,b=>b.startsWith("$")),g=ye(a,b=>!b.startsWith("$")),T=JSON.stringify(g),w=Object.entries(B).map(([b,F])=>b==="$tempId"?`'$tempId': '_:${F}'`:`'${b}': '${F}'`).join(","),M=a[wt],D=$.filter(b=>!E.includes(b)).map(b=>{let F=h.dataFields?.find(Q=>Q.path===b||Q.dbPath===b);if(!F)throw new Error(`Data field schema not found for ${b}`);let S=a[b];return S===null?`${b} = NONE`:`${b} = ${Ge(S,F.contentType)}`}).filter(Boolean),j=`$\u27E8${f||c}\u27E9`,K=M?.bzId?`array::flatten($\u27E8${M.bzId}\u27E9.\u27E8${M.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:y?isArray(y)?m.flatMap(b=>y.map(F=>`${b}:\u27E8${F}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):true,ce=(()=>{if(M?.bzId){let b=`array::flatten($\u27E8${M.bzId}\u27E9.\u27E8${M.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return y?isArray(y)?`${b}[? $this.id() IN [${y.map(F=>`'${F}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${y}'] ]`:b}return y?isArray(y)?m.flatMap(b=>y.map(F=>`${b}:\u27E8${F}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):m.join(", ")})(),se=l?`WHERE ${be(Le(l,d,t))}`:"",I=D.length>0?`SET ${D.join(", ")}`:"",A=`VALUE (CREATE ONLY Delta SET input = ${T}, meta = {${w}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,Y="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return f?"":`LET ${j} = (SELECT VALUE id FROM ${ce} ${se});`;if(a.$op==="create"){if(isArray(y))throw new Error("Cannot create multiple things at once");let b=le(d);return `LET ${j} = (CREATE ONLY ${b}:\u27E8${y}\u27E9 ${I} RETURN ${A});`}if(a.$op==="update")return `LET ${j} = IF (${K}) THEN (UPDATE ${ce} ${I} ${se} RETURN ${A}) END;`;if(a.$op==="delete")return `LET ${j} = IF (${K}) THEN (DELETE ${ce} ${se} RETURN ${Y}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=ee(t,l),{usedRoleFields:f}=ge(p,a),h=`$\u27E8${u||d}\u27E9`,$="roles"in p?f.flatMap(m=>{let B=p.roles[m];if(!B)throw new Error(`Role field schema not found for ${m}`);let{cardinality:g}=B,T=isArray(a[m])?a[m].map(w=>`$\u27E8${w}\u27E9`):[`$\u27E8${a[m]}\u27E9`];if(g==="ONE"){if(T.length>1){let w=`array::filter(array::flatten([${T}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${m} = ((array::len(${w})==1) && ${w}[0]) || ${w}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${m} = ((type::is::array(${T[0]}) && array::len(${T[0]})==1) && ${T[0]}[0]) || ${T[0]}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(g==="MANY"){let w=`array::flatten([${T}])`;switch(c){case "link":return `${m} += ${w}`;case "unlink":return `${m} -= ${w}`;case "replace":return `${m} = ${w}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${g}`)}):[],E=$.length>0?`${$.join(", ")}`:"",y=E?`SET ${E}`:"";return `IF ${h} THEN (UPDATE ${h} ${y} RETURN VALUE id) END; ${h};`},i=a=>{let{$thing:l,$op:d}=a,c=ee(t,l),u=le(l),{usedRoleFields:p}=ge(c,a);if(!["create","delete"].includes(d))throw new Error("Arcs can only be created or deleted");let[f,h]=p,$=isArray(a[f])?a[f]:[a[f]],E=isArray(a[h])?a[h]:[a[h]];if(d==="create"){if(p.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let y=ye(a,j=>!j.startsWith("$")),B=`(CREATE ONLY Delta SET input = ${JSON.stringify(y)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,T=c.roles[f].cardinality==="MANY",M=c.roles[h].cardinality==="MANY";return [`
130
130
  ${T?"":`IF array::len(array::filter(array::flatten([$\u27E8${$}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${f} is cardinality one and can link a single thing." + <string>$\u27E8${$}\u27E9; };`}
131
- ${Q?"":`IF array::len(array::filter(array::flatten([$\u27E8${E}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${h} is cardinality one and can link a single thing." + <string>$\u27E8${E}\u27E9; };`}
131
+ ${M?"":`IF array::len(array::filter(array::flatten([$\u27E8${E}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${h} is cardinality one and can link a single thing." + <string>$\u27E8${E}\u27E9; };`}
132
132
  FOR $node1 IN array::flatten([$\u27E8${$}\u27E9]) {
133
133
  IF $node1 {
134
134
  FOR $node2 IN array::flatten([$\u27E8${E}\u27E9]) {
135
135
  IF $node2 {
136
136
  CREATE ONLY ${u} SET
137
137
  ${f} = ${T?"array::flatten([$node1])":"$node1"},
138
- ${h} = ${Q?"array::flatten([$node2])":"$node2"}
138
+ ${h} = ${M?"array::flatten([$node2])":"$node2"}
139
139
  RETURN ${B};
140
140
  }
141
141
  }
142
142
  }
143
- }`]}if(d==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${h}) CONTAINSANY $\u27E8${E}\u27E9 RETURN BEFORE`},o=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=ee(t,l),{usedRefFields:f}=ge(p,a),h=`$\u27E8${u||d}\u27E9`,$=f.flatMap(y=>{let B=p.refFields[y];if(!B)throw new Error(`ReferenceField schema not found for ${y}`);let{cardinality:g,contentType:T}=B;if(T==="REF"){let w=isArray(a[y])?a[y]:[`${a[y]}`];if(g==="ONE"){if(w.length>1){let Q=`array::filter(array::flatten([${w}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${y} = ((array::len(${Q})==1) && ${Q}[0]) || ${Q}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${y} = ((type::is::array(${w[0]}) && array::len(${w[0]})==1) && ${w[0]}[0]) || ${w[0]}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(g==="MANY"){let Q=`array::flatten([${w}])`;switch(c){case "link":return `${y} += ${Q}`;case "unlink":return `${y} -= ${Q}`;case "replace":return `${y} = ${Q}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${g}`)}if(T==="FLEX")return `${y} = ${g==="ONE"?`array::flatten([${a[y]}])[0]`:`array::flatten([${a[y]}])`}`;throw new Error(`Unsupported contentType ${T}`)}),E=$.length>0?`${$.join(", ")}`:"",m=E?`SET ${E}`:"";return `IF ${h} THEN (UPDATE ${h} ${m} RETURN VALUE id) END; ${h};`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(i),...e.references.map(o)]};var yo=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(i=>{if(isArray(i))return i.map(o=>{if(!isObject(o)||!("meta"in o))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(o)}`);return $o(o,r)});if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return $o(i,r)})},$o=(e,t)=>{let r=mapEntries(e.after||{},(o,s)=>[o,o==="id"?s.id:isArray(s)&&s.length===0?void 0:s]),n=ye(e.input||{},(o,s)=>s===null),i={...r,...e.meta,...n};return t.mutation?.noMetadata?ye(i,o=>!o.startsWith("$")):i};var go=async(e,t)=>{let r=`
143
+ }`]}if(d==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${h}) CONTAINSANY $\u27E8${E}\u27E9 RETURN BEFORE`},o=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=ee(t,l),{usedRefFields:f}=ge(p,a),h=`$\u27E8${u||d}\u27E9`,$=f.flatMap(m=>{let B=p.refFields[m];if(!B)throw new Error(`ReferenceField schema not found for ${m}`);let{cardinality:g,contentType:T}=B;if(T==="REF"){let w=isArray(a[m])?a[m]:[`${a[m]}`];if(g==="ONE"){if(w.length>1){let M=`array::filter(array::flatten([${w}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${m} = ((array::len(${M})==1) && ${M}[0]) || ${M}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${m} = ((type::is::array(${w[0]}) && array::len(${w[0]})==1) && ${w[0]}[0]) || ${w[0]}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(g==="MANY"){let M=`array::flatten([${w}])`;switch(c){case "link":return `${m} += ${M}`;case "unlink":return `${m} -= ${M}`;case "replace":return `${m} = ${M}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${g}`)}if(T==="FLEX"){if(g==="ONE")return `${m} = array::flatten([${a[m]}])[0]`;let M=(isArray(a[m])?a[m]:[a[m]]).map(D=>typeof D=="string"&&D.startsWith("$")?`array::flatten([${D}])[0]`:D);return `${m} = [${M.join(", ")}]`}throw new Error(`Unsupported contentType ${T}`)}),E=$.length>0?`${$.join(", ")}`:"",y=E?`SET ${E}`:"";return `IF ${h} THEN (UPDATE ${h} ${y} RETURN VALUE id) END; ${h};`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(i),...e.references.map(o)]};var go=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(i=>{if(isArray(i))return i.map(o=>{if(!isObject(o)||!("meta"in o))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(o)}`);return mo(o,r)});if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return mo(i,r)})},mo=(e,t)=>{let r=mapEntries(e.after||{},(o,s)=>[o,o==="id"?s.id:isArray(s)&&s.length===0?void 0:s]),n=ye(e.input||{},(o,s)=>s===null),i={...r,...e.meta,...n};return t.mutation?.noMetadata?ye(i,o=>!o.startsWith("$")):i};var Eo=async(e,t)=>{let r=`
144
144
  BEGIN TRANSACTION;
145
145
  ${t.join(";")};
146
146
  LET $DELTAS = SELECT * FROM Delta;
@@ -150,11 +150,11 @@ limit ${d};`),u.join(`
150
150
  LET $LOGS = SELECT * FROM LOG;
151
151
  RETURN $LOGS;
152
152
  COMMIT TRANSACTION;
153
- `;Z(`>>> batchedMutation[${G}]`,JSON.stringify({batchedMutation:r}));try{return (await e.query(r)).filter(Boolean)}catch(n){let o=(await e.queryRaw(r)).filter(s=>s.result!=="The query was not executed due to a failed transaction"&&s.result!=="There was an error when starting a new datastore transaction"&&s.status==="ERR");throw o.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(o)}`):n}};var ql=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),xl=(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}}},jl=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},qr=x("error","error",q((e,t)=>({...e,error:t.error}))),_l=e=>{let t=e.surrealDB?.values().next().value;if(!t?.client)throw new Error("No SurrealDB client available");return t.client},zl=we("buildMutation",{buildMutation:U(async e=>(Z(`>>> surqlMachine/buildMutation[${G}]`,JSON.stringify(e.bql.flat)),ho(e.bql.flat,e.schema)),x("done","runMutation",q(xl)),qr),runMutation:U(async e=>(Z(`>>> surqlMachine/runMutation[${G}]`,JSON.stringify(e.surql.mutations)),go(_l(e.handles),e.surql.mutations)),x("done","parseMutation",q(jl)),qr),parseMutation:U(async e=>(Z(`>>> surqlMachine/parseMutation[${G}]`,JSON.stringify(e.surql.res)),yo({res:e.surql.res,config:e.config,schema:e.schema})),x("done","success",q(ql)),qr),success:me(),error:me()},e=>e),Vl=async e=>new Promise((t,r)=>{Re(zl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Bo=async(e,t,r,n,i,o)=>Vl({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:i,handles:o,error:null});var xr=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 bo=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=p=>{let f=p.$op,h=`$${p.$bzId}`,$=z(r,p),{idFields:E,defaultDBConnector:m}=$,y=m?.path||p.$thing,B=p.$id,g=E?.[0],T=listify(p,(I,D)=>{if(I.startsWith("$")||I.startsWith("%")||I===g||D===void 0||D===null)return "";let Y=$.dataFields?.find(S=>S.path===I);if(!Y?.path)return "";let F=Y.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Y.contentType))return `has ${F} '${D}'`;if(["NUMBER","BOOLEAN"].includes(Y.contentType))return `has ${F} ${D}`;if(Y.contentType==="DATE"){if(Number.isNaN(D.valueOf()))throw new Error("Invalid format, Nan Date");return D instanceof Date?`has ${F} ${D.toISOString().replace("Z","")}`:`has ${F} ${new Date(D).toISOString().replace("Z","")}`}if(Y.contentType==="FLEX"){let S=`bza${je()}`,M=isArray(D)?D.map(R=>xr(R)):xr(D);if(Array.isArray(M))throw new Error("Array in FLEX fields not supported yet");return `has ${F} $${S}; $${S} '${S}' isa ${F}, has ${M.type}Attribute ${M.value}`}throw new Error(`Unsupported contentType ${Y.contentType}`)}).filter(I=>I),w=`${h}-atts`,Q=listify(p,I=>{if(I.startsWith("$")||I.startsWith("%")||I===g)return "";let D=$.dataFields?.find(F=>F.path===I);if(!D?.path)return "";let b=D.dbPath;return `{${w} isa ${b};}`}).filter(I=>I),O=isArray(B)?`like '${B.join("|")}'`:`'${B}'`,j=B?[`has ${g} ${O}`]:[],K=[...j,...T].filter(I=>I).join(","),ce=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[y,...j].filter(I=>I).join(",")};`;if(f==="update"){if(!Q.length)throw new Error("update without attributes");return `${h} isa ${[y,...j].filter(I=>I).join(",")}, has ${w};
154
- ${Q.join(" or ")};`}return ""},se=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[y,...j].filter(I=>I).join(",")};`:"";if(Lt(p))return {op:f,deletionMatch:ce(),insertionMatch:se(),insertion:f==="create"?`${h} isa ${[y,K].filter(I=>I).join(",")};`:f==="update"&&T.length?`${h} ${T.join(",")};`:"",deletion:f==="delete"?`${h} isa ${y};`:f==="update"&&Q.length?`${h} has ${w};`:""};throw new Error("in attributes")},i=p=>{let f=p.$op,h=z(r,p),$=`$${p.$bzId}`,E=p.$id,m=h.defaultDBConnector?.path||p.$thing,y="roles"in h?listify(h.roles,D=>D):[],B="roles"in h?mapEntries(h.roles,(D,Y)=>[D,Y.dbConnector?.path||D]):{},g=listify(p,(D,Y)=>{if(!y.includes(D))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=B[D];return Array.isArray(Y)?Y.map(F=>({path:b,id:F})):{path:b,id:Y}}).filter(D=>D).flat(),T=g.map(D=>{if(!D?.path)throw new Error("Object without path");return `${D.path}: $${D.id}`}),w=g.length>0?`( ${T.join(" , ")} )`:"",Q=p[We];if(!Q)throw new Error("[internal error] Symbol edgeType not defined");let O=w?`${$} ${w} ${Q==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",j=`${$} ${Q==="linkField"||f==="delete"?`isa ${m}`:""}`,K=()=>O?f==="link"?`${O};`:f==="create"?`${O}, has id '${E}';`:"":"",ce=()=>O&&f==="match"?`${O};`:"",se=()=>O?f==="delete"?`${O};`:f==="match"?`${O};`:"":"",I=()=>O?f==="delete"?`${j};`:f==="unlink"?`${$} ${w};`:"":"";return {deletionMatch:se(),insertionMatch:ce(),deletion:I(),insertion:K(),op:""}},o=(p,f)=>{let h=f==="edges"?i:n;if(Array.isArray(p))return p.map(g=>{let{preDeletionBatch:T,insertionMatch:w,deletionMatch:Q,insertion:O,deletion:j}=h(g);return shake({preDeletionBatch:T,insertionMatch:w,deletionMatch:Q,insertion:O,deletion:j},K=>!K)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:E,deletionMatch:m,insertion:y,deletion:B}=h(p);return shake({preDeletionBatch:$,insertionMatch:E,deletionMatch:m,insertion:y,deletion:B},g=>!g)},s=o(e),a=Array.isArray(s)?s:[s],l=o(t,"edges"),d=Array.isArray(l)?l:[l],c=[...a,...d];return shake({insertionMatches:c.map(p=>p.insertionMatch).join(" ").trim(),deletionMatches:c.map(p=>p.deletionMatch).join(" ").trim(),insertions:c.map(p=>p.insertion).join(" ").trim(),deletions:c.map(p=>p.deletion).join(" ").trim()},p=>!p)};var To=async(e,t,r,n,i)=>{let o=[...t,...r],s=o.map(a=>{let l=e.insertions?.find(u=>u.get(`${a.$bzId}`))?.get(`${a.$bzId}`),d=a.$thing||a.$relation||a.$entity,c=d?ee(n,d):void 0;if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!l&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let u=l?.asThing().iid,p=Object.entries(a).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,E])=>{if(c?.dataFields?.find(y=>y.path===$)?.contentType==="JSON")return h[$]=JSON.parse(E),h;if(a.$thingType==="relation"){let y=o.filter(B=>B.$id&&B.$bzId===E);return y.length===1?(h[$]=y[0].$id,h):(h[$]=E,h)}return h[$]=E,h},{});if(i.mutation?.noMetadata)return p;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:u,...a,...p,[a.path]:a.$id,...f}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(s)};var So=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 jt(t,r),i=await n.transaction(TransactionType.WRITE),o=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{o&&await i.query.delete(o);let a=s&&i.query.insert(s),l=a?await a.collect():void 0;return await i.commit(),{insertions:l}}catch(a){throw new Error(`Transaction failed: ${a.message}`)}finally{await i.close();}};var Jl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Kl=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),Yl=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),_r=x("error","error",q((e,t)=>({...e,error:t.error}))),Xl=we("buildMutation",{buildMutation:U(async e=>bo(e.bql.things,e.bql.edges,e.schema),x("done","runMutation",q(Kl)),_r),runMutation:U(async e=>So(e.tql.mutation,e.handles,e.config),x("done","parseMutation",q(Yl)),_r),parseMutation:U(async e=>To(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),x("done","success",q(Jl)),_r),success:me(),error:me()},e=>e),Zl=async e=>new Promise((t,r)=>{Re(Xl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),wo=async(e,t,r,n,i,o,s)=>Zl({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:i,config:o,handles:s,error:null});var Ro=me,pt=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Gl=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ec=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),tc=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),rc=async e=>(Z(`>>> mutationMachine/enrich[${G}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?fr(e.bql.enriched,e.schema,e.config):fr(e.bql.raw,e.schema,e.config)),nc=async e=>(Z(`>>> mutationMachine/preQuery[${G}]`,JSON.stringify(e.bql.enriched)),uo(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),ic=async e=>(Z(`>>> mutationMachine/preQueryDependencies[${G}]`,JSON.stringify(e.bql.enriched)),eo(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),oc=async e=>(Z(`>>> mutationMachine/parseBQL[${G}]`,JSON.stringify(e.bql.enriched)),co(e.bql.enriched,e.schema)),sc=async e=>(Z(`>>> mutationMachine/flattenBQL[${G}]`,JSON.stringify(e.bql.enriched)),oo(e.bql.enriched,e.schema)),ac=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 true;if(r==="surrealDB")return false;throw new Error(`Unsupported provider ${r}.`)},lc=e=>it(e.bql.enriched),Ye=x("error","error",q((e,t)=>({...e,error:t.error}))),cc=we("stringify",{stringify:U(async e=>(Z(`>>> mutationMachine/stringify[${G}]`,JSON.stringify(e.bql.raw)),po(e.bql.raw,e.schema)),x("done","enrich",q(pt)),Ye),enrich:U(rc,x("done","preQuery",rr(ac),q(pt)),x("done","parseBQL",q(pt)),Ye),preQuery:U(nc,x("done","preHookDependencies",rr(lc),q(pt)),x("done","parseBQL",q(pt)),Ye),preHookDependencies:U(ic,x("done","enrich",q(pt)),Ye),parseBQL:U(oc,x("done","flattenBQL",q(Gl)),Ye),flattenBQL:U(sc,x("done","adapter",q(ec)),Ye),adapter:U(async e=>{Z(`>>> mutationMachine/adapter[${G}]`,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 wo(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return Bo(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},x("done","success",q(tc)),Ye),success:Ro(),error:Ro()},e=>e),dc=async e=>new Promise((t,r)=>{Re(cc,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Lo=async(e,t,r,n,i)=>dc({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,draftSchema:r,config:n,handles:i,depthLevel:0,error:null});enableMapSet();var zr=class{schema;config;initializing=false;subscribers=[];initialized=null;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.initialized?.dbHandles;getInitialized=async()=>{if(this.initialized)return this.initialized;if(await this.init(),this.initialized)return this.initialized;throw new Error("Client is not initialized")};init=async()=>{if(this.initializing)return new Promise((r,n)=>{this.subscribers.push(i=>{i?n(i):r();});});this.initializing=true;let t={typeDB:new Map,surrealDB:new Map};try{await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let i=new Bt({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});await i.connect(),t.surrealDB.set(n.id,{client:i,providerConfig:n.providerConfig});}else if(n.provider==="typeDB"&&n.dbName){let[i,o]=await tryit(TypeDB.coreDriver)(n.url);if(i){let s=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await o.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:o,session:s});}catch(s){let a=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}else if(n.provider==="typeDBCluster"&&n.dbName){let i=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[o,s]=await tryit(TypeDB.cloudDriver)(n.addresses,i);if(o){let a=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:s,session:a});}catch(a){let l=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(l)}}})),this.initialized={draftSchema:sn(this.schema),enrichedSchema:tn(this.schema,t),dbHandles:t};let r=this.subscribers;this.subscribers=[];for(let n of r)n();}catch(r){let n=this.subscribers;this.subscribers=[];for(let i of n)i(r);}finally{this.initializing=false;}};introspect=async()=>(await this.getInitialized()).enrichedSchema;define=async()=>{let t=await this.getInitialized();return await Yr(this.config,t.enrichedSchema,t.dbHandles)};query=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,query:{...Ht.query,...this.config.query,...r}},o=Array.isArray(t),s=o?t:[t],[a,l]=await tryit(dt)(s,n.enrichedSchema,n.draftSchema,i,n.dbHandles);if(a){let c=new Error(a.error);throw c.stack=a.error.stack,c}let d=l.bql.res;return o?d:d[0]};mutate=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,mutation:{...Ht.mutation,...this.config.mutation,...r}},[o,s]=await tryit(Lo)(t,n.enrichedSchema,n.draftSchema,i,n.dbHandles);if(o){let l=new Error(o.error.message);throw l.stack=o.error.stack,l}return s.bql.res};close=async()=>{if(this.initialized)try{await Promise.all([...this.initialized.dbHandles.typeDB?.values()??[]].map(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();})),await Promise.all([...this.initialized.dbHandles.surrealDB?.values()??[]].map(async({client:t})=>{await t.close();}));}finally{this.initialized=null;}}},p$=zr;//! TO-DO Rule: Everything that can be changed or defined by the user should use $ prefix, but the rest is metadata and should be packed in symbols, depending on their origin. extension inside the schema and schema or query inside the query. Probably no more categories are necessary
153
+ `;Z(`>>> batchedMutation[${G}]`,JSON.stringify({batchedMutation:r}));try{return (await e.query(r)).filter(Boolean)}catch(n){let i=n instanceof Error?n.message:String(n);throw i==="The query was not executed due to a failed transaction"||i==="There was an error when starting a new datastore transaction"?n:new Error(`Error running SURQL mutation: ${i}`)}};var Cl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Pl=(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}}},ql=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Pr=x("error","error",q((e,t)=>({...e,error:t.error}))),xl=e=>{let t=e.surrealDB?.values().next().value;if(!t?.client)throw new Error("No SurrealDB client available");return t.client},jl=we("buildMutation",{buildMutation:U(async e=>(Z(`>>> surqlMachine/buildMutation[${G}]`,JSON.stringify(e.bql.flat)),fo(e.bql.flat,e.schema)),x("done","runMutation",q(Pl)),Pr),runMutation:U(async e=>(Z(`>>> surqlMachine/runMutation[${G}]`,JSON.stringify(e.surql.mutations)),Eo(xl(e.handles),e.surql.mutations)),x("done","parseMutation",q(ql)),Pr),parseMutation:U(async e=>(Z(`>>> surqlMachine/parseMutation[${G}]`,JSON.stringify(e.surql.res)),go({res:e.surql.res,config:e.config,schema:e.schema})),x("done","success",q(Cl)),Pr),success:me(),error:me()},e=>e),_l=async e=>new Promise((t,r)=>{Re(jl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Fo=async(e,t,r,n,i,o)=>_l({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:i,handles:o,error:null});var qr=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 To=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=p=>{let f=p.$op,h=`$${p.$bzId}`,$=V(r,p),{idFields:E,defaultDBConnector:y}=$,m=y?.path||p.$thing,B=p.$id,g=E?.[0],T=listify(p,(I,A)=>{if(I.startsWith("$")||I.startsWith("%")||I===g||A===void 0||A===null)return "";let Y=$.dataFields?.find(S=>S.path===I);if(!Y?.path)return "";let F=Y.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Y.contentType))return `has ${F} '${A}'`;if(["NUMBER","BOOLEAN"].includes(Y.contentType))return `has ${F} ${A}`;if(Y.contentType==="DATE"){if(Number.isNaN(A.valueOf()))throw new Error("Invalid format, Nan Date");return A instanceof Date?`has ${F} ${A.toISOString().replace("Z","")}`:`has ${F} ${new Date(A).toISOString().replace("Z","")}`}if(Y.contentType==="FLEX"){let S=`bza${je()}`,Q=isArray(A)?A.map(R=>qr(R)):qr(A);if(Array.isArray(Q))throw new Error("Array in FLEX fields not supported yet");return `has ${F} $${S}; $${S} '${S}' isa ${F}, has ${Q.type}Attribute ${Q.value}`}throw new Error(`Unsupported contentType ${Y.contentType}`)}).filter(I=>I),w=`${h}-atts`,M=listify(p,I=>{if(I.startsWith("$")||I.startsWith("%")||I===g)return "";let A=$.dataFields?.find(F=>F.path===I);if(!A?.path)return "";let b=A.dbPath;return `{${w} isa ${b};}`}).filter(I=>I),D=isArray(B)?`like '${B.join("|")}'`:`'${B}'`,j=B?[`has ${g} ${D}`]:[],K=[...j,...T].filter(I=>I).join(","),ce=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[m,...j].filter(I=>I).join(",")};`;if(f==="update"){if(!M.length)throw new Error("update without attributes");return `${h} isa ${[m,...j].filter(I=>I).join(",")}, has ${w};
154
+ ${M.join(" or ")};`}return ""},se=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[m,...j].filter(I=>I).join(",")};`:"";if(Qt(p))return {op:f,deletionMatch:ce(),insertionMatch:se(),insertion:f==="create"?`${h} isa ${[m,K].filter(I=>I).join(",")};`:f==="update"&&T.length?`${h} ${T.join(",")};`:"",deletion:f==="delete"?`${h} isa ${m};`:f==="update"&&M.length?`${h} has ${w};`:""};throw new Error("in attributes")},i=p=>{let f=p.$op,h=V(r,p),$=`$${p.$bzId}`,E=p.$id,y=h.defaultDBConnector?.path||p.$thing,m="roles"in h?listify(h.roles,A=>A):[],B="roles"in h?mapEntries(h.roles,(A,Y)=>[A,Y.dbConnector?.path||A]):{},g=listify(p,(A,Y)=>{if(!m.includes(A))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=B[A];return Array.isArray(Y)?Y.map(F=>({path:b,id:F})):{path:b,id:Y}}).filter(A=>A).flat(),T=g.map(A=>{if(!A?.path)throw new Error("Object without path");return `${A.path}: $${A.id}`}),w=g.length>0?`( ${T.join(" , ")} )`:"",M=p[ve];if(!M)throw new Error("[internal error] Symbol edgeType not defined");let D=w?`${$} ${w} ${M==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",j=`${$} ${M==="linkField"||f==="delete"?`isa ${y}`:""}`,K=()=>D?f==="link"?`${D};`:f==="create"?`${D}, has id '${E}';`:"":"",ce=()=>D&&f==="match"?`${D};`:"",se=()=>D?f==="delete"?`${D};`:f==="match"?`${D};`:"":"",I=()=>D?f==="delete"?`${j};`:f==="unlink"?`${$} ${w};`:"":"";return {deletionMatch:se(),insertionMatch:ce(),deletion:I(),insertion:K(),op:""}},o=(p,f)=>{let h=f==="edges"?i:n;if(Array.isArray(p))return p.map(g=>{let{preDeletionBatch:T,insertionMatch:w,deletionMatch:M,insertion:D,deletion:j}=h(g);return shake({preDeletionBatch:T,insertionMatch:w,deletionMatch:M,insertion:D,deletion:j},K=>!K)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:E,deletionMatch:y,insertion:m,deletion:B}=h(p);return shake({preDeletionBatch:$,insertionMatch:E,deletionMatch:y,insertion:m,deletion:B},g=>!g)},s=o(e),a=Array.isArray(s)?s:[s],l=o(t,"edges"),d=Array.isArray(l)?l:[l],c=[...a,...d];return shake({insertionMatches:c.map(p=>p.insertionMatch).join(" ").trim(),deletionMatches:c.map(p=>p.deletionMatch).join(" ").trim(),insertions:c.map(p=>p.insertion).join(" ").trim(),deletions:c.map(p=>p.deletion).join(" ").trim()},p=>!p)};var So=async(e,t,r,n,i)=>{let o=[...t,...r],s=o.map(a=>{let l=e.insertions?.find(u=>u.get(`${a.$bzId}`))?.get(`${a.$bzId}`),d=a.$thing||a.$relation||a.$entity,c=d?ee(n,d):void 0;if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!l&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let u=l?.asThing().iid,p=Object.entries(a).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,E])=>{if(c?.dataFields?.find(m=>m.path===$)?.contentType==="JSON")return h[$]=JSON.parse(E),h;if(a.$thingType==="relation"){let m=o.filter(B=>B.$id&&B.$bzId===E);return m.length===1?(h[$]=m[0].$id,h):(h[$]=E,h)}return h[$]=E,h},{});if(i.mutation?.noMetadata)return p;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:u,...a,...p,[a.path]:a.$id,...f}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(s)};var wo=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 Vt(t,r),i=await n.transaction(TransactionType.WRITE),o=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{o&&await i.query.delete(o);let a=s&&i.query.insert(s),l=a?await a.collect():void 0;return await i.commit(),{insertions:l}}catch(a){throw new Error(`Transaction failed: ${a.message}`)}finally{await i.close();}};var vl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Hl=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),Jl=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),jr=x("error","error",q((e,t)=>({...e,error:t.error}))),Kl=we("buildMutation",{buildMutation:U(async e=>To(e.bql.things,e.bql.edges,e.schema),x("done","runMutation",q(Hl)),jr),runMutation:U(async e=>wo(e.tql.mutation,e.handles,e.config),x("done","parseMutation",q(Jl)),jr),parseMutation:U(async e=>So(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),x("done","success",q(vl)),jr),success:me(),error:me()},e=>e),Yl=async e=>new Promise((t,r)=>{Re(Kl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Ro=async(e,t,r,n,i,o,s)=>Yl({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:i,config:o,handles:s,error:null});var Lo=me,pt=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Xl=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Zl=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Gl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ec=async e=>(Z(`>>> mutationMachine/enrich[${G}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?hr(e.bql.enriched,e.schema,e.config):hr(e.bql.raw,e.schema,e.config)),tc=async e=>(Z(`>>> mutationMachine/preQuery[${G}]`,JSON.stringify(e.bql.enriched)),po(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),rc=async e=>(Z(`>>> mutationMachine/preQueryDependencies[${G}]`,JSON.stringify(e.bql.enriched)),to(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),nc=async e=>(Z(`>>> mutationMachine/parseBQL[${G}]`,JSON.stringify(e.bql.enriched)),uo(e.bql.enriched,e.schema)),ic=async e=>(Z(`>>> mutationMachine/flattenBQL[${G}]`,JSON.stringify(e.bql.enriched)),so(e.bql.enriched,e.schema)),oc=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 true;if(r==="surrealDB")return false;throw new Error(`Unsupported provider ${r}.`)},sc=e=>it(e.bql.enriched),Xe=x("error","error",q((e,t)=>({...e,error:t.error}))),ac=we("stringify",{stringify:U(async e=>(Z(`>>> mutationMachine/stringify[${G}]`,JSON.stringify(e.bql.raw)),ho(e.bql.raw,e.schema)),x("done","enrich",q(pt)),Xe),enrich:U(ec,x("done","preQuery",rr(oc),q(pt)),x("done","parseBQL",q(pt)),Xe),preQuery:U(tc,x("done","preHookDependencies",rr(sc),q(pt)),x("done","parseBQL",q(pt)),Xe),preHookDependencies:U(rc,x("done","enrich",q(pt)),Xe),parseBQL:U(nc,x("done","flattenBQL",q(Xl)),Xe),flattenBQL:U(ic,x("done","adapter",q(Zl)),Xe),adapter:U(async e=>{Z(`>>> mutationMachine/adapter[${G}]`,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 Ro(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return Fo(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},x("done","success",q(Gl)),Xe),success:Lo(),error:Lo()},e=>e),lc=async e=>new Promise((t,r)=>{Re(ac,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Mo=async(e,t,r,n,i)=>lc({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,draftSchema:r,config:n,handles:i,depthLevel:0,error:null});enableMapSet();var _r=class{schema;config;initializing=false;subscribers=[];initialized=null;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.initialized?.dbHandles;getInitialized=async()=>{if(this.initialized)return this.initialized;if(await this.init(),this.initialized)return this.initialized;throw new Error("Client is not initialized")};init=async()=>{if(this.initializing)return new Promise((r,n)=>{this.subscribers.push(i=>{i?n(i):r();});});this.initializing=true;let t={typeDB:new Map,surrealDB:new Map};try{await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let i=new bt({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});await i.connect(),t.surrealDB.set(n.id,{client:i,providerConfig:n.providerConfig});}else if(n.provider==="typeDB"&&n.dbName){let[i,o]=await tryit(TypeDB.coreDriver)(n.url);if(i){let s=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await o.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:o,session:s});}catch(s){let a=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}else if(n.provider==="typeDBCluster"&&n.dbName){let i=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[o,s]=await tryit(TypeDB.cloudDriver)(n.addresses,i);if(o){let a=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:s,session:a});}catch(a){let l=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(l)}}})),this.initialized={draftSchema:on(this.schema),enrichedSchema:en(this.schema,t),dbHandles:t};let r=this.subscribers;this.subscribers=[];for(let n of r)n();}catch(r){let n=this.subscribers;this.subscribers=[];for(let i of n)i(r);}finally{this.initializing=false;}};introspect=async()=>(await this.getInitialized()).enrichedSchema;define=async()=>{let t=await this.getInitialized();return await Kr(this.config,t.enrichedSchema,t.dbHandles)};query=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,query:{...Jt.query,...this.config.query,...r}},o=Array.isArray(t),s=o?t:[t],[a,l]=await tryit(dt)(s,n.enrichedSchema,n.draftSchema,i,n.dbHandles);if(a){let c=new Error(a.error);throw c.stack=a.error.stack,c}let d=l.bql.res;return o?d:d[0]};mutate=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,mutation:{...Jt.mutation,...this.config.mutation,...r}},[o,s]=await tryit(Mo)(t,n.enrichedSchema,n.draftSchema,i,n.dbHandles);if(o){let l=new Error(o.error.message);throw l.stack=o.error.stack,l}return s.bql.res};close=async()=>{if(this.initialized)try{await Promise.all([...this.initialized.dbHandles.typeDB?.values()??[]].map(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();})),await Promise.all([...this.initialized.dbHandles.surrealDB?.values()??[]].map(async({client:t})=>{await t.close();}));}finally{this.initialized=null;}}},u$=_r;//! TO-DO Rule: Everything that can be changed or defined by the user should use $ prefix, but the rest is metadata and should be packed in symbols, depending on their origin. extension inside the schema and schema or query inside the query. Probably no more categories are necessary
155
155
  //! Todo: delete when this works with the new $thing and $thingType fields
156
156
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
157
157
  //! reads all the insertions and gets the first match. This means each id must be unique
158
158
  //!old
159
- export{p$ as default};//# sourceMappingURL=index.mjs.map
159
+ export{u$ as default};//# sourceMappingURL=index.mjs.map
160
160
  //# sourceMappingURL=index.mjs.map