@blitznocode/blitz-orm 0.15.6 → 0.16.0

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,73 +1,47 @@
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 {RecordId,DateTime,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 Pt,{z as z$1}from'zod/v4';var Po=Object.defineProperty;var xo=(e,t)=>{for(var r in t)Po(e,r,{get:t[r],enumerable:true});};var Kt=new Set((process.env.BORM_LOG_TAGS||"").split(",").map(e=>e.trim()).filter(e=>!!e)),G=(e,...t)=>{(Kt.has("*")||(Array.isArray(e)?e.some(n=>Kt.has(n)||n==="*"):Kt.has(e)||e==="*"))&&console.log(...t);},ee=(...e)=>G("debug",...e);var We="SurrealClient",zo={enabled:true,attempts:-1,retryDelayMultiplier:1.2,retryDelayJitter:0},Tt=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={...zo,...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 G([We,"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="",G([We,"info"],"Connection established");}).catch(s=>{throw this.#i=s.message,s instanceof UnsupportedVersionError&&G([We,"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="",G([We,"info"],"Connection re-established");}),this.#e.subscribe("disconnected",()=>{this.#t="disconnected",this.#n=null;}),this.#e.subscribe("error",t=>{this.#i=t.message,G([We,"error"],"Connection error",{error:t.message});}));}async#u(){try{let t=await this.#e.version();this.#n=t.version.replace(/^surrealdb-/,""),G([We,"info"],`Database version ${this.#n}`);}catch{G([We,"info"],"Database version unknown");}}};var Yt={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var Hr=e=>e.replace(/`/g,""),Vo=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],se=e=>Vo.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var vr=(e,t)=>Xt(e,t),Xt=(e,t)=>{if(e==null)return "null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return `[${e.map(n=>Xt(n,t)).join(", ")}]`;if(typeof e=="object"){let r=Wo(e,t);return r?`${se(r.thing)}:\u27E8${r.id.replaceAll("\u27E9","\\\u27E9")}\u27E9`:`{${Object.entries(e).map(([o,s])=>`${JSON.stringify(o)}: ${Xt(s,t)}`).join(", ")}}`}return JSON.stringify(e)},Wo=(e,t)=>{let r=Object.keys(e);if(r.length!==1||r[0]!=="$ref")return null;let n=e.$ref;if(typeof n!="string")return null;let i=n.indexOf(":");if(i===-1)return null;let o=n.slice(0,i),s=n.slice(i+1);return !o||!s||!t.entities[o]&&!t.relations[o]?null:{thing:o,id:s}},St=e=>{if(e==null)return e;if(Array.isArray(e))return e.map(St);if(e instanceof RecordId)return e.id;if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=St(n);return t}return e};var Jr=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 Kr={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"},et=(e,t,r)=>{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":return e;case "JSON":if(r&&typeof e=="string")try{let n=JSON.parse(e);return vr(n,r)}catch{return e}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 Jr(e);default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var Jo=" ",He=e=>Jo.repeat(e),wt=(e,t)=>e.split(`
2
- `).map(r=>r.trim()?`${He(t)}${r}`:r).join(`
3
- `),Ko=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 {RecordId,DateTime,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 Nt,{z}from'zod/v4';var Bo=Object.defineProperty;var Fo=(e,t)=>{for(var r in t)Bo(e,r,{get:t[r],enumerable:true});};var Wt=new Set((process.env.BORM_LOG_TAGS||"").split(",").map(e=>e.trim()).filter(e=>!!e)),ee=(e,...t)=>{(Wt.has("*")||(Array.isArray(e)?e.some(n=>Wt.has(n)||n==="*"):Wt.has(e)||e==="*"))&&console.log(...t);},le=(...e)=>ee("debug",...e);var We="SurrealClient",wo={enabled:true,attempts:-1,retryDelayMultiplier:1.2,retryDelayJitter:0},Ft=class{#e=new Surreal;#s;#a;#l;#r=null;#c=false;#n=false;#t="disconnected";#i=null;#o="";constructor(t,r={}){this.#s=t,this.#a={...wo,...r.reconnect},this.#l=r.versionCheck??false;}async connect(){if(this.#n)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 ee([We,"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.#o="",ee([We,"info"],"Connection established");}).catch(s=>{throw this.#o=s.message,s instanceof UnsupportedVersionError&&ee([We,"error"],"Unsupported SurrealDB version",{version:s.version,minimum:s.minimum,maximum:s.maximum}),s}).finally(()=>{this.#r=null;}),this.#r}async close(){this.#n||(this.#n=true,await this.#e.close().catch(()=>{}),this.#t="disconnected",this.#i=null);}async query(t,r){if(this.#n)throw new Error("Client has been closed");return typeof t=="string"?this.#e.query(t,r):this.#e.query(t)}async beginTransaction(){if(this.#n)throw new Error("Client has been closed");return this.#e.beginTransaction()}get state(){return this.#t}get version(){return this.#i}get latestError(){return this.#o}#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.#o="",ee([We,"info"],"Connection re-established");}),this.#e.subscribe("disconnected",()=>{this.#t="disconnected",this.#i=null;}),this.#e.subscribe("error",t=>{this.#o=t.message,ee([We,"error"],"Connection error",{error:t.message});}));}async#u(){try{let t=await this.#e.version();this.#i=t.version.replace(/^surrealdb-/,""),ee([We,"info"],`Database version ${this.#i}`);}catch{ee([We,"info"],"Database version unknown");}}};var Ut={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var oe=e=>/[^a-zA-Z0-9_]/.test(e)||/^[^a-zA-Z_]/.test(e)?`\u27E8${e.replace(/⟩/g,"\\\u27E9")}\u27E9`:e,Be=e=>/[\s-]/.test(e)?e.replace(/[\s-]/g,"_"):e;var Pr=(e,t)=>vt(e,t),vt=(e,t)=>{if(e==null)return "null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return `[${e.map(n=>vt(n,t)).join(", ")}]`;if(typeof e=="object"){let r=So(e,t);return r?`${oe(r.thing)}:\u27E8${r.id.replaceAll("\u27E9","\\\u27E9")}\u27E9`:`{${Object.entries(e).map(([o,s])=>`${JSON.stringify(o)}: ${vt(s,t)}`).join(", ")}}`}return JSON.stringify(e)},So=(e,t)=>{let r=Object.keys(e);if(r.length!==1||r[0]!=="$ref")return null;let n=e.$ref;if(typeof n!="string")return null;let i=n.indexOf(":");if(i===-1)return null;let o=n.slice(0,i),s=n.slice(i+1);return !o||!s||!t.entities[o]&&!t.relations[o]?null:{thing:o,id:s}},bt=e=>{if(e==null)return e;if(Array.isArray(e))return e.map(bt);if(e instanceof RecordId)return e.id;if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=bt(n);return t}return e};var _r=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 jr={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,r)=>{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":return e;case "JSON":if(r&&typeof e=="string")try{let n=JSON.parse(e);return Pr(n,r)}catch{return e}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 _r(e);default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var Do=" ",Ue=e=>Do.repeat(e),Ao=(e,t)=>e.split(`
2
+ `).map(r=>r.trim()?`${Ue(t)}${r}`:r).join(`
3
+ `),Qo=e=>{let t=`USE NS test;
4
4
  USE DB test;
5
5
 
6
6
  BEGIN TRANSACTION;
7
- `,r=`-- ENTITIES
8
- ${Yr(e.entities)}`,n=`
7
+ `,r=Object.entries(e).filter(([,a])=>a.type==="entity"),n=Object.entries(e).filter(([,a])=>a.type==="relation"),i=`-- ENTITIES
8
+ ${qr(r,e)}`,o=`
9
+
9
10
  -- RELATIONS
10
- ${Yr(e.relations)}`,i=rs();return `${t}${r}${n}${i}COMMIT TRANSACTION;`},Yr=e=>Object.entries(e).map(([t,r])=>Yo(se(t),r,1)).join(`
11
+ ${qr(n,e)}`,s=`
11
12
 
12
- `),Yo=(e,t,r)=>{let n=`${He(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,i=wt(`-- DATA FIELDS
13
- ${Xo(t.dataFields??[],e,r)}`,r+1),o=wt(`
14
- -- LINK FIELDS
15
- ${Zo(t.linkFields??[],e,r)}`,r+1),s="roles"in t?wt(`
16
- -- ROLES
17
- ${Go(t.roles,e,r)}`,r+1):"";return `${n}
18
- ${i}${o}${s}`},Xo=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let i=ts(n.contentType,n.validations),o=`${He(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
- `),Zo=(e,t,r)=>e.map(n=>{let i=n.cardinality==="MANY"?`option<array<record<${n.$things.map(se).join("|")}>>>`:`option<record<${n.$things.map(se).join("|")}>>`,o=`${He(r)}DEFINE FIELD ${se(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<${se(n.relation)}>`:`array<record<${se(n.relation)}>>`,c=se(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?"":`${He(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${d}>;`;return [p,f].join(`
20
- `)}if(n.target==="relation")return `${`${He(r)}DEFINE FIELD ${se(n.path)} ON TABLE ${t} TYPE ${i};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
21
- `),Go=(e,t,r)=>Object.entries(e).map(([n,i])=>{let o=i.cardinality==="MANY"?`array<record<${i.$things.map(se).join("|")}>>`:`record<${i.$things.map(se).join("|")}>`,s=`${He(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${o}>;`,a=es(n,t,i,r);return `${s}
22
- ${a}`}).join(`
23
- `),es=(e,t,r,n)=>{let i=`update_${e}`,o=r.playedBy?.find(F=>F.target==="relation"),s=o?.pathToRelation,a=r.playedBy?.find(F=>F.target==="role"),l=a?.pathToRelation,d=o??a;if(!d)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=se(s??l),u=(F,E)=>F.map(({path:w,cardinality:S})=>`${w} ${E==="remove"?S==="ONE"?"=":"-=":S==="ONE"?"=":"+="} ${E==="remove"?S==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),p=r.impactedLinkFields?.map(F=>({path:F.path,cardinality:F.cardinality}))||[],h=[{path:c,cardinality:d.cardinality},...p],$=u(h,"remove"),g=u(h,"add"),y=`
24
- IF ($before.${e}) THEN {UPDATE $before.${e} SET ${$}} END;
25
- IF ($after.${e}) THEN {UPDATE $after.${e} SET ${g}} END;`,m=`
26
- LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
27
- FOR $unlink IN $edges.deletions {UPDATE $unlink SET ${$};};
28
- FOR $link IN $edges.additions {${d.cardinality==="ONE"?`
29
- IF ($link.${c}) THEN {UPDATE $link.${c} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
30
- UPDATE $link SET ${g};
31
- };`;return wt(`DEFINE EVENT ${i} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?y:m}
32
- };`,n+1)},ts=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>et(n,e)).join("|")}`:Kr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},rs=()=>`
33
- -- BORM TOOLS
34
- DEFINE FUNCTION fn::get_mutated_edges(
35
- $before_relation: option<array|record>,
36
- $after_relation: option<array|record>,
37
- ) {
38
- LET $notEmptyCurrent = $before_relation ?? [];
39
- LET $current = array::flatten([$notEmptyCurrent]);
40
- LET $notEmptyResult = $after_relation ?? [];
41
- LET $result = array::flatten([$notEmptyResult]);
42
- LET $links = array::complement($result, $current);
43
- LET $unlinks = array::complement($current, $result);
44
-
45
- RETURN {
46
- additions: $links,
47
- deletions: $unlinks
48
- };
49
- };
13
+ -- INTERNAL
14
+ ${Ue(1)}DEFINE TABLE Delta SCHEMALESS PERMISSIONS FULL;
15
+ `;return `${t}${i}${o}${s}COMMIT TRANSACTION;
16
+ `},qr=(e,t)=>e.map(([r,n])=>No(oe(r),n,1,t)).join(`
50
17
 
51
- DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
52
- RETURN (type::is::array($var) AND $var) OR [$var]
53
- };
54
- `,Xr=e=>Ko(e);var os=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},ss=(e,t)=>{let r="",n=[];r+=`
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
- `,d&&d.length>0)for(let p of d)p.contentType!=="REF"&&(p.inherited||(p.isIdField?r+=` owns ${p.dbPath} @key,
57
- `:r+=` owns ${p.dbPath},
58
- `,n.push({dbPath:p.dbPath,contentType:p.contentType})));if(c&&c.length>0){let p=[];for(let f of c){let{relation:h,plays:$,inherited:g}=f;if(g)continue;!t.relations[h].roles[$].inherited&&!p.includes(`${h}:${$}`)&&(r+=` plays ${h}:${$},
59
- `,p.push(`${h}:${$}`));}}r=r.replace(/,\s*$/,`;
18
+ `),Oo=(e,t)=>{let r=new Map,n=(i,o,s)=>{let a=r.get(i);if(a&&a.originalName!==o)throw new Error(`Field name conflict in "${e}": ${s} field "${o}" resolves to "${i}" which conflicts with ${a.fieldType} field "${a.originalName}"`);r.set(i,{originalName:o,fieldType:s});};for(let i of Object.values(t.fields))if(i.type==="data"){if(i.name==="id")continue;n(oe(i.name),i.name,"data");}else i.type==="link"?n(Be(i.name),i.name,"link"):i.type==="role"?n(oe(i.name),i.name,"role"):i.type==="ref"&&n(oe(i.name),i.name,"ref");},No=(e,t,r,n)=>{Oo(e,t);let i=`${Ue(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${t.extends?` //EXTENDS ${t.extends};`:""}`,o=Object.values(t.fields).filter(h=>h.type==="data"),s=Io(o,e,r),a=Object.values(t.fields).filter(h=>h.type==="link"),l=ko(a,e,r,n),p="";if(t.type==="relation"){let h=Object.entries(t.fields).filter($=>$[1].type==="role");h.length>0&&(p=xo(h,e,r,n));}let c=Object.values(t.fields).filter(h=>h.type==="ref"),u=c.length>0?Po(c,e,r):"",d=[];s&&d.push(`-- DATA FIELDS
19
+ ${s}`),l?d.push(`-- LINK FIELDS
20
+ ${l}`):s&&!p&&!u&&d.push("-- LINK FIELDS"),p&&d.push(`-- ROLES
21
+ ${p}`),u&&d.push(`-- REF FIELDS
22
+ ${u}`);let f=d.map(h=>Ao(h,r+1)).join(`
23
+ `);return `${i}
24
+ ${f}`},Io=(e,t,r)=>e.map(n=>{if(n.name==="id")return "";let i=oe(n.name),o=`${Ue(r)}DEFINE FIELD ${i} ON TABLE ${t}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${o} ${a};`:""}if(["FLEX","JSON"].includes(n.contentType))return `${o} TYPE any;`;let s=_o(n.contentType,n.validations,n.cardinality);return `${o} TYPE ${s};`}).filter(Boolean).join(`
25
+ `),ko=(e,t,r,n)=>e.map(i=>{let o=Be(i.name),s=`${Ue(r)}DEFINE FIELD ${o} ON TABLE ${t}`;if(i.isVirtual){let d=i.dbValue?.surrealDB;return d?`${s} ${d};`:""}let a=i.plays,l=i.target==="relation"?i.opposite.thing:i.relation,p=Co(l,a,n),c=i.target==="role"?`.${oe(i.targetRole)}`:"",u;if(p.length===1){let d=`<~(${p[0]})${c}`;i.target==="relation"?u=i.cardinality==="ONE"?`array::first(${d} ?? [])`:d:i.cardinality==="ONE"?u=`array::first(${d} ?? [])`:i.targetRoleCardinality==="MANY"?u=`array::distinct(array::flatten(${d} ?? []))`:u=`array::distinct(${d})`;}else if(i.target==="relation"){let f=`array::concat(${p.map(h=>`<~(${h}) ?? []`).join(", ")})`;u=i.cardinality==="ONE"?`array::first(${f} ?? [])`:`array::distinct(${f})`;}else {let f=`array::flatten([${p.map(h=>`(<~(${h}) ?? [])${c}`).join(", ")}])`;i.cardinality==="ONE"?u=`array::first(${f} ?? [])`:i.targetRoleCardinality==="MANY"?u=`array::distinct(array::flatten(${f}))`:u=`array::distinct(${f})`;}return `${s} COMPUTED ${u};`}).join(`
26
+ `),Co=(e,t,r)=>{let n=r[e];return n?[e,...n.subTypes].map(o=>`${oe(o)} FIELD ${oe(t)}`):[`${oe(e)} FIELD ${oe(t)}`]},xo=(e,t,r,n)=>e.map(([,i])=>{let o=oe(i.name),s=i.opposite.thing,a=n[s],p=(a?[s,...a.subTypes]:[s]).map(oe).join("|"),c=i.cardinality==="MANY"?`array<record<${p}>>`:`record<${p}>`,u=i.onDelete??"UNSET";return `${Ue(r)}DEFINE FIELD ${o} ON TABLE ${t} TYPE option<${c}> REFERENCE ON DELETE ${u};`}).join(`
27
+ `),Po=(e,t,r)=>e.map(n=>{let i=oe(n.name),o;return n.contentType==="REF"?o=n.cardinality==="MANY"?"option<array<record>>":"option<record>":o="any",`${Ue(r)}DEFINE FIELD ${i} ON TABLE ${t} TYPE ${o};`}).join(`
28
+ `),_o=(e,t,r)=>{let n=t?.enum?`${t.enum.map(o=>Ge(o,e)).join("|")}`:jr[e];if(!n)throw new Error(`Unknown content type: ${e}`);let i=r==="MANY"?`array<${n}>`:n;return t?.required?i:`option<${i}>`},Vr=e=>Qo(e);var Vo=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+=`
29
+ `;for(let a of Object.keys(t.entities).filter(l=>t.entities[l].defaultDBConnector.id===e)){let l=t.entities[a],{dataFields:p,linkFields:c,name:u}=l;if(r+=`${u} sub ${"extends"in l?l.extends:"entity"},
30
+ `,p&&p.length>0)for(let d of p)d.contentType!=="REF"&&(d.inherited||(d.isIdField?r+=` owns ${d.dbPath} @key,
31
+ `:r+=` owns ${d.dbPath},
32
+ `,n.push({dbPath:d.dbPath,contentType:d.contentType})));if(c&&c.length>0){let d=[];for(let f of c){let{relation:h,plays:$,inherited:g}=f;if(g)continue;!t.relations[h].roles[$].inherited&&!d.includes(`${h}:${$}`)&&(r+=` plays ${h}:${$},
33
+ `,d.push(`${h}:${$}`));}}r=r.replace(/,\s*$/,`;
60
34
  `),r+=`
61
- `;}for(let a of Object.keys(t.relations).filter(l=>t.relations[l].defaultDBConnector.id===e)){let l=t.relations[a],{dataFields:d,roles:c,name:u,linkFields:p}=l;if(r+=`${u} sub ${"extends"in l?l.extends:"relation"},
62
- `,d&&d.length>0)for(let f of d)f.inherited||(f.isIdField?r+=` owns ${f.dbPath} @key,
35
+ `;}for(let a of Object.keys(t.relations).filter(l=>t.relations[l].defaultDBConnector.id===e)){let l=t.relations[a],{dataFields:p,roles:c,name:u,linkFields:d}=l;if(r+=`${u} sub ${"extends"in l?l.extends:"relation"},
36
+ `,p&&p.length>0)for(let f of p)f.inherited||(f.isIdField?r+=` owns ${f.dbPath} @key,
63
37
  `:r+=` owns ${f.dbPath},
64
38
  `,n.push({dbPath:f.dbPath,contentType:f.contentType}));if(c)for(let f of Object.keys(c))c[f].inherited||(r+=` relates ${f},
65
- `);if(p&&p.length>0){let f=[];for(let h of p){let{plays:$,relation:g}=h;!t.relations[g].roles[$].inherited&&!h.inherited&&!f.includes(`${g}:${$}`)&&(r+=` plays ${h.relation}:${$},
39
+ `);if(d&&d.length>0){let f=[];for(let h of d){let{plays:$,relation:g}=h;!t.relations[g].roles[$].inherited&&!h.inherited&&!f.includes(`${g}:${$}`)&&(r+=` plays ${h.relation}:${$},
66
40
  `,f.push(`${g}:${$}`));}}r=r.replace(/,\s*$/,`;
67
41
  `),r+=`
68
42
  `;}let i=`define
69
43
 
70
- `,o=os(n);for(let a of o)if(a.contentType==="TEXT"||a.contentType==="ID"||a.contentType==="JSON")i+=`${a.dbPath} sub attribute, value string;
44
+ `,o=Vo(n);for(let a of o)if(a.contentType==="TEXT"||a.contentType==="ID"||a.contentType==="JSON")i+=`${a.dbPath} sub attribute, value string;
71
45
  `;else if(a.contentType==="EMAIL")i+=`${a.dbPath} sub attribute, value string,
72
46
  `,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
47
  `;else if(a.contentType==="DATE")i+=`${a.dbPath} sub attribute, value datetime;
@@ -90,74 +64,62 @@ flexAttribute sub attribute, abstract, value string,
90
64
  owns doubleAttribute,
91
65
  owns booleanAttribute,
92
66
  owns datetimeAttribute;
93
- `},Zr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let i=ss(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 Gr=async(e,t,r)=>await(async()=>{let o=(await Promise.all([...r.typeDB||[]].map(async([l])=>[l,await Zr(l,e,t,r)]))).map(l=>[l[0],l[1]]),a=(await Promise.all([...r.surrealDB||[]].map(async([l])=>[l,Xr(t)]))).map(l=>[l[0],l[1]]);return {typeDB:Object.fromEntries(o),surrealDB:Object.fromEntries(a)}})();var en={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var le=Symbol.for("queryPath"),Rt=Symbol.for("stepPrint"),ve=Symbol.for("edgeType"),Ne=Symbol.for("edgeSchema");var tt=Symbol.for("dbNode"),Zt=Symbol.for("isTransformed"),Lt=Symbol.for("parent"),pe=Symbol.for("fieldSchema"),v=Symbol.for("sharedMetadata"),ft=Symbol.for("flexDataValue"),Oe=Symbol.for("suqlMetadata");var on=(e,t)=>{let r=tn(e.entities),n=tn(e.relations),i=ls(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&&er(o,l.name,s);let d=rn({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&&er(o,l.name,s);let d=rn({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,nn({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=nn({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=Gt(o,a.$things);});}),Object.values(o.relations).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Gt(o,a.$things);}),Object.values(s.roles??{}).forEach(a=>{a.$things=Gt(o,a.$things);});}),o},tn=e=>{let t=[],r=new Set,n=new Set;for(let i of Object.keys(e))sn({thingMap:e,name:i,inProcess:n,seen:r,ordered:t});return t},sn=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&&sn({...e,name:s.extends}),n.delete(r),i.add(r),o.push(r);},as=(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},er=(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&&er(e,n.extends,r);},rn=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=>cs(h,n,d))??[],p=i.linkFields?.map(h=>us({linkField:h,thingName:n,thing:i,schema:t,allLinkFields:a}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([h,$])=>[h,ds($,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:en[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?as(r,i.extends):void 0,dbProviderConfig:l==="surrealDB"?o[l]?.get(i.defaultDBConnector.id)?.providerConfig:void 0}},ls=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},cs=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:ps(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:false,[v]:{fieldType:"dataField"},[Oe]:{dbPath:e.path}}),ds=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[v]:{fieldType:"refField"}}),us=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(!an(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"},[Oe]:{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"},[Oe]:{queryPath:a}}},nn=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"},[Oe]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${r}\`]`:`$parent.\`${r}\``}}},ps=(e,t,r)=>r?t:`${e}\xB7${t}`,an=(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?an(e,n.extends,r):false},Gt=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var cn=e=>{let t=bs(e),r={},n=Es(t);for(let i in t.entities)tr("entity",i,r,t,n);for(let i in t.relations)tr("relation",i,r,t,n);return r},tr=(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?tr(e,s.extends,r,n,i):void 0;a&&fs(a.name,t,r);let l={},d=a?a.idFields:Fs(t,s);if($s(l,s.dataFields??[],t),ms(l,s.refFields??{},t),ys(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&&gs(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},fs=(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;}},$s=(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};Je(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};Je(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};Je(r,o,i),e[n.path]=o;}},ms=(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"};Je(r,s,o),e[n]=s;}},ys=(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}};Je(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};Je(r,u,l),e[o.path]=u;}},gs=(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};Je(r,l,a),e[i]=l;}},Je=(e,t,r)=>{if(r&&!isEqual(t,r))throw new Error(`Duplicate field name "${t.name}" in "${e}"`)},Es=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||ln(r,a.thing,e))continue;if(!ln(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},ln=(e,t,r)=>Bs(e,r).includes(t),Bs=(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}"`)},bs=e=>{let t={entities:{},relations:{}};for(let r in e.entities)dn(r,e,t);for(let r in e.relations)un(r,e,t);return t},dn=(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=dn(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:pn(i,n),linkFields:hn(i,n),refFields:fn(i,n)};return r.entities[e]=o,o}return r.entities[e]=n,n},un=(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=un(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:pn(i,n),linkFields:hn(i,n),refFields:fn(i,n),roles:Ts(i,n)};return r.relations[e]=o,o}return r.relations[e]=n,n},pn=(e,t)=>{let r=new Set(t.dataFields?.map(i=>i.path)??[]);return [...e.dataFields?.filter(i=>!r.has(i.path))??[],...t.dataFields??[]]},hn=(e,t)=>{let r=new Set(t.linkFields?.map(i=>i.path)??[]);return [...e.linkFields?.filter(i=>!r.has(i.path))??[],...t.linkFields??[]]},fn=(e,t)=>({...Object.fromEntries(Object.entries(e.refFields??{}).filter(([n])=>!t.refFields?.[n])),...t.refFields??{}}),Ts=(e,t)=>({...Object.fromEntries(Object.entries(e.roles??{}).filter(([n])=>!t.roles?.[n])),...t.roles??{}});var ir={};xo(ir,{action:()=>Ls,createMachine:()=>Cs,d:()=>Ke,guard:()=>Ms,immediate:()=>Ds,interpret:()=>Mn,invoke:()=>ks,reduce:()=>Fn,state:()=>Os,transition:()=>Qs});function he(e){return {enumerable:true,value:e}}function $n(e){return {enumerable:true,writable:true,value:e}}var Ke={},Ss=()=>true,mn=()=>({}),gn=e=>e,ws=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),Rs=(e,t,r,[n,i])=>t.call(r,e.call(r,n,i),i),Pe=(e,t)=>Object.freeze(Object.create(e,t));function yn(e,t,r){return e.reduce((n,i)=>function(...o){return r(n,i,this,o)},t)}function En(e){return Pe(this,{fn:he(e)})}var Bn={},Fn=En.bind(Bn),Ls=e=>Fn((t,r)=>!!~e(t,r)&&t),bn={},Ms=En.bind(bn);function Mt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Tn(e,t,...r){let n=yn(Mt(bn,r).map(o=>o.fn),Ss,ws),i=yn(Mt(Bn,r).map(o=>o.fn),gn,Rs);return Pe(this,{from:he(e),to:he(t),guards:he(n),reducers:he(i)})}var Sn={},wn={},Qs=Tn.bind(Sn),Ds=Tn.bind(wn,null);function As(e,t,r){return nr(t,e,r,this.immediates)||e}function Rn(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 Ns={enter:gn};function Os(...e){let t=Mt(Sn,e),r=Mt(wn,e),n={final:he(e.length===0),transitions:he(Rn(t))};return r.length&&(n.immediates=he(r),n.enter=he(As)),Pe(Ns,n)}var Is={enter(e,t,r){let n=this.fn.call(t,t.context,r);return rr.isPrototypeOf(n)?Pe(Ln,{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)}},Ln={enter(e,t,r){if(t.child=Mn(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,nr(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function ks(e,...t){let r=he(Rn(t));return rr.isPrototypeOf(e)?Pe(Ln,{machine:he(e),transitions:r}):Pe(Is,{fn:he(e),transitions:r})}var rr={get state(){return {name:this.current,value:this.states[this.current]}}};function Cs(e,t,r=mn){return typeof e!="string"&&(r=t||mn,t=e,e=Object.keys(t)[0]),Ke._create&&Ke._create(e,t),Pe(rr,{context:he(r),current:he(e),states:he(t)})}function nr(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=Pe(l,{current:he(o),original:{value:l}});Ke._onEnter&&Ke._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)?nr(e,n,t,i.transitions.get(r))||n:(Ke._send&&Ke._send(r,o),n)}var Ps={send(e){qs(this,e);}};function Mn(e,t,r,n){let i=Object.create(Ps,{machine:$n(e),context:$n(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:or,interpret:Re,invoke:U,reduce:x,state:me,transition:j}=ir;var te="0.15.6";var An=(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}))},re=(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)}`)},Qt=(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`)},Dt=(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},Nn=(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")},ar=(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`)},lr=(e,t,r)=>ar(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,($,g)=>c.includes($)):{},h=t.$filter?ye(t.$filter,($,g)=>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 On=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},In=(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 At=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},M=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},je=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)(),cr=(e=5)=>customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e)(),kn=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 nt=(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[le]=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=ur(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=Cn(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}else {let p=dr(c)?.flatMap(f=>{let h=Cn(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>Nt(c,u)?true:!l.$excludedFields.includes(u.$path)));}}}))},dr=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]},ur=(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}),Nt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),vs=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=z(s,f),$=t?.$fields?.filter(m=>Nt(h,m)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let m=h.idFields||[];g=[...t.$fields,...m];}else g=t.$fields;else g=dr(h);else g=["id"];t.$excludedFields&&(g=g.filter(m=>Nt(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:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:y,$idNotIncluded:$,$filterByUnique:ur(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[pe]:a}})},Ks=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}},Ys=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(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 $=dr(f);else $=["id"];t.$excludedFields&&($=$.filter(y=>Nt(f,y)?true:!t.$excludedFields.includes(y.$path)));let g=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:g,$idNotIncluded:h,$filterByUnique:ur(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[pe]:a}})},Cn=(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 vs({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?Ys({field:e,fieldStr:n,roleField:a,$justId:i,dbPath:n,schema:r,fieldSchema:a}):l?Ks({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,$]=Qt(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 g=$,[y]=g.$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 Zs=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Gs=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,qn=e=>{let r=e.toString().replace(Zs,"").trim().split("=>")[0].split("{")[0].replace(Gs,"").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 it=({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=qn(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 Pn=(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(m=>m.path===p),$=o.linkFields?.find(m=>m.path===p)?.oppositeLinkFieldsPlayedBy[0],g="roles"in o?An(o.roles,(m,F)=>m===p):void 0,y=f||$||g;if(!y)throw new Error(`no field Def for ${p}`);if(!i[p]){let m=it({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 pr=(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}},jn=(e,t,r)=>{(isArray(t)?t:[t]).forEach(i=>{ze(e,i,r);});};var _n=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"},zn=(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 Ot=(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 Un=e=>isArray(e)?e.map(Un):isObject(e)?{...e,[ft]:true}:e,Wn=(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=_n(o),a=pr(o);if(r[v].fieldType==="refField"){let c=r;if(!isObject(o)){if(c.contentType==="FLEX")return isArray(o)?[Un(o)]:o;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!o.$thing){if(c.contentType==="FLEX")return {...o,[ft]: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=Ot(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,[Ne]:d,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:s,$bzId:a}}if(o.$thing)return [{...o,[Ne]: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,[Ne]:d,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:s,$bzId:pr(o,c)}))});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var It=(e,t)=>{let r=z(t,e).hooks;if(r?.pre){let n=`on${On(e.$op)}`;return r.pre.filter(s=>!s.triggers||s.triggers[n]?.()).flatMap(s=>s.actions)}return []};var Hn=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!At(o)||o.$fields||o[Zt])return;let s=It(o,r).filter(u=>u.type==="transform"),a=clone(Ie(e)),l=clone(Ie(o)),d=n.mutation?.context||{},c=clone(Ie(o[tt]||o.$dbNode));s.forEach(u=>{let p=u.fn(l,a,d,c||{});Object.keys(p).length!==0&&(l={...l,...p,...xe(o),[Zt]:true},Object.assign(o,l));});});};var Jn=(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[tt]||{})),g=It(u,r);for(let y of g)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 Kn=(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 Xn=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}},Zn=(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}=Xn(s);return a?{...l,$op:o}:{$id:s,$op:o}}return s});},Gn=(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}=Xn(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 ti=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=zn(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:Nn(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${je()}`}},...i}});e.$root=isArray(e.$root)?n:n[0];};var kt=(e,t)=>{let r=t[Rt];return isSet(r)?r.has("clean")?(Reflect.set(t,Rt,r.add("clean")),true):false:(Reflect.set(t,Rt,new Set(["clean"])),true)};var ri=(e,t,r)=>{if(kt("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 ni=(e,t,r)=>{let n=Ot(t,r),[i]=n;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Ne]:r};};var ot=e=>{if(Array.isArray(e)){for(let t of e)if(ot(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"&&ot(e[t]))return true}return false};var $a=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(kt("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);},mr=(e,t,r)=>{let n={$rootWrap:{$root:e}},i=ot(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("%"))||ft 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),g=u.at(-2);if(d==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($||"")&&!h.includes(g||"")&&!$?.startsWith("%")&&!g?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(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($a(p,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))continue;let $=h!=="$root"?ar(t,p,h):{[v]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);let{fieldType:g}=$[v],y=["linkField","roleField"].includes(g),m=g==="refField",F=g==="rootField";if(g==="dataField"){continue}if((y||m)&&(p[h]===null?y&&ni(p,h,$):y?Zn(p,h,$):Gn(p,h,$)),F){if(!("$root"in p))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);ti(p,t);}if((y||m)&&Kn(p,h,$,u),(y||m)&&(Wn(p,h,$,t),jn(p,p[h],t)),y||F){ri(p,h,t),Pn(p,h,t);let E=isArray(p[h])?p[h]:[p[h]];for(let w of E){let S=z(t,w),{unidentifiedFields:Q,usedLinkFields:L,usedFields:O,fields:H}=ge(S,w);for(let oe of O)if(!H.includes(oe))throw new Error(`[Schema] Field ${oe} not found in the schema`);if(Q.length>0)throw new Error(`Unknown fields: [${Q.join(",")}] in ${JSON.stringify(a)}`);if(L.length>1){let oe=S.linkFields?.filter(ce=>L.includes(ce.path));if(oe)for(let ce=0;ce<oe.length;ce++){let k=oe[ce];for(let A=0;A<oe.length;A++){let X=oe[A];if(ce!==A&&k.target!==X.target&&k.relation===X.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||(Hn(p,h,t,r),Jn(p,h,t,r));}}}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var Ct=(e,t)=>{if(!t)return;let r=ga(t);return Ea(r,e.query)},ga=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Ea=(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 qt=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[le];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 g=d.dataFields?.find(y=>y.path===$);if(g?.default){let y=it({currentThing:l,fieldSchema:g,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 gt={$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,[gt[c]]:Le(u,t,r)};if(c==="$id")return {...d,$id:void 0,[gt[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return d;if(c==="$exists")return {...d,$exists:void 0,[gt[c]]:u};if(c==="$eq")return {...d,$eq:void 0,[gt[c]]:u};if(c==="$in")return {...d,$in:void 0,[gt[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let p=t in r.entities?r.entities[t]:r.relations[t],[f,h]=Qt(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 g=h[Oe].queryPath;return {...d,[g]: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 ")},st=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 ci=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=[];d.push("SELECT");let c=gr({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=>se(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(g=>h?.map(y=>`${g}:\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(st(l)),typeof a=="number"&&d.push(`LIMIT ${a}`),typeof s=="number"&&d.push(`START ${s}`),d.join(`
94
- `)},gr=e=>{let{queries:t,schema:r,level:n,parentQuery:i}=e,o=[],s=i[le];return o.push(M(`"${s}" as \`$$queryPath\``,n)),o.push(M("record::id(id) as `$id`",n)),o.push(M("record::tb(id) as `$thing`",n)),t.forEach(a=>{let l=La({query:a,level:n,schema:r});l&&o.push(l);}),o.length===0?null:o.join(`,
95
- `)},La=e=>{let{query:t,schema:r,level:n}=e;if(t.$fieldType==="data")return Ma({query:t,level:n});if(t.$fieldType==="ref")throw new Error("Ref fields are not supported in this context");return t.$fieldType==="link"?Qa({query:t,level:n,schema:r}):t.$fieldType==="role"?Da({query:t,level:n,schema:r}):null},Ma=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},Qa=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(M("(",n));let c=n+1;d.push(M("SELECT",c));let u=gr({parentQuery:t,queries:i,level:c+1,schema:r});u&&d.push(u);let p=t[pe][Oe].queryPath;if(d.push(M(`FROM ${p}`,c)),o){let f=Le(o,t.$thing,r),h=be(f);d.push(`WHERE ${h}`);}return l&&d.push(M(st(l),c)),typeof a=="number"&&d.push(M(`LIMIT ${a}`,c)),typeof s=="number"&&d.push(M(`START ${s}`,c)),d.push(M(`) AS \`${t.$as}\``,n)),d.join(`
96
- `)},Da=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let i=[];i.push(M("(",n));let o=n+1;i.push(M("SELECT",o));let s=o+1,a=gr({parentQuery:t,queries:t.$fields,level:s,schema:r});a&&i.push(a);let l=t[pe][Oe].queryPath;if(i.push(M(`FROM ${l}`,o)),t.$filter){let d=Le(t.$filter,t.$playedBy.thing,r),c=be(d);i.push(`WHERE ${c}`);}return i.push(M(`) AS \`${t.$as}\``,n)),i.join(`
97
- `)};var di=e=>{let{queries:t,schema:r}=e;return t.map(n=>Na({query:n,schema:r}))},Na=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[le],u=Er(c),p=ui(i.filter(w=>w.$fieldType==="data")),f=pi(i.filter(w=>w.$fieldType==="link"||w.$fieldType==="role"),r),h=hi(i.filter(w=>w.$fieldType==="ref")),$=[...u,...p,...f,...h].join(`,
98
- `),g=Oa(t,d),y=o?`WHERE id AND (${be(Le(o,n,r))})`:"WHERE id",m=l?st(l):"",F=typeof a=="number"?`LIMIT ${a}`:"",E=typeof s=="number"?`START ${s}`:"";return `SELECT ${$} ${g} ${y} ${m} ${F} ${E}`},Oa=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(s=>se(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")},Er=e=>[`"${e}" as \`$$queryPath\``,"id && record::id(id) || null as `$id`","id && record::tb(id) || null as `$thing`"],ui=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}\``),pi=(e,t)=>e.map(r=>{if(!r[le])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(r)}`);let n=Er(r[le]),i=ui(r.$fields.filter(f=>f.$fieldType==="data")),o=pi(r.$fields.filter(f=>f.$fieldType==="link"||f.$fieldType==="role"),t),s=hi(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?st(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),hi=e=>e.map(t=>{if(!t[le])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(t)}`);let r=Er(t[le]);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 $i=e=>{let{res:t,queries:r,schema:n}=e;return t.map((o,s)=>mi(r[s],o,n))},mi=(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 Br(e,t[0],r)}if(t.length>=1)return t.map(n=>Br(e,n,r))}else throw new Error("res is unexpectedly not an array")},Br=(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={[le]:t.$$queryPath,$id:t.$id,$thing:Hr(n),$thingType:i};return e.$fields.forEach(s=>{let a=s.$as,l=t[a];s.$path==="id"&&e.$idNotIncluded||(o[a]=Ca(s,l,r));}),o},Ca=(e,t,r)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:n}=e[pe];return fi(t,n)??null}if(e.$fieldType==="ref"){let i=(isArray(t)?t:[t]).map(s=>{if(s.$thing){let a=re(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)]),[le]:s.$$queryPath,[l]:s.$id}}return s.$value?fi(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"?Br(e,t[0],r):mi(e,t,r)},fi=(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 yi=async e=>{let{client:t,queries:r,config:n}=e,i=`
101
- BEGIN TRANSACTION;
102
- ${r.join(";")};
103
- COMMIT TRANSACTION;
104
- `;return n.query?.debugger&&ee(`batchedQuery[${te}]`,JSON.stringify({batchedQuery:i})),await t.query(i)};var qa=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,gi=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,at=j("error","error",x((e,t)=>({...e,error:t.error}))),Pa=we("enrich",{enrich:U(async e=>(ee(`originalBQLQuery[${te}]`,JSON.stringify(e.bql.raw)),nt(e.bql.raw,e.schema)),j("done","build",x(qa)),at),build:U(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return ci({queries:e.bql.queries??[],schema:e.schema});if(t==="refs")return di({queries:e.bql.queries??[],schema:e.schema})},j("done","run",x((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),at),run:U(async e=>yi({client:e.client,queries:Ee(e.surql.queries),config:e.config}),j("done","parse",x((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),at),parse:U(async e=>$i({res:Ee(e.surql.res),queries:e.bql.queries??[],schema:e.schema,config:e.config}),j("done","postHooks",x((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),at),postHooks:U(async e=>qt(e.schema,Ee(e.bql.queries),Ee(e.bql.res)),j("done","clean",x(gi)),at),clean:U(async e=>Ct(e.config,Ee(e.bql.res)),j("done","success",x(gi)),at),success:me(),error:me()},e=>e),xa=async e=>new Promise((t,r)=>{Re(Pa,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Ei=async(e,t,r,n)=>xa({bql:{raw:e},surql:{},schema:t,config:r,client:n,error:null});var fe=z$1.json(),Me=z$1.array(fe),Bi=z$1.strictObject({$exists:z$1.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()}),lt=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>lt)).optional(),$not:z$1.lazy(()=>lt).optional()}).catchall(z$1.union([fe,Me,z$1.lazy(()=>z$1.union([Xe,z$1.array(Xe)]))]))),Xe=z$1.lazy(()=>z$1.object({$or:z$1.array(z$1.lazy(()=>lt)).optional(),$not:z$1.lazy(()=>lt).optional(),$exists:z$1.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$1.union([fe,Me,z$1.lazy(()=>z$1.union([Xe,z$1.array(Xe)]))]))),Fi=z$1.object({$id:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),$filter:z$1.union([lt,z$1.array(lt)]).optional(),$fields:z$1.array(z$1.union([z$1.string(),z$1.lazy(()=>ja)])).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()}),ja=Fi.extend({$path:z$1.string(),$as:z$1.string().optional()}),bi=Fi.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 Ti=(e,t,r)=>{let n=t[e.$thing],i=Si({fields:e.$fields,thing:n,schema:t,metadata:r}),o=e.$filter?ct(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:Mi(e.$limit),offset:Qi(e.$offset),sort:Di(i,Ri(e.$sort)),cardinality:a}},Si=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)){let a=Fr(s);a&&o.push(a);}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}`);let p=Fr(u);p&&o.push(p);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"){let u=Fr(a,s.$as);u&&o.push(u);continue}let l=n[a.opposite.thing],d=Si({fields:s.$fields,thing:l,schema:n,metadata:i}),c="$filter"in s&&s.$filter?ct(s.$filter,l,n):void 0;o.push({type:a.type==="role"?"nested_ref":"nested_future_ref",path:s.$path,projection:d,resultCardinality:typeof s.$id=="string"||br(l,c)?"ONE":a.cardinality,fieldCardinality:a.cardinality,alias:s.$as,ids:typeof s.$id=="string"?[s.$id]:s.$id,filter:c,limit:Mi(s.$limit),offset:Qi(s.$offset),sort:Di(d,Ri(s.$sort))});}return {fields:o}},Fr=(e,t)=>{if(!(e.type==="constant"||e.type==="computed"))return e.type==="ref"&&e.contentType==="FLEX"?{type:"flex",path:e.name,cardinality:e.cardinality,alias:t}:e.type==="data"?{type:"data",path:e.name,alias:t}:e.type==="role"||e.type==="ref"?{type:"ref",path:e.name,resultCardinality:e.cardinality,fieldCardinality:e.cardinality,alias:t}:{type:"future_ref",path:e.name,resultCardinality:e.cardinality,fieldCardinality:e.cardinality,alias:t}},ct=(e,t,r)=>Array.isArray(e)?{type:"or",filters:e.map(o=>ct(o,t,r)).filter(o=>!!o)}:{type:"and",filters:_a(e,t,r)},_a=(e,t,r)=>Object.entries(e).map(([n,i])=>{if(n==="$not"&&e.$not)return za(e.$not,t,r);if(n==="$or"&&e.$or)return Va(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"?Ua(o,i):o.type==="ref"?Wa(o,i):wi(o,i,r)}).filter(n=>n!==void 0),za=(e,t,r)=>{let n=ct(e,t,r);return n?{type:"not",filter:n}:void 0},Va=(e,t,r)=>ct(e,t,r),Ua=(e,t)=>{let r=Bi.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=Ha[i];if(s){n.push({type:"scalar",op:s,left:e.name,right:o});continue}let a=Li[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}},Wa=(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,cardinality:e.cardinality};if(xt.safeParse(t).success)return {type:"ref",op:"IN",left:e.name,right:t,tunnel:false,cardinality:e.cardinality};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,cardinality:e.cardinality};if(xt.safeParse(t).success)return {type:"ref",op:"CONTAINSANY",left:e.name,right:t,tunnel:false,cardinality:e.cardinality};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}throw new Error("Filtering by FLEX reference is not supported")},wi=(e,t,r)=>{let n=e.type==="link"&&e.target==="role",i=e.type==="role"?"biref":"future_biref",o=e.type==="role"?"nested_ref":"nested_future_ref",s=e.cardinality,a=e.opposite.cardinality;if(t===null)return {type:"null",op:"IS",left:e.name,tunnel:n};if(typeof t=="string")return {type:i,op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:[t],tunnel:n,cardinality:s,oppositeCardinality:a};if(xt.safeParse(t).success)return {type:e.type==="role"?"biref":"future_biref",op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:t,tunnel:n,cardinality:s,oppositeCardinality:a};let l=Pt.union([Xe,Pt.array(Xe)]).safeParse(t);if(l.error)throw new Error(`Invalid nested filter: ${l.error.message}`);let d=r[e.opposite.thing];if(!d)throw new Error(`Opposite thing ${e.opposite.thing} not found`);let c=[e.opposite.thing,...d.subTypes];if(Array.isArray(l.data))return {type:"or",filters:l.data.map(O=>wi(e,O,r))};let{$eq:u,$ne:p,$contains:f,$containsNot:h,$in:$,$nin:g,$containsAll:y,$containsAny:m,$containsNone:F,...E}=l.data;for(let L of ["$gt","$lt","$gte","$lte"])if(E[L])throw new Error(`Filtering ${e.type} field with ${L} operator is not supported`);let w=[];for(let L of ["$exists","$eq","$ne","$contains","$containsNot"]){let O=l.data[L];if(O!==void 0){if(L==="$exists"){w.push({type:"null",op:O?"IS NOT":"IS",left:e.name,tunnel:n});continue}if((L==="$eq"||L==="$ne")&&O===null){w.push({type:"null",op:L==="$eq"?"IS":"IS NOT",left:e.name,tunnel:n});continue}if(typeof O!="string")throw new Error(`Filter value for ${e.type} field with operator ${L} must be a string`);w.push({type:i,op:L==="$eq"||L==="$contains"?"IN":"NOT IN",left:e.name,right:[O],thing:c,tunnel:n,cardinality:s,oppositeCardinality:a});}}for(let L of ["$in","$nin","$containsAll","$containsAny","$containsNone"]){let O=l.data[L];if(O===void 0)continue;let H=xt.safeParse(O);if(!H.success)throw new Error(`Filter value for ${e.type} field with operator ${L} must be a string array`);let oe=Li[L];if(!oe)throw new Error(`Invalid list operator: ${L}`);w.push({type:i,op:oe,left:e.name,right:H.data,thing:c,tunnel:n,cardinality:s,oppositeCardinality:a});}let S=r[e.opposite.thing];if(!S)throw new Error(`Unknown thing: ${e.opposite.thing}`);let Q=ct(E,S,r);return Q&&w.push({type:o,path:e.name,filter:Q,cardinality:s,oppositeCardinality:a}),{type:"and",filters:w}},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},Ri=e=>{if(!(!e||e.length===0))return e.map(t=>typeof t=="string"?{field:t,desc:false}:{field:t.field,desc:t.desc??false})},Ha={$eq:"=",$ne:"!=",$gt:">",$lt:"<",$gte:">=",$lte:"<=",$contains:"CONTAINS",$containsNot:"CONTAINSNOT"},Li={$in:"IN",$nin:"NOT IN",$containsAll:"CONTAINSALL",$containsAny:"CONTAINSANY",$containsNone:"CONTAINSNONE"},xt=Pt.array(Pt.string()),Mi=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid limit: ${e}`);return e},Qi=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid offset: ${e}`);return e},Di=(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 Ai=(e,t)=>{let r=[],n=e.cardinality==="MANY"?0:1;e.cardinality==="ONE"&&r.push("array::first("),r.push(Ni(e.projection,n,t)),r.push(Oi(e.source,n,t));let i=e.filter&&Ve(e.filter,t);return i&&r.push(Y(`WHERE ${i}`,n)),e.sort&&e.sort.length>0&&r.push(Ii(e.sort,n)),e.limit!==void 0&&r.push(Y(`LIMIT ${e.limit}`,n)),e.offset!==void 0&&r.push(Y(`START ${e.offset}`,n)),e.cardinality==="ONE"&&r.push(")"),r.join(`
105
- `)},Ni=(e,t,r)=>{let n=[],i=t+1;for(let s of e.fields)s.type==="metadata"?n.push(va(s,i)):s.type==="data"?n.push(Ja(s,i)):s.type==="ref"||s.type==="future_ref"?n.push(Ka(s,i)):s.type==="nested_ref"||s.type==="nested_future_ref"?n.push(Ya(s,i,r)):s.type==="flex"&&n.push(Xa(s,i));let o=[];return o.push(Y("SELECT",t)),o.push(n.join(`,
67
+ `},zr=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 Wr=async(e,t,r,n)=>await(async()=>{let s=(await Promise.all([...n.typeDB||[]].map(async([p])=>[p,await zr(p,e,t,n)]))).map(p=>[p[0],p[1]]),l=(await Promise.all([...n.surrealDB||[]].map(async([p])=>[p,Vr(r)]))).map(p=>[p[0],p[1]]);return {typeDB:Object.fromEntries(s),surrealDB:Object.fromEntries(l)}})();var Ur={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var Le=Symbol.for("queryPath"),Tt=Symbol.for("stepPrint"),ve=Symbol.for("edgeType"),Me=Symbol.for("edgeSchema");var et=Symbol.for("dbNode"),Ht=Symbol.for("isTransformed"),tt=Symbol.for("parent"),ke=Symbol.for("fieldSchema"),J=Symbol.for("sharedMetadata"),ut=Symbol.for("flexDataValue"),He=Symbol.for("suqlMetadata");var Kr=(e,t)=>{let r=vr(e.entities),n=vr(e.relations),i=Uo(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&&Kt(o,l.name,s);let p=Hr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i});o.entities[s]={...p,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&&Kt(o,l.name,s);let p=Hr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i}),c={...p,defaultDBConnector:a.defaultDBConnector,roles:Object.fromEntries(Object.entries(a.roles??{}).map(([u,d])=>[u,Jr({role:d,roleName:u,relationName:s,relation:a,allExtends:p.allExtends,allLinkFields:i})])),thingType:"relation"};"extends"in a&&l&&Object.entries(l?.roles??{}).forEach(([u,d])=>{let f=Jr({role:d,roleName:u,relationName:s,relation:a,allExtends:p.allExtends,allLinkFields:i});c.roles[u]={...f,inherited:true,[J]:{...d[J],inheritanceOrigin:d[J]?.inheritanceOrigin||a.extends}};}),o.relations[s]=c;}),Object.values(o.entities).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Jt(o,a.$things);});}),Object.values(o.relations).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Jt(o,a.$things);}),Object.values(s.roles??{}).forEach(a=>{a.$things=Jt(o,a.$things);});}),o},vr=e=>{let t=[],r=new Set,n=new Set;for(let i of Object.keys(e))Yr({thingMap:e,name:i,inProcess:n,seen:r,ordered:t});return t},Yr=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&&Yr({...e,name:s.extends}),n.delete(r),i.add(r),o.push(r);},Wo=(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},Kt=(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&&Kt(e,n.extends,r);},Hr=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 p=[...i.idFields??s?.idFields??[]];if(p.length===0)throw new Error(`"${n}" does not have an id field`);let c={...i.hooks},u=i.dataFields?.map(h=>vo(h,n,p))??[],d=i.linkFields?.map(h=>Jo({linkField:h,thingName:n,thing:i,schema:t,allLinkFields:a}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([h,$])=>[h,Ho($,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=>{d.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:Ur[l],idFields:p,hooks:c,dataFields:u,linkFields:d,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?Wo(r,i.extends):void 0}},Uo=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},vo=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:Ko(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:false,[J]:{fieldType:"dataField"},[He]:{dbPath:e.path}}),Ho=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[J]:{fieldType:"refField"}}),Jo=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(!Zr(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"},[He]:{queryPath:a}}}let l=o.filter(p=>p.relation===t.relation&&p.plays!==t.plays&&p.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(p=>p.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(p=>p.target==="relation"&&p.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:false,$things:l.map(p=>p.thing),oppositeLinkFieldsPlayedBy:l,[J]:{fieldType:"linkField"},[He]:{queryPath:a}}},Jr=e=>{let{role:t,roleName:r,relationName:n,relation:i,allExtends:o,allLinkFields:s}=e;if(i.dataFields?.find(p=>p.path===r)||i.linkFields?.find(p=>p.path===r))throw new Error(`[Schema] The path ${r} is already in use by a dataField or linkField in ${n}.`);let a=s.filter(p=>p.relation===n&&p.plays===r),l=s.filter(p=>p.target==="relation"&&p.plays===r&&o?.includes(p.relation));return {...t,fieldType:"roleField",inherited:false,playedBy:a.map(p=>({...p,pathToRelation:p.target==="relation"?p.path:i.linkFields?.find(c=>c.target==="relation"&&c.relation===r&&c.plays===r)?.path??p.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:r,$things:[...new Set(a.map(p=>p.thing))],[J]:{fieldType:"roleField"},[He]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${r}\`]`:`$parent.\`${r}\``}}},Ko=(e,t,r)=>r?t:`${e}\xB7${t}`,Zr=(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?Zr(e,n.extends,r):false},Jt=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var en=e=>{let t=os(e),r={},n=rs(t);for(let i in t.entities)Yt("entity",i,r,t,n);for(let i in t.relations)Yt("relation",i,r,t,n);return r},Yt=(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?Yt(e,s.extends,r,n,i):void 0;a&&Zo(a.name,t,r);let l={},p=a?a.idFields:is(t,s);if(Xo(l,s.dataFields??[],t),Go(l,s.refFields??{},t),es(l,s.linkFields??[],t,n,i),e==="entity"){Xr(t,l);let u={type:"entity",name:t,idFields:p,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=u,u}"roles"in s&&s.roles&&ts(l,s.roles??{},t,i),Xr(t,l);let c={type:"relation",name:t,idFields:p,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=c,c},Zo=(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;}},Xo=(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};Je(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};Je(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,validations:n.validations,isVirtual:n.isVirtual,dbValue:n.dbValue};Je(r,o,i),e[n.path]=o;}},Go=(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"};Je(r,s,o),e[n]=s;}},es=(e,t,r,n,i)=>{for(let o of t??[]){if(/[^a-zA-Z0-9_\-\s]/.test(o.path))throw new Error(`Invalid link field name "${o.path}" in "${r}": only alphanumeric characters, underscores, dashes, and spaces are allowed`);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 h={type:"link",name:o.path,cardinality:o.cardinality,target:"relation",relation:o.relation,plays:o.plays,opposite:{thing:o.relation,path:o.plays,cardinality:a.cardinality},isVirtual:o.isVirtual,dbValue:o.dbValue};Je(r,h,l),e[o.path]=h;continue}let p=i[o.relation]?.[o.targetRole];if(!p)throw new Error(`Role ${o.targetRole} in relation ${o.relation} does not exist`);let c=p.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=s.roles?.[o.targetRole];if(!u)throw new Error(`Target role ${o.targetRole} not found in relation ${o.relation}`);let d=u.cardinality;if(o.cardinality==="ONE"&&d==="MANY")throw new Error(`Invalid link field "${o.path}": cardinality ONE with target role "${o.targetRole}" cardinality MANY is not allowed (relation: ${o.relation})`);let f={type:"link",name:o.path,cardinality:o.cardinality,target:"role",relation:o.relation,plays:o.plays,targetRole:o.targetRole,targetRoleCardinality:d,opposite:c,isVirtual:o.isVirtual,dbValue:o.dbValue};Je(r,f,l),e[o.path]=f;}},ts=(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",onDelete:o.onDelete,opposite:s};Je(r,l,a),e[i]=l;}},Je=(e,t,r)=>{if(r&&!isEqual(t,r))throw new Error(`Duplicate field name "${t.name}" in "${e}"`)},Xr=(e,t)=>{let r=new Map,n=(i,o,s)=>{let a=r.get(i);if(a&&a.originalName!==o)throw new Error(`Field name conflict in "${e}": ${s} field "${o}" resolves to "${i}" which conflicts with ${a.fieldType} field "${a.originalName}"`);r.set(i,{originalName:o,fieldType:s});};for(let i of Object.values(t))if(i.type==="link"){n(i.name,i.name,i.type);let o=Be(i.name);o!==i.name&&n(o,i.name,i.type);}else n(i.name,i.name,i.type);},rs=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||Gr(r,a.thing,e))continue;if(!Gr(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},Gr=(e,t,r)=>ns(e,r).includes(t),ns=(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()},is=(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}"`)},os=e=>{let t={entities:{},relations:{}};for(let r in e.entities)tn(r,e,t);for(let r in e.relations)rn(r,e,t);return t},tn=(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=tn(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:nn(i,n),linkFields:on(i,n),refFields:sn(i,n)};return r.entities[e]=o,o}return r.entities[e]=n,n},rn=(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=rn(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:nn(i,n),linkFields:on(i,n),refFields:sn(i,n),roles:ss(i,n)};return r.relations[e]=o,o}return r.relations[e]=n,n},nn=(e,t)=>{let r=new Set(t.dataFields?.map(i=>i.path)??[]);return [...e.dataFields?.filter(i=>!r.has(i.path))??[],...t.dataFields??[]]},on=(e,t)=>{let r=new Set(t.linkFields?.map(i=>i.path)??[]);return [...e.linkFields?.filter(i=>!r.has(i.path))??[],...t.linkFields??[]]},sn=(e,t)=>({...Object.fromEntries(Object.entries(e.refFields??{}).filter(([n])=>!t.refFields?.[n])),...t.refFields??{}}),ss=(e,t)=>({...Object.fromEntries(Object.entries(e.roles??{}).filter(([n])=>!t.roles?.[n])),...t.roles??{}});var Gt={};Fo(Gt,{action:()=>ds,createMachine:()=>Es,d:()=>Ke,guard:()=>us,immediate:()=>hs,interpret:()=>Bn,invoke:()=>gs,reduce:()=>hn,state:()=>ms,transition:()=>ps});function ue(e){return {enumerable:true,value:e}}function an(e){return {enumerable:true,writable:true,value:e}}var Ke={},as=()=>true,ln=()=>({}),dn=e=>e,ls=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),cs=(e,t,r,[n,i])=>t.call(r,e.call(r,n,i),i),Ce=(e,t)=>Object.freeze(Object.create(e,t));function cn(e,t,r){return e.reduce((n,i)=>function(...o){return r(n,i,this,o)},t)}function un(e){return Ce(this,{fn:ue(e)})}var pn={},hn=un.bind(pn),ds=e=>hn((t,r)=>!!~e(t,r)&&t),fn={},us=un.bind(fn);function wt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function $n(e,t,...r){let n=cn(wt(fn,r).map(o=>o.fn),as,ls),i=cn(wt(pn,r).map(o=>o.fn),dn,cs);return Ce(this,{from:ue(e),to:ue(t),guards:ue(n),reducers:ue(i)})}var mn={},yn={},ps=$n.bind(mn),hs=$n.bind(yn,null);function fs(e,t,r){return Xt(t,e,r,this.immediates)||e}function gn(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 $s={enter:dn};function ms(...e){let t=wt(mn,e),r=wt(yn,e),n={final:ue(e.length===0),transitions:ue(gn(t))};return r.length&&(n.immediates=ue(r),n.enter=ue(fs)),Ce($s,n)}var ys={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Zt.isPrototypeOf(n)?Ce(En,{machine:ue(n),transitions:ue(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)}},En={enter(e,t,r){if(t.child=Bn(this.machine,n=>{t.onChange(n),t.child==n&&n.machine.state.value.final&&(delete t.child,t.send({type:"done",data:n.context}));},t.context,r),t.child.machine.state.value.final){let n=t.child.context;return delete t.child,Xt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function gs(e,...t){let r=ue(gn(t));return Zt.isPrototypeOf(e)?Ce(En,{machine:ue(e),transitions:r}):Ce(ys,{fn:ue(e),transitions:r})}var Zt={get state(){return {name:this.current,value:this.states[this.current]}}};function Es(e,t,r=ln){return typeof e!="string"&&(r=t||ln,t=e,e=Object.keys(t)[0]),Ke._create&&Ke._create(e,t),Ce(Zt,{context:ue(r),current:ue(e),states:ue(t)})}function Xt(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,p=Ce(l,{current:ue(o),original:{value:l}});Ke._onEnter&&Ke._onEnter(t,o,e.context,i,r);let c=p.state.value;e.machine=p;let u=c.enter(p,e,r);return e.onChange(e),u}}function Bs(e,t){let r=t.type||t,{machine:n}=e,{value:i,name:o}=n.state;return i.transitions.has(r)?Xt(e,n,t,i.transitions.get(r))||n:(Ke._send&&Ke._send(r,o),n)}var Fs={send(e){Bs(this,e);}};function Bn(e,t,r,n){let i=Object.create(Fs,{machine:an(e),context:an(e.context(r,n)),onChange:ue(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,n),i}var{createMachine:De,guard:er,interpret:Ae,invoke:X,reduce:U,state:ge,transition:v}=Gt;var ce="0.16.0";var Tn=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],fe=(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}))},ne=(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)}`)},Rt=(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`)},St=(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},wn=(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")},rr=(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`)},nr=(e,t,r)=>rr(e,t,r)?.cardinality,$e=(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 p=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($)):[],d=[...p,...c].filter($=>!$?.startsWith("%")).filter($=>!l.includes($)).filter($=>$),f=t.$filter?fe(t.$filter,($,g)=>c.includes($)):{},h=t.$filter?fe(t.$filter,($,g)=>u.includes($)):{};return {fields:s,dataFields:r,roleFields:o,linkFields:n,refFields:i,usedFields:p,usedLinkFields:n.filter($=>p.includes($)),usedRoleFields:o.filter($=>p.includes($)),usedDataFields:r.filter($=>p.includes($)),usedRefFields:i.filter($=>p.includes($)),unidentifiedFields:d,...c.length?{localFilters:f}:{},...u.length?{nestedFilters:h}:{}}};var Rn=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Sn=(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),Qe=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},Te=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},I=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Pe=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)(),ir=(e=5)=>customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e)();var Dt=(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[Le]=a.nodePath,l.$id){let p=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=V(t,p);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 p=V(t,l);if(!p?.name)throw new Error(`Schema not found for ${l.$thing}`);l.$path=p.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 p=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=V(t,p);if(l.$filter&&(Object.keys(l.$filter).length===0?l.$filter=void 0:(l.$filter=_e(l.$filter,l.$thing,t),l.$filterByUnique=sr(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 d=l.$fields?.flatMap(f=>{let h=Ln(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=d;}else {let d=or(c)?.flatMap(f=>{let h=Ln(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=d;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>Mt(c,u)?true:!l.$excludedFields.includes(u.$path)));}}}))},or=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]},sr=(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(p=>(p.dbPath===n||p.path===n)&&p?.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 p=Object.keys(i);if(p.length===1&&p[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),Ms=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,[ke]:s}},Ds=e=>{let{field:t,fieldStr:r,linkField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e,{target:l,oppositeLinkFieldsPlayedBy:p}=n;return p.map(c=>{let u=l==="role"?c.thingType:"relation",d=l==="role"?c.thing:n.relation,f={[`$${u}`]:d},h=V(s,f),$=t?.$fields?.filter(E=>Mt(h,E)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let E=h.idFields||[];g=[...t.$fields,...E];}else g=t.$fields;else g=or(h);else g=["id"];t.$excludedFields&&(g=g.filter(E=>Mt(h,E)?true:!t.$excludedFields.includes(E.$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:d,$fields:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:sr(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ke]:a}})},As=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,[ke]:o}},Qs=e=>{let{field:t,fieldStr:r,roleField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e;return n.playedBy.map(l=>{let{thing:p,thingType:c,relation:u}=l,d={[`$${c}`]:p},f=V(s,d),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 $=or(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>Mt(f,m)?true:!t.$excludedFields.includes(m.$path)));let g=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:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:i,$id:t.$id,$filter:g,$idNotIncluded:h,$filterByUnique:sr(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ke]:a}})},Ln=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,i=typeof e=="string",o=t.dataFields?.find(p=>p.path===n),s=t.linkFields?.find(p=>p.path===n),a=t.roles?.[n],l=t.refFields?.[n];if(o){let p=!!o.isVirtual&&!!o.default;return Ms({field:e,fieldStr:n,$justId:i,dbPath:o.dbPath,isVirtual:p,fieldSchema:o})}return s?Ds({field:e,fieldStr:n,linkField:s,$justId:i,dbPath:s.path,schema:r,fieldSchema:s}):a?Qs({field:e,fieldStr:n,roleField:a,$justId:i,dbPath:n,schema:r,fieldSchema:a}):l?As({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((p,c)=>{let u=s[c],d=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))p[c]=u;else if(["$not","$or","$and"].includes(c))p[c]=_e(u,t,r);else if(["$eq","$in","$exists"].includes(c))p[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,$]=Rt(f,c);if(h==="idField")p[c]=u;else if(h==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?p[c]=isArray(u)?{$or:_e(u,t,r)}:_e(u,t,r):isArray(u)?p[c]={$in:u}:p[c]={$eq:u};else if(h==="linkField"||h==="roleField"){let g=$,[m]=g.$things;d.every(E=>typeof E=="string")?p[c]={$id:d,$thing:m}:d.every(E=>isObject(E))&&(p[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 p},{}));return !n||o.length===1?o[0]:{$or:o}};var Ns=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Is=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Mn=e=>{let r=e.toString().replace(Ns,"").trim().split("=>")[0].split("{")[0].replace(Is,"").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=Mn(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 Dn=(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}=$e(o,i),{computedFields:a,virtualFields:l}=o,p=listify(i,(d,f)=>f!==void 0?d:void 0),c=p.filter(d=>l?.includes(d));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(a.filter(d=>!p.includes(d)).forEach(d=>{let f=o.dataFields?.find(E=>E.path===d),$=o.linkFields?.find(E=>E.path===d)?.oppositeLinkFieldsPlayedBy[0],g="roles"in o?Tn(o.roles,(E,T)=>E===d):void 0,m=f||$||g;if(!m)throw new Error(`no field Def for ${d}`);if(!i[d]){let E=nt({currentThing:i,fieldSchema:m,mandatoryDependencies:true});i[d]=E;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(i)}`)}),e};var ar=(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}_${Pe()}`:`SN_MANY_${Pe()}`:`SM_${Pe()}`;var je=(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}=$e(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}},Qn=(e,t,r)=>{(isArray(t)?t:[t]).forEach(i=>{je(e,i,r);});};var On=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"},Nn=(e,t,r)=>{let n=V(r,t),{usedFields:i}=$e(n,t);return t.$op?(je(e,t,r),t.$op):t.$id||t.$filter?i.length>0?(je(e,{...t,$op:"update"},r),"update"):(je(e,{...t,$op:"link"},r),"link"):t.$tempId?i.length>0?(je(e,{...t,$op:"create"},r),"create"):(je(e,{...t,$op:"create"},r),"link"):(je(e,{...t,$op:"create"},r),"create")};var At=(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 kn=e=>isArray(e)?e.map(kn):isObject(e)?{...e,[ut]:true}:e,Cn=(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=On(o),a=ar(o);if(r[J].fieldType==="refField"){let c=r;if(!isObject(o)){if(c.contentType==="FLEX")return isArray(o)?[kn(o)]:o;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!o.$thing){if(c.contentType==="FLEX")return {...o,[ut]: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 p=r;if(p.$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,[Me]:p,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:s,$bzId:a}}if(o.$thing)return [{...o,[Me]:p,$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 p.$things.map(c=>({...o,[Me]:p,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:s,$bzId:ar(o,c)}))});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var Qt=(e,t)=>{let r=V(t,e).hooks;if(r?.pre){let n=`on${Rn(e.$op)}`;return r.pre.filter(s=>!s.triggers||s.triggers[n]?.()).flatMap(s=>s.actions)}return []};var xn=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!Lt(o)||o.$fields||o[Ht])return;let s=Qt(o,r).filter(u=>u.type==="transform"),a=clone(Qe(e)),l=clone(Qe(o)),p=n.mutation?.context||{},c=clone(Qe(o[et]||o.$dbNode));s.forEach(u=>{let d=u.fn(l,a,p,c||{});Object.keys(d).length!==0&&(l={...l,...d,...xe(o),[Ht]:true},Object.assign(o,l));});});};var _n=(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:p}=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=p?.find(d=>d.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(o[c])){for(let d of o[c])if(d!==null&&!u.includes(d))throw new Error(`[Validations] Option "${d}" 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=p?.find(d=>d.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,d=clone(Qe(e)),f=clone(Qe(u)),h=n.mutation?.context||{},$=clone(Qe(o[et]||{})),g=Qt(u,r);for(let m of g)if(m.type==="validate"){if(m.severity!=="error")continue;try{let E=m.fn(f,d,h,$);if(E===!1)throw new Error(`${m.message}.`);if(E!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(E){throw new Error(`[Validations:thing:${c}] ${E.message}`)}}}}};var jn=(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}},zn=(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?.[J].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}=Vn(s);return a?{...l,$op:o}:{$id:s,$op:o}}return s});},Wn=(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 vn=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=Nn(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:wn(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${Pe()}`}},...i}});e.$root=isArray(e.$root)?n:n[0];};var Ot=(e,t)=>{let r=t[Tt];return isSet(r)?r.has("clean")?(Reflect.set(t,Tt,r.add("clean")),true):false:(Reflect.set(t,Tt,new Set(["clean"])),true)};var Hn=(e,t,r)=>{if(Ot("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)=>({...Qe(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 Jn=(e,t,r)=>{let n=At(t,r),[i]=n;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Me]: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 Ys=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Ot("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);},ur=(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:p,meta:c})=>{if(!(!l||!p)&&isObject(a)){let u=c.nodePath?.split(".")||[];if(u.some(h=>h.startsWith("%"))||ut 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),g=u.at(-2);if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($||"")&&!h.includes(g||"")&&!$?.startsWith("%")&&!g?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let d=a,f=u.includes("$filter");"$filter"in d&&d.$filter&&(d.$filter=_e(d.$filter,d.$thing,t));for(let h of Object.keys(d)){if(Ys(d,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))continue;let $=h!=="$root"?rr(t,d,h):{[J]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);let{fieldType:g}=$[J],m=["linkField","roleField"].includes(g),E=g==="refField",T=g==="rootField";if(g==="dataField"){continue}if((m||E)&&(d[h]===null?m&&Jn(d,h,$):m?zn(d,h,$):Wn(d,h,$)),T){if(!("$root"in d))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);vn(d,t);}if((m||E)&&jn(d,h,$,u),(m||E)&&(Cn(d,h,$,t),Qn(d,d[h],t)),m||T){Hn(d,h,t),Dn(d,h,t);let y=isArray(d[h])?d[h]:[d[h]];for(let w of y){let M=V(t,w),{unidentifiedFields:Q,usedLinkFields:b,usedFields:A,fields:k}=$e(M,w);for(let j of A)if(!k.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`);if(Q.length>0)throw new Error(`Unknown fields: [${Q.join(",")}] in ${JSON.stringify(a)}`);if(b.length>1){let j=M.linkFields?.filter(G=>b.includes(G.path));if(j)for(let G=0;G<j.length;G++){let D=j[G];for(let N=0;N<j.length;N++){let z=j[N];if(G!==N&&D.target!==z.target&&D.relation===z.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||(xn(d,h,t,r),_n(d,h,t,r));}}}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var pe=z.json(),Fe=z.array(pe),Yn=z.strictObject({$exists:z.boolean().optional(),$eq:pe.optional(),$neq:pe.optional(),$gt:pe.optional(),$lt:pe.optional(),$gte:pe.optional(),$lte:pe.optional(),$contains:pe.optional(),$containsNot:pe.optional(),$in:Fe.optional(),$nin:Fe.optional(),$containsAll:Fe.optional(),$containsAny:Fe.optional(),$containsNone:Fe.optional()}),ot=z.lazy(()=>z.object({$or:z.array(z.lazy(()=>ot)).optional(),$not:z.lazy(()=>ot).optional()}).catchall(z.union([pe,Fe,z.lazy(()=>z.union([Ye,z.array(Ye)]))]))),Ye=z.lazy(()=>z.object({$or:z.array(z.lazy(()=>ot)).optional(),$not:z.lazy(()=>ot).optional(),$exists:z.boolean().optional(),$eq:pe.optional(),$neq:pe.optional(),$gt:pe.optional(),$lt:pe.optional(),$gte:pe.optional(),$lte:pe.optional(),$contains:pe.optional(),$containsNot:pe.optional(),$in:Fe.optional(),$nin:Fe.optional(),$containsAll:Fe.optional(),$containsAny:Fe.optional(),$containsNone:Fe.optional()}).catchall(z.union([pe,Fe,z.lazy(()=>z.union([Ye,z.array(Ye)]))]))),Zn=z.object({$id:z.union([z.string(),z.array(z.string())]).optional(),$filter:z.union([ot,z.array(ot)]).optional(),$fields:z.array(z.union([z.string(),z.lazy(()=>Xs)])).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()}),Xs=Zn.extend({$path:z.string(),$as:z.string().optional()}),Xn=Zn.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 Gn=(e,t,r)=>{let n=t[e.$thing],i=ei({fields:e.$fields,thing:n,schema:t,metadata:r}),o=e.$filter?st(e.$filter,n,t):void 0,s=Array.isArray(e.$id)?e.$id:e.$id?[e.$id]:[],a=s.length===1||hr(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:ii(e.$limit),offset:oi(e.$offset),sort:si(i,ri(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)){let a=pr(s);a&&o.push(a);}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}`);let d=pr(u);d&&o.push(d);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"){let u=pr(a,s.$as);u&&o.push(u);continue}let l=n[a.opposite.thing],p=ei({fields:s.$fields,thing:l,schema:n,metadata:i}),c="$filter"in s&&s.$filter?st(s.$filter,l,n):void 0;o.push({type:a.type==="role"?"nested_ref":"nested_computed_ref",path:s.$path,projection:p,resultCardinality:typeof s.$id=="string"||hr(l,c)?"ONE":a.cardinality,fieldCardinality:a.cardinality,alias:s.$as,ids:typeof s.$id=="string"?[s.$id]:s.$id,filter:c,limit:ii(s.$limit),offset:oi(s.$offset),sort:si(p,ri(s.$sort))});}return {fields:o}},pr=(e,t)=>{if(!(e.type==="constant"||e.type==="computed"))return e.type==="ref"&&e.contentType==="FLEX"?{type:"flex",path:e.name,cardinality:e.cardinality,alias:t}:e.type==="data"?{type:"data",path:e.name,alias:t}:e.type==="role"||e.type==="ref"?{type:"ref",path:e.name,resultCardinality:e.cardinality,fieldCardinality:e.cardinality,alias:t}:{type:"computed_ref",path:e.name,resultCardinality:e.cardinality,fieldCardinality:e.cardinality,alias:t}},st=(e,t,r)=>Array.isArray(e)?{type:"or",filters:e.map(o=>st(o,t,r)).filter(o=>!!o)}:{type:"and",filters:Gs(e,t,r)},Gs=(e,t,r)=>Object.entries(e).map(([n,i])=>{if(n==="$not"&&e.$not)return ea(e.$not,t,r);if(n==="$or"&&e.$or)return ta(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"?ra(o,i):o.type==="ref"?na(o,i):ti(o,i,r)}).filter(n=>n!==void 0),ea=(e,t,r)=>{let n=st(e,t,r);return n?{type:"not",filter:n}:void 0},ta=(e,t,r)=>st(e,t,r),ra=(e,t)=>{let r=Yn.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,emptyIsArray:false});continue}if((i==="$eq"||i==="$ne")&&o===null){n.push({type:"null",op:i==="$eq"?"IS":"IS NOT",left:e.name,emptyIsArray:false});continue}let s=ia[i];if(s){n.push({type:"scalar",op:s,left:e.name,right:o});continue}let a=ni[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,emptyIsArray:false}:{type:"scalar",op:"=",left:e.name,right:t}:{type:"scalar",op:"CONTAINS",left:e.name,right:t}},na=(e,t)=>{if(e.contentType==="REF"){if(e.cardinality==="ONE"){if(typeof t=="string")return {type:"ref",op:"IN",left:e.name,right:[t],cardinality:e.cardinality};if(It.safeParse(t).success)return {type:"ref",op:"IN",left:e.name,right:t,cardinality:e.cardinality};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],cardinality:e.cardinality};if(It.safeParse(t).success)return {type:"ref",op:"CONTAINSANY",left:e.name,right:t,cardinality:e.cardinality};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}throw new Error("Filtering by FLEX reference is not supported")},ti=(e,t,r)=>{let n=e.type==="link"&&e.cardinality==="MANY",i=e.type==="role"?"biref":"computed_biref",o=e.type==="role"?"nested_ref":"nested_computed_ref",s=e.cardinality,a=e.opposite.cardinality;if(t===null)return {type:"null",op:"IS",left:e.name,emptyIsArray:n};if(typeof t=="string")return {type:i,op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:[t],cardinality:s,oppositeCardinality:a};if(It.safeParse(t).success)return {type:i,op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:t,cardinality:s,oppositeCardinality:a};let l=Nt.union([Ye,Nt.array(Ye)]).safeParse(t);if(l.error)throw new Error(`Invalid nested filter: ${l.error.message}`);let p=r[e.opposite.thing];if(!p)throw new Error(`Opposite thing ${e.opposite.thing} not found`);let c=[e.opposite.thing,...p.subTypes];if(Array.isArray(l.data))return {type:"or",filters:l.data.map(A=>ti(e,A,r))};let{$eq:u,$ne:d,$contains:f,$containsNot:h,$in:$,$nin:g,$containsAll:m,$containsAny:E,$containsNone:T,...y}=l.data;for(let b of ["$gt","$lt","$gte","$lte"])if(y[b])throw new Error(`Filtering ${e.type} field with ${b} operator is not supported`);let w=[];for(let b of ["$exists","$eq","$ne","$contains","$containsNot"]){let A=l.data[b];if(A!==void 0){if(b==="$exists"){w.push({type:"null",op:A?"IS NOT":"IS",left:e.name,emptyIsArray:n});continue}if((b==="$eq"||b==="$ne")&&A===null){w.push({type:"null",op:b==="$eq"?"IS":"IS NOT",left:e.name,emptyIsArray:n});continue}if(typeof A!="string")throw new Error(`Filter value for ${e.type} field with operator ${b} must be a string`);w.push({type:i,op:b==="$eq"||b==="$contains"?"IN":"NOT IN",left:e.name,right:[A],thing:c,cardinality:s,oppositeCardinality:a});}}for(let b of ["$in","$nin","$containsAll","$containsAny","$containsNone"]){let A=l.data[b];if(A===void 0)continue;let k=It.safeParse(A);if(!k.success)throw new Error(`Filter value for ${e.type} field with operator ${b} must be a string array`);let j=ni[b];if(!j)throw new Error(`Invalid list operator: ${b}`);w.push({type:i,op:j,left:e.name,right:k.data,thing:c,cardinality:s,oppositeCardinality:a});}let M=r[e.opposite.thing];if(!M)throw new Error(`Unknown thing: ${e.opposite.thing}`);let Q=st(y,M,r);return Q&&w.push({type:o,path:e.name,filter:Q,cardinality:s,oppositeCardinality:a}),{type:"and",filters:w}},hr=(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=>hr(e,r)):false},ri=e=>{if(!(!e||e.length===0))return e.map(t=>typeof t=="string"?{field:t,desc:false}:{field:t.field,desc:t.desc??false})},ia={$eq:"=",$ne:"!=",$gt:">",$lt:"<",$gte:">=",$lte:"<=",$contains:"CONTAINS",$containsNot:"CONTAINSNOT"},ni={$in:"IN",$nin:"NOT IN",$containsAll:"CONTAINSALL",$containsAny:"CONTAINSANY",$containsNone:"CONTAINSNONE"},It=Nt.array(Nt.string()),ii=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid limit: ${e}`);return e},oi=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid offset: ${e}`);return e},si=(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 ai=(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(ci(e.source,n,t));let i=e.filter&&qe(e.filter,t);return i&&r.push(Z(`WHERE ${i}`,n)),e.sort&&e.sort.length>0&&r.push(di(e.sort,n)),e.limit!==void 0&&r.push(Z(`LIMIT ${e.limit}`,n)),e.offset!==void 0&&r.push(Z(`START ${e.offset}`,n)),e.cardinality==="ONE"&&r.push(")"),r.join(`
68
+ `)},li=(e,t,r)=>{let n=[],i=t+1;for(let s of e.fields)s.type==="metadata"?n.push(oa(s,i)):s.type==="data"?n.push(sa(s,i)):s.type==="ref"||s.type==="computed_ref"?n.push(aa(s,i)):s.type==="nested_ref"||s.type==="nested_computed_ref"?n.push(la(s,i,r)):s.type==="flex"&&n.push(ca(s,i));let o=[];return o.push(Z("SELECT",t)),o.push(n.join(`,
106
69
  `)),o.join(`
107
- `)},va=(e,t)=>{if(e.path==="$id")return Y(`record::id(id) AS ${Z(e.alias??"$id")}`,t);if(e.path==="$thing")return Y(`record::tb(id) AS ${Z(e.alias??"$thing")}`,t);throw new Error(`Unsupported metadata field: ${e.path}`)},Ja=(e,t)=>{if(e.path==="id")return Y(`record::id(id) AS ${Z(e.alias??"id")}`,t);let r=Z(e.path);return e.alias?Y(`${r} AS ${Z(e.alias)}`,t):Y(r,t)},Ka=(e,t)=>{let{path:r,alias:n}=e,i=Z(r),o=Z(n||r),s=e.fieldCardinality==="ONE"&&e.type==="ref"?`SELECT VALUE record::id(id) FROM $this.${i}`:`SELECT VALUE record::id(id) FROM $this.${i}[*]`;return e.resultCardinality==="ONE"?Y(`array::first(${s}) AS ${o}`,t):Y(`(${s}) AS ${o}`,t)},Ya=(e,t,r)=>{let n=[];e.resultCardinality==="MANY"?n.push(Y("(",t)):n.push(Y("array::first(",t)),n.push(Ni(e.projection,t+1,r));let i=e.filter?Ve(e.filter,r):void 0;e.fieldCardinality==="ONE"&&e.type==="nested_ref"?n.push(Y(`FROM $this.${Z(e.path)}`,t+1)):n.push(Y(`FROM $this.${Z(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(Y(`WHERE ${o.join(" AND ")}`,t+1)),e.sort&&e.sort.length>0&&n.push(Ii(e.sort,t+1)),e.limit!==void 0&&n.push(Y(`LIMIT ${e.limit}`,t+1)),e.offset!==void 0&&n.push(Y(`START ${e.offset}`,t+1)),n.push(Y(`) AS ${Z(e.alias||e.path)}`,t)),n.join(`
108
- `)},Xa=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=Z(r),s=Z(n||r);return Y(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)},Oi=(e,t,r)=>{let n=[];switch(e.type){case "table_scan":{n.push(Y(`FROM ${e.thing.map(Z)}`,t));break}case "record_pointer":{let i=e.thing.flatMap(o=>e.ids.map(s=>`${Z(o)}:${Z(s)}`)).map(o=>`type::record($${Te(r,o)})`).join(", ");n.push(Y(`FROM ${i}`,t));break}case "subquery":{n.push(Y(e.cardinality==="MANY"?"FROM array::distinct(array::flatten(":"FROM (",t)),e.oppositePath,n.push(Y(`SELECT VALUE ${Z(e.oppositePath)}`,t+1)),n.push(Oi(e.source,t+1,r));let i=e.filter?Ve(e.filter,r):void 0;i&&n.push(Y(`WHERE ${i}`,t+1)),n.push(Y(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}${Z(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}${Z(e.left)}`} ${e.op} [${i}]`}case "ref":case "biref":case "future_biref":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${Z(e.left)}`;if(e.thing){let o=e.thing.flatMap(s=>e.right.map(a=>{let l=`${Z(s)}:${Z(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}${Z(e.left)}) = 0`:`${n}${Z(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_ref":case "nested_future_ref":{let i=`${n}${Z(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}}},Ii=(e,t)=>{let r=e.map(n=>`${Z(n.field)} ${n.desc?"DESC":"ASC"}`).join(", ");return Y(`ORDER BY ${r}`,t)},Y=(e,t)=>`${" ".repeat(t*2)}${e}`,Te=(e,t)=>{let r=cr();for(;e[r]!==void 0;)r=cr();return e[r]=t,r},Z=e=>{let t=e.replace(/⟩/g,"\\\u27E9");return /^[^a-zA-Z]/.test(t)||/[^a-zA-Z0-9_]/.test(t)?`\u27E8${e}\u27E9`:e};var qi=(e,t)=>{let r=_i(e.source,t),n=e.filter?Et(e.filter):void 0,{source:i,filter:o}=Pi({source:e.source,filter:n,schema:t,thing:r});return {source:i,projection:ji(e.projection,t,r),filter:o,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Pi=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 l=0;l<o.length;l++){let d=o[l];if(d?.type!=="scalar"&&d?.type!=="list")continue;let c=Za(d,t);if(c)return {source:c,filter:Tr(o.filter((u,p)=>p!==l))}}let s=Ue(o,l=>l.type==="future_biref"&&l.oppositeCardinality==="ONE")??Ue(o,l=>l.type==="future_biref")??Ue(o,l=>l.type==="biref"&&l.oppositeCardinality==="ONE")??Ue(o,l=>l.type==="biref");if(s){let l=Ga(s,n,i);if(l)return {source:l,filter:Tr(o.filter(d=>d!==s))}}let a=Ue(o,l=>l.type==="nested_ref"&&l.oppositeCardinality==="ONE")??Ue(o,l=>l.type==="nested_ref"&&l.oppositeCardinality==="MANY")??Ue(o,l=>l.type==="nested_ref")??Ue(o,l=>l.type==="nested_future_ref");if(a){let l=el(a,n,i);if(l)return {source:l,filter:Tr(o.filter(d=>d!==a))}}return {source:t,filter:r?rl(r,i):void 0}},Za=(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"&&Pt.array(Pt.string()).safeParse(e.right).success)return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:e.right}}},Ga=(e,t,r)=>{let n=r.fields[e.left];if(!n)throw new Error(`Field ${e.left} not found in ${r.name}`);let i=xi(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=Sr(o,t);return {type:"subquery",source:{type:"record_pointer",thing:[o,...l.subTypes],ids:e.right},oppositePath:s,cardinality:a}},el=(e,t,r)=>{let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);let i=xi(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=Sr(o,t),d={type:"table_scan",thing:[o,...l.subTypes]},c=Pi({source:d,filter:e.filter,schema:t,thing:l});return {type:"subquery",source:c.source,oppositePath:s,cardinality:a,filter:c.filter}},xi=(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}},ji=(e,t,r)=>({fields:e.fields.map(n=>tl(n,t,r))}),tl=(e,t,r)=>{if(e.type==="metadata"||e.type==="data"||e.type==="flex"||e.type==="ref"||e.type==="future_ref")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:e.type,path:e.path,projection:ji(e.projection,t,i),ids:e.ids,filter:e.filter?Et(e.filter):void 0,alias:e.alias,resultCardinality:e.resultCardinality,fieldCardinality:e.fieldCardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Et=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=Et(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:jt[i.op]??0};if(i.type==="list"){let o=jt[i.op]??0;return {filter:i,score:o**i.right.length}}if(i.type==="biref"){let o=jt[i.op]??0,s=i.cardinality==="ONE"?1:.5;return i.thing?{filter:i,score:o**(i.right.length*i.thing.length)*s}:{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=Et(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_ref"||e.type==="nested_future_ref"){let t=Et(e.filter);return t?{type:e.type,filter:t,path:e.path,cardinality:e.cardinality,oppositeCardinality:e.oppositeCardinality}:void 0}return e},jt={"=":.9,">":.5,"<":.5,">=":.5,"<=":.5,IN:.5,"NOT IN":.5,CONTAINSALL:.3,CONTAINSANY:.4,CONTAINSNONE:.3},rl=(e,t)=>{if(e.type==="and"){let r=Object.fromEntries(e.filters.map((i,o)=>{if(i.type!=="scalar")return;let s=jt[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(Ci(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(Ci(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},Tr=e=>{if(e.length!==0)return e.length===1?e[0]:{type:"and",filters:e}},Ci=(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)),Sr=(e,t)=>{let r=t[e];if(!r)throw new Error(`Thing ${e} not found in schema`);return r},_i=(e,t)=>{if(e.type==="table_scan"||e.type==="record_pointer")return Sr(e.thing[0],t);let r=_i(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};function Ue(e,t){return e.find(t)}var nl=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vi=e=>e==null,Ui=e=>Array.isArray(e)&&e.length===0,Hi=e=>{let{batch:t,results:r,schema:n,metadata:i,returnNulls:o}=e;return t.map((s,a)=>il({query:s,result:r[a],schema:n,metadata:i,returnNulls:o}))},il=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=>_t({query:t,result:a,thing:s,schema:n,metadata:i,returnNulls:o})):_t({query:t,result:r,thing:s,schema:n,metadata:i,returnNulls:o})},ol=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=>_t({query:t,result:a,thing:n,schema:i,metadata:o,returnNulls:s})):_t({query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s})},_t=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;if(!nl(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&&Vi(f))continue;if(p.contentType==="JSON"){a[u]=St(f)??null;continue}a[u]=Wi(f)??null;continue}if(!s&&(Vi(f)||Ui(f)))continue;if(typeof d=="string"||p.type==="ref"){a[u]=Ui(f)?null:Wi(f)??null;continue}let h=i[p.opposite.thing];a[u]=ol({query:d,result:f,thing:h,schema:i,metadata:o,returnNulls:s});}return a},Wi=e=>Array.isArray(e)?e.map(t=>t instanceof DateTime?t.toDate():t):e instanceof DateTime?e.toDate():e;var vi=async e=>{let{client:t,queries:r,config:n,params:i}=e,o=`BEGIN TRANSACTION;
110
- ${r.join(`;
70
+ `)},oa=(e,t)=>{if(e.path==="$id")return Z(`record::id(id) AS ${se(e.alias??"$id")}`,t);if(e.path==="$thing")return Z(`record::tb(id) AS ${se(e.alias??"$thing")}`,t);throw new Error(`Unsupported metadata field: ${e.path}`)},sa=(e,t)=>{if(e.path==="id")return Z(`record::id(id) AS ${se(e.alias??"id")}`,t);let r=se(e.path);return e.alias?Z(`${r} AS ${se(e.alias)}`,t):Z(r,t)},aa=(e,t)=>{let{path:r,alias:n}=e,i=e.type==="computed_ref"?Be(r):se(r),o=se(n||r),s=e.fieldCardinality==="ONE"?`SELECT VALUE record::id(id) FROM $this.${i}`:`SELECT VALUE record::id(id) FROM $this.${i}[*]`;return e.resultCardinality==="ONE"?Z(`array::first(${s}) AS ${o}`,t):Z(`(${s}) AS ${o}`,t)},la=(e,t,r)=>{let n=[];e.resultCardinality==="MANY"?n.push(Z("(",t)):n.push(Z("array::first(",t)),n.push(li(e.projection,t+1,r));let i=e.filter?qe(e.filter,r):void 0,o=e.type==="nested_computed_ref"?Be(e.path):se(e.path);e.fieldCardinality==="ONE"?n.push(Z(`FROM $this.${o}`,t+1)):n.push(Z(`FROM $this.${o}[*]`,t+1));let s=[];if(e.ids&&e.ids.length>0){let a=e.ids.map(l=>`$${be(r,l)}`);a.length===1?s.push(`record::id(id) = ${a[0]}`):s.push(`record::id(id) IN [${a.join(", ")}]`);}return i&&s.push(i),s.length>0&&n.push(Z(`WHERE ${s.join(" AND ")}`,t+1)),e.sort&&e.sort.length>0&&n.push(di(e.sort,t+1)),e.limit!==void 0&&n.push(Z(`LIMIT ${e.limit}`,t+1)),e.offset!==void 0&&n.push(Z(`START ${e.offset}`,t+1)),n.push(Z(`) AS ${se(e.alias||e.path)}`,t)),n.join(`
71
+ `)},ca=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=se(r),s=se(n||r);return Z(i==="ONE"?`(IF ${o} { IF type::is_record(${o}) { record::id(${o}) } ELSE { ${o} } }) AS ${s}`:`(IF ${o} { ${o}.map(|$i| IF type::is_record($i) { record::id($i)} ELSE { $i }) }) AS ${s}`,t)},ci=(e,t,r)=>{let n=[];switch(e.type){case "table_scan":{n.push(Z(`FROM ${e.thing.map(se)}`,t));break}case "record_pointer":{let i=e.thing.flatMap(o=>e.ids.map(s=>{let a=be(r,o),l=be(r,s);return `type::record($${a}, $${l})`})).join(", ");n.push(Z(`FROM ${i}`,t));break}case "subquery":{n.push(Z(e.cardinality==="MANY"?"FROM array::distinct(array::flatten(":"FROM (",t)),n.push(Z(`SELECT VALUE ${se(e.oppositePath)}`,t+1)),n.push(ci(e.source,t+1,r));let i=e.filter?qe(e.filter,r):void 0;i&&n.push(Z(`WHERE ${i}`,t+1)),n.push(Z(e.cardinality==="MANY"?"))":")",t));break}}return n.join(`
72
+ `)},qe=(e,t,r)=>{let n=r??"";switch(e.type){case "scalar":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${se(e.left)}`,o=be(t,e.right);return `${i} ${e.op} $${o}`}case "list":{let i=e.right.map(s=>`$${be(t,s)}`).join(", ");return `${`${n}${se(e.left)}`} ${e.op} [${i}]`}case "ref":case "biref":case "computed_biref":{let i=e.type==="computed_biref"?Be(e.left):se(e.left),o=e.left==="id"?`record::id(${n}id)`:`${n}${i}`;if(e.thing){let s=e.thing.flatMap(a=>e.right.map(l=>{let p=be(t,a),c=be(t,l);return `type::record($${p}, $${c})`}));if(s.length===1){let a=s[0];if(e.op==="IN")return `${o} = ${a}`;if(e.op==="NOT IN")return `${o} != ${a}`;if(e.op==="CONTAINSANY")return `${a} IN ${o}`;if(e.op==="CONTAINSNONE")return `${a} NOT IN ${o}`}return `${o} ${e.op} [${s.join(", ")}]`}if(e.right.length===1){if(e.op==="IN")return `${o} && record::id(${o}) = $${be(t,e.right[0])}`;if(e.op==="NOT IN")return `${o} && record::id(${o}) != $${be(t,e.right[0])}`;if(e.op==="CONTAINSANY")return `$${be(t,e.right[0])} IN (${o} ?: []).map(|$i| record::id($i))`;if(e.op==="CONTAINSNONE")return `$${be(t,e.right[0])} NOT IN (${o} ?: []).map(|$i| record::id($i))`}return `(${o} ?: []).map(|$i| record::id($i)) ${e.op} [${e.right.map(s=>`$${be(t,s)}`).join(", ")}]`}case "null":return e.emptyIsArray?e.op==="IS"?`array::len(${n}${se(e.left)}) = 0`:`array::len(${n}${se(e.left)}) > 0`:`${n}${se(e.left)} ${e.op} NONE`;case "and":{let i=e.filters.map(o=>{let s=qe(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=qe(o,t,r);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" OR "):void 0}case "not":{let i=qe(e.filter,t,r);return i?`NOT(${i})`:void 0}case "nested_ref":case "nested_computed_ref":{let i=e.type==="nested_computed_ref"?Be(e.path):se(e.path),o=`${n}${i}`;if(e.cardinality==="ONE")return qe(e.filter,t,`${o}.`);let s=qe(e.filter,t);return s?`${o}[WHERE ${s}]`:void 0}}},di=(e,t)=>{let r=e.map(n=>`${se(n.field)} ${n.desc?"DESC":"ASC"}`).join(", ");return Z(`ORDER BY ${r}`,t)},Z=(e,t)=>`${" ".repeat(t*2)}${e}`,be=(e,t)=>{let r=ir();for(;e[r]!==void 0;)r=ir();return e[r]=t,r},se=e=>{let t=e.replace(/⟩/g,"\\\u27E9");return /^[^a-zA-Z]/.test(t)||/[^a-zA-Z0-9_]/.test(t)?`\u27E8${e}\u27E9`:e};var hi=(e,t)=>{let r=yi(e.source,t),n=e.filter?$t(e.filter):void 0,{source:i,filter:o}=fi({source:e.source,filter:n,schema:t,thing:r});return {source:i,projection:mi(e.projection,t,r),filter:o,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},fi=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 l=0;l<o.length;l++){let p=o[l];if(p?.type!=="scalar"&&p?.type!=="list")continue;let c=da(p,t);if(c)return {source:c,filter:fr(o.filter((u,d)=>d!==l))}}let s=Ve(o,l=>l.type==="computed_biref"&&l.oppositeCardinality==="ONE")??Ve(o,l=>l.type==="computed_biref")??Ve(o,l=>l.type==="biref"&&l.oppositeCardinality==="ONE")??Ve(o,l=>l.type==="biref");if(s){let l=ua(s,n,i);if(l)return {source:l,filter:fr(o.filter(p=>p!==s))}}let a=Ve(o,l=>l.type==="nested_ref"&&l.oppositeCardinality==="ONE")??Ve(o,l=>l.type==="nested_ref"&&l.oppositeCardinality==="MANY")??Ve(o,l=>l.type==="nested_computed_ref"&&l.oppositeCardinality==="ONE")??Ve(o,l=>l.type==="nested_computed_ref"&&l.oppositeCardinality==="MANY");if(a){let l=pa(a,n,i);if(l)return {source:l,filter:fr(o.filter(p=>p!==a))}}return {source:t,filter:r?fa(r,i):void 0}},da=(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"&&Nt.array(Nt.string()).safeParse(e.right).success)return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:e.right}}},ua=(e,t,r)=>{let n=r.fields[e.left];if(!n)throw new Error(`Field ${e.left} not found in ${r.name}`);let i=$i(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=$r(o,t);return {type:"subquery",source:{type:"record_pointer",thing:[o,...l.subTypes],ids:e.right},oppositePath:s,cardinality:a}},pa=(e,t,r)=>{let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);let i=$i(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=$r(o,t),p={type:"table_scan",thing:[o,...l.subTypes]},c=fi({source:p,filter:e.filter,schema:t,thing:l});return {type:"subquery",source:c.source,oppositePath:s,cardinality:a,filter:c.filter}},$i=(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}},mi=(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==="ref"||e.type==="computed_ref")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:e.type,path:e.path,projection:mi(e.projection,t,i),ids:e.ids,filter:e.filter?$t(e.filter):void 0,alias:e.alias,resultCardinality:e.resultCardinality,fieldCardinality:e.fieldCardinality,limit:e.limit,offset:e.offset,sort:e.sort}},$t=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=$t(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:kt[i.op]??0};if(i.type==="list"){let o=kt[i.op]??0;return {filter:i,score:o**i.right.length}}if(i.type==="biref"){let o=kt[i.op]??0,s=i.cardinality==="ONE"?1:.5;return i.thing?{filter:i,score:o**(i.right.length*i.thing.length)*s}:{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=$t(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_ref"||e.type==="nested_computed_ref"){let t=$t(e.filter);return t?{type:e.type,filter:t,path:e.path,cardinality:e.cardinality,oppositeCardinality:e.oppositeCardinality}:void 0}return e},kt={"=":.9,">":.5,"<":.5,">=":.5,"<=":.5,IN:.5,"NOT IN":.5,CONTAINSALL:.3,CONTAINSANY:.4,CONTAINSNONE:.3},fa=(e,t)=>{if(e.type==="and"){let r=Object.fromEntries(e.filters.map((i,o)=>{if(i.type!=="scalar")return;let s=kt[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 p=r[l];if(!p||a.some(c=>c.index===p.index))break;a.push(p);}a.length>0&&i.push({filters:a,score:a.reduce((l,p)=>l+l*p.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 p=t.fields[a.left];if(pi(p,t.indexes))return {filter:a,score:1,index:l}}else if(a.type==="list"&&a.op==="IN"){let p=t.fields[a.left];if(pi(p,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}},pi=(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)),$r=(e,t)=>{let r=t[e];if(!r)throw new Error(`Thing ${e} not found in schema`);return r},yi=(e,t)=>{if(e.type==="table_scan"||e.type==="record_pointer")return $r(e.thing[0],t);let r=yi(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};function Ve(e,t){return e.find(t)}var $a=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ei=e=>e==null,Bi=e=>Array.isArray(e)&&e.length===0,bi=e=>{let{batch:t,results:r,schema:n,metadata:i,returnNulls:o}=e;return t.map((s,a)=>ma({query:s,result:r[a],schema:n,metadata:i,returnNulls:o}))},ma=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=>Ct({query:t,result:a,thing:s,schema:n,metadata:i,returnNulls:o})):Ct({query:t,result:r,thing:s,schema:n,metadata:i,returnNulls:o})},ya=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=>Ct({query:t,result:a,thing:n,schema:i,metadata:o,returnNulls:s})):Ct({query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s})},Ct=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;if(!$a(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 p of l){let c=typeof p=="string"?p:p.$path,u=typeof p=="string"?p:p.$as??c;if(t.$excludedFields?.includes(c))continue;if(c==="$id"||c==="$thing"){a[u]=r[u]??null;continue}let d=n.fields[c];if(!d)throw new Error(`Field ${c} not found in ${n.name}`);if(d.type==="constant"){a[u]=d.value;continue}if(d.type==="computed"){a[u]=d.fn(r);continue}let f=r[u];if(d.type==="data"){if(!s&&Ei(f))continue;if(d.contentType==="JSON"){a[u]=bt(f)??null;continue}a[u]=Fi(f)??null;continue}if(!s&&(Ei(f)||Bi(f)))continue;if(typeof p=="string"||d.type==="ref"){a[u]=Bi(f)?null:Fi(f)??null;continue}let h=i[d.opposite.thing];a[u]=ya({query:p,result:f,thing:h,schema:i,metadata:o,returnNulls:s});}return a},Fi=e=>Array.isArray(e)?e.map(t=>t instanceof DateTime?t.toDate():t):e instanceof DateTime?e.toDate():e;var Ti=async e=>{let{client:t,queries:r,config:n,params:i}=e,o=r.join(`;
73
+ `);return ee("query",`query/batchedQuery
74
+ `,o),n.query?.debugger&&le(`batchedQuery[${ce}]`,JSON.stringify({batchedQuery:o})),await t.query(o,i)};var wi=async(e,t,r,n)=>{let i=nanoid(3);if(e.length===0)return [];let o=performance.now(),s=e.map(g=>Xn.parse(g));ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/bqlQueries"],`> runSurrealDbQueryMachine2/bqlQueries ${i}
75
+ `,JSON.stringify(s));let a=s.map(g=>Gn(g,t,!r.query?.noMetadata));ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/logicalQueries"],`> runSurrealDbQueryMachine2/logicalQueries ${i}
76
+ `,JSON.stringify(a));let l=a.map(g=>hi(g,t));ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/optimizedQueries"],`> runSurrealDbQueryMachine2/optimizedQueries ${i}
77
+ `,JSON.stringify(l));let p={},c=l.map(g=>ai(g,p));ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/params"],`> runSurrealDbQueryMachine2/params ${i}
78
+ `,JSON.stringify(p)),ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/surqlQueries"],`> runSurrealDbQueryMachine2/surqlQueries ${i}
79
+ `,JSON.stringify(c));let u=performance.now(),d=await Ti({client:n,queries:c,config:r,params:p}),f=performance.now();ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/queryDuration"],`> runSurrealDbQueryMachine2/queryDuration ${i}
80
+ `,`${(f-u).toFixed(2)}ms`),ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/result"],`> runSurrealDbQueryMachine2/result ${i}
81
+ `,JSON.stringify(d));let h=bi({batch:s,results:d,schema:t,metadata:!r.query?.noMetadata,returnNulls:!!r.query?.returnNulls});ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/finalResult"],`> runSurrealDbQueryMachine2/finalResult ${i}
82
+ `,h);let $=performance.now();return ee(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/duration"],`> runSurrealDbQueryMachine2/duration ${i}
83
+ `,`${($-o).toFixed(2)}ms`),h};var Mi=(e,t)=>{if(!t)return;let r=Ba(t);return Fa(r,e.query)},Ba=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Fa=(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 Di=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 p=V(e,l),{virtualFields:c}=p,u=l[Le];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let d=getNodeByPath(t,u);if(d.$fieldType==="ref")return;let f=d.$fields.map($=>$.$path),h=d.$excludedFields;c.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let g=p.dataFields?.find(m=>m.path===$);if(g?.default){let m=nt({currentThing:l,fieldSchema:g,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 xt=e=>{let{$filter:t,$var:r,$thing:n,schema:i,depth:o}=e,s=Da(t,ne(i,n)),{$not:a,...l}=s,p=[];if(yr(a)){let u=mr(a,r,n,i,o,true);p.push(...u);}else if(a!==void 0)throw new Error("$not must be a PositiveFilter object");let c=mr(l,r,n,i,o,false);return p.push(...c),p.join(`
84
+ `)},mr=(e,t,r,n,i,o)=>{let s=ne(n,r),a=[];for(let[l,p]of Object.entries(e)){if(l.startsWith("$")){let d=l.toLowerCase();if(d==="$and"||d==="$or"){let h=(isArray(p)?p:[p]).map(g=>{if(yr(g))return mr(g,t,r,n,i+1,o).join(`
85
+ `);throw new Error(`Invalid subfilter in ${d}: ${JSON.stringify(g)}`)}),$=h.join(d==="$and"?`
86
+ `:" } or { ");d==="$or"&&h.length>1?a.push(I(`{ ${$} };`,i)):a.push(I($,i));continue}continue}if(s.dataFields?.find(d=>d.dbPath===l||d.path===l)){let d=Sa(l,p,t,i,o);a.push(...d);continue}let u=s.linkFields?.find(d=>d.path===l);if(u){let d=La(u,p,t,n,i,o);a.push(...d);continue}if(s.thingType==="relation"){let d=s.roles[l];if(d){let f=Ma(d,p,t,r,n,i,o);a.push(...f);continue}}throw new Error(`"${r}" does not have property "${l}"`)}return a},Sa=(e,t,r,n,i)=>{let o=[];if(isObject(t)&&!isArray(t))for(let[s,a]of Object.entries(t)){let l=s.toLowerCase(),p="";switch(l){case "$eq":p=`$${r} has ${e} ${Ee(a)};`;break;case "$ne":p=`not { $${r} has ${e} ${Ee(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} ${Ee(u)};`);p=yt(c),i&&(p=`not { ${p} };`);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} ${Ee(c)}; };`;o.push(I(u,n));}continue;case "$exists":if(a===true)p=`$${r} has ${e} $${e}_${v4()};`;else if(a===false)p=`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&&(p=`not { ${p} };`),o.push(I(p,n));}else if(isArray(t)){let s=t.map(l=>`$${r} has ${e} ${Ee(l)};`),a=yt(s);a&&(i&&(a=`not { ${a} };`),o.push(I(a,n)));}else {let s=`$${r} has ${e} ${Ee(t)};`;i&&(s=`not { ${s} };`),o.push(I(s,n));}return o},La=(e,t,r,n,i,o)=>{let s=[],[a]=e.oppositeLinkFieldsPlayedBy,p=ne(n,a.thing).idFields?.[0];if(!p)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 d=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${Ee(f)};`);u=yt(d),o&&(u=`not { ${u} };`);}else u=`(${e.plays}: $${r}) isa ${e.relation}, has ${p} ${Ee(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 d=t.map(f=>`$${c} isa ${a.thing}, has ${p} ${Ee(f)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`);u=yt(d),o&&(u=`not { ${u} };`);}else u=`$${c} isa ${a.thing}, has ${p} ${Ee(t)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`,o&&(u=`not { ${u} };`);return s.push(I(u,i)),s},Ma=(e,t,r,n,i,o,s)=>{let a=[],[l]=e.playedBy||[],c=ne(i,l.thing).idFields?.[0];if(!c)throw new Error(`"${l.thing}" does not have an id field`);let u=`${l.thing}_${v4()}`,d=v4(),f=`${r}_${d}`;a.push(I(`$${f} isa ${n};`,o));let h="";if(t===null)h=`$${f} (${l.plays}: ${u});`,s?a.push(I(h,o)):a.push(I(`not { ${h} };`,o));else if(isArray(t)){let $=t.map(g=>`$${u} isa ${l.thing}, has ${c} ${Ee(g)}; $${f} (${l.plays}: $${u});`);h=yt($),s?a.push(I(`not { ${h} };`,o)):a.push(I(h,o));}else h=`$${u} isa ${l.thing}, has ${c} ${Ee(t)}; $${f} (${l.plays}: $${u});`,s?a.push(I(`not { ${h} };`,o)):a.push(I(h,o));return a.push(I(`$${r} is $${f};`,o)),a},yt=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},Ee=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("|")})$"`:Ee(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},Da=(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=Ai(i,r);return n&&yr(n)&&(o.$not=Ai(n,r)),o},Ai=(e,t)=>{let r={};return Object.entries(e).forEach(([n,i])=>{let o=t[n]||n;r[o]=i;}),r},yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var gr="___",Oi=async e=>{let{queries:t,schema:r}=e;return t.map(n=>Aa({query:n,schema:r}))},Aa=e=>{let{query:t,schema:r}=e,{$path:n,$thing:i,$filter:o,$fields:s,$sort:a,$offset:l,$limit:p,$id:c}=t;if(!n)throw new Error("Path is not defined");let u=[],d=t[Le];if(u.push("match"),u.push(`$${n} isa ${i};`),o||c){let $=St(r,t),g={...o,...c?{[$]:c}:{}},m=xt({$filter:g,$var:n,$thing:i,schema:r,depth:0});u.push(`
87
+ ${m}`);}let f=br({schema:r,$thing:i,$var:n,$sort:a,depth:0});f&&u.push(f.match);let h=`M_${v4()}`;if(u.push(`?queryPath${h} = "${d}";`),u.push("fetch"),u.push(`?queryPath${h} as "queryPath";`),s){let $=s.filter(E=>E.$fieldType==="data");$&&$.length>0&&u.push(...Er($,n,0));let g=s.filter(E=>E.$fieldType==="link");g&&g.length>0&&u.push(...Fr(g,n,n,0,r));let m=s.filter(E=>E.$fieldType==="role");m&&m.length>0&&u.push(...Br(m,n,n,0,r));}return f&&u.push(f.sort),typeof l=="number"&&u.push(`
88
+ offset ${l};`),typeof p=="number"&&u.push(`
89
+ limit ${p};`),u.join(`
90
+ `)},Er=(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][ke].contentType==="FLEX"&&o.push({path:e[c][ke].dbPath}),i.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=n.join(", "),l=`$metadata:{as:[${i.join(",")}]}`,p=[I(`$${t} as "${t}.${l}.$dataFields": ${s};`,r)];return o.length>0&&o.forEach(c=>{p.push(I(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),p},Br=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:p,$justId:c,$idNotIncluded:u,$filterByUnique:d,$thing:f,$sort:h,$offset:$,$limit:g}=a,m=a[Le],E=`$metadata:{as:${p},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${d}}`;s.push(I(`"${r}.${E}.${a.$var}": {`,n)),s.push(I("match",o));let T=`${t}${gr}${a.$var}`;if(s.push(I(`$${T} isa ${a.$thing};`,o)),s.push(I(`$${t} (${a.$var}: $${t}${gr}${a.$var}) isa ${a.$intermediary};`,o)),a.$filter||a.$id){let w=St(i,a),M=a.$id?{[w]:a.$id}:{},Q={...a.$filter,...M};s.push(xt({$filter:Q,$var:T,$thing:a.$thing,schema:i,depth:o}));}let y=br({schema:i,$thing:f,$var:T,$sort:h,depth:o});if(y&&s.push(y.match),l){let w=`M_${v4()}`;s.push(I(`
91
+ ?queryPath${w} = "${m}";`,o)),s.push(I("fetch",o)),s.push(I(`?queryPath${w} as "queryPath";`,o));let M=l?.filter(A=>A.$fieldType==="data");M&&M.length>0&&s.push(...Er(M,T,o));let Q=l?.filter(A=>A.$fieldType==="link");Q&&Q.length>0&&s.push(...Fr(Q,T,`${t}.${a.$var}`,o,i));let b=l?.filter(A=>A.$fieldType==="role");b&&b.length>0&&s.push(...Br(b,T,`${t}.${a.$var}`,o,i));}y&&s.push(y.sort),typeof $=="number"&&s.push(I(`offset ${$};`,o)),typeof g=="number"&&s.push(I(`limit ${g};`,o)),s.push(I("};",n));}return s},Fr=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:p,$justId:c,$idNotIncluded:u,$filterByUnique:d,$playedBy:f,$thing:h,$sort:$,$offset:g,$limit:m}=a,E=a[Le],T=`$metadata:{as:${p},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${d}}`;s.push(I(`"${r}.${T}.${a.$var}": {`,n)),s.push(I("match",o));let y=`${t}${gr}${a.$var}`;if(s.push(I(`$${y} isa ${a.$thing};`,o)),a.$filter||a.$id){let M=St(i,a),Q=a.$id?{[M]:a.$id}:{},b={...a.$filter,...Q};s.push(xt({$filter:b,$var:y,$thing:a.$thing,schema:i,depth:o}));}let w=br({schema:i,$thing:h,$var:y,$sort:$,depth:o});if(w&&s.push(w.match),a.$target==="role"?s.push(I(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${y}) isa ${a.$intermediary};`,o)):s.push(I(`$${y} (${a.$plays}: $${t});`,o)),l){let M=`M_${v4()}`;s.push(I(`?queryPath${M} = "${E}";`,o)),s.push(I("fetch",o)),s.push(I(`?queryPath${M} as "queryPath";`,o));let Q=l?.filter(k=>k.$fieldType==="data");Q&&Q.length>0&&s.push(...Er(Q,y,o));let b=l?.filter(k=>k.$fieldType==="link");b&&b.length>0&&s.push(...Fr(b,y,`${t}.${a.$var}`,o,i));let A=l?.filter(k=>k.$fieldType==="role");A&&A.length>0&&s.push(...Br(A,y,`${t}.${a.$var}`,o,i));}w&&s.push(w.sort),typeof g=="number"&&s.push(I(`offset ${g};`,o)),typeof m=="number"&&s.push(I(`limit ${m};`,o)),s.push(I("};",n));}return s},Qa=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},br=e=>{let{$var:t,$thing:r,schema:n,$sort:i,depth:o}=e,s=ne(n,r),a=[],l=[];if(i?.forEach(p=>{let c=Qa(p),u=s.dataFields?.find(h=>h.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let d=`${c.field}_${v4()}`;a.push(I("{",o)),a.push(I(`$${t} has ${u.dbPath} $${d}_1;`,o+1)),a.push(I("not {",o+1)),a.push(I(`$${t} has ${u.dbPath} $${d}_2;`,o+2)),a.push(I(`$${d}_2 < $${d}_1;`,o+2)),a.push(I("};",o+1)),a.push(I(`?${d}_ = $${d}_1;`,o+1)),a.push(I("} or {",o)),a.push(I(`not { $${t} has ${u.dbPath} $${d}_1; };`,o+1)),a.push(I(`?${d}_ = "~";`,o+1)),a.push(I("};",o)),a.push(I(`?${d} = ?${d}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${d} ${f}`);}),a.length!==0)return {match:a.join(""),sort:I(`sort ${l.join(", ")};`,o)}};var Ii=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],p=t[a];return Na(s,l,p,n,i)})},Na=(e,t,r,n,i)=>e.length===0?null:r.$filterByUnique?Ni(e[0],t,n,i):e.map(o=>Ni(o,t,n,i)),Ni=(e,t,r,n)=>{let{dataFields:i,currentSchema:o,linkFields:s,roleFields:a,schemaValue:l}=Tr(e,r),p=wr(i,o,n),c=Sr(s,r,n),u=Rr(a,r,n),d=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)?p.id:t.$id}:{},...d?Object.fromEntries(Object.entries(p).filter(([h])=>!o?.idFields?.includes(h))):p}},Tr=(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,[Le]:e.queryPath.value},p={[`$${l.$thingType}`]:l.$thing},c=V(t,p),u=r.filter(f=>{let h=Te(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(f=>{let h=Te(f.split(".").pop()),$=Te(c.linkFields?.find(g=>g.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),d=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(f=>{let h=Te(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:d}},wr=(e,t,r)=>{let{$metaData:n}=e,{as:i}=Ia(n),o=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).flatMap(([s,a])=>{let l=t.dataFields?.find(d=>d.path===s||d.dbPath===s),p=s==="id",c=Array.isArray(i)?i.find(d=>d[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)),p)return [[c,u],["$id",u]].filter(([d,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(d=>`${d.value}Z`):l.contentType==="FLEX"?u=a.map(d=>d.type.value_type==="datetime"?`${d.value}Z`:d.value):l.contentType==="JSON"?u=a.map(d=>d.value&&JSON.parse(d.value)):u=a.map(d=>d.value);}return [[c,u]].filter(([d,f])=>f!==void 0)});return Object.fromEntries([...o])},Rr=(e,t,r)=>{let n={};for(let i of e){let{$roleFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:p,idNotIncluded:c,filterByUnique:u}=ki(s);if(l===null)continue;let d=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:E}=Tr(f,t),T=wr(h,$,r);if(p==="T")return T.id;let y=Sr(g,t,r),w=Rr(m,t,r),M={...T};if(c==="true"&&$?.idFields)for(let Q of $.idFields)delete M[Q];return {...M,...y,...w,...E}});d.length>0?n[l]=a==="MANY"&&u==="false"?d:d[0]:r.query?.returnNulls&&(n[l]=null);}return n},Sr=(e,t,r)=>{let n={};for(let i of e){let{$linkFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:p,idNotIncluded:c,filterByUnique:u}=ki(s);if(l===null)continue;let d=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:m,schemaValue:E}=Tr(f,t),T=wr(h,$,r);if(p==="T")return T.id;let y=Sr(g,t,r),w=Rr(m,t,r),M={...T};if(c==="true")for(let Q of $.idFields??[])delete M[Q];return {...M,...y,...w,...E}});n[l]=d.length>0?a==="MANY"&&u==="false"?d:d[0]:r.query?.returnNulls?null:void 0;}return n},ki=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}},Ia=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 _t=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 Ci=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,i=new TypeDBOptions;i.infer=true;let{session:o}=await _t(r,n),s=await o.transaction(TransactionType.READ,i),[a,l]=await tryit(parallel)(t.length,t,async p=>await s.query.fetch(p).collect());if(a){await s.rollback();let p=a;throw new Error(`Error running TQL query: ${p.errors}`)}return await s.close(),l};var ja=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Lr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,qa=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Va=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,at=v("error","error",U((e,t)=>({...e,error:t.error}))),za=De("enrich",{enrich:X(async e=>(le(`originalBQLQuery[${ce}]`,JSON.stringify(e.bql.raw)),Dt(e.bql.raw,e.schema)),v("done","build",U(ja)),at),build:X(async e=>Oi({queries:e.bql.queries??[],schema:e.schema}),v("done","run",U(qa)),at),run:X(async e=>Ci({dbHandles:e.handles,tqlRequest:Te(e.tql.queries),config:e.config}),v("done","parse",U(Va)),at),parse:X(async e=>Ii({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries??[],schema:e.schema,config:e.config,rawTqlRes:Te(e.tql.res)}),v("done","postHooks",U(Lr)),at),postHooks:X(async e=>Di(e.schema,Te(e.bql.queries),Te(e.bql.res)),v("done","clean",U(Lr)),at),clean:X(async e=>Mi(e.config,Te(e.bql.res)),v("done","success",U(Lr)),at),success:ge(),error:ge()},e=>e),Wa=async e=>new Promise((t,r)=>{Ae(za,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),xi=async(e,t,r,n)=>Wa({bql:{raw:e},tql:{},schema:t,config:r,handles:n,error:null});var Ua=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,va=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Pi=v("error","error",U((e,t)=>({...e,error:t.error}))),Ha=De("enrich",{enrich:X(async e=>(le(`originalBQLQuery[${ce}]`,JSON.stringify(e.bql.raw)),Dt(e.bql.raw,e.schema)),v("done","adapter",U(Ua)),Pi),adapter:X(async e=>{let t={};e.bql.raw?.forEach((a,l)=>{let p=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=ne(e.schema,c),{id:d}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[d]){let h=e.handles.typeDB?.get(d)?.client;if(!h)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:h,rawBql:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[d]){let h=e.handles.surrealDB?.get(d)?.client;if(!h)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:h,rawBql:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let f=t[d];f.rawBql.push(p),f.indices.push(l);});let r=Object.values(t),n=r.map(a=>{if(a.db==="typeDB")return xi(a.rawBql,e.schema,e.config,e.handles);if(a.db==="surrealDB")return wi(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 p=i[l];return a.indices.map((c,u)=>({index:c,result:p[u]}))});return o.sort((a,l)=>a.index<l.index?-1:a.index>l.index?1:0),o.map(({result:a})=>a)},v("done","success",U(va)),Pi),success:ge(),error:ge()},e=>e),Ja=async e=>new Promise((t,r)=>{Ae(Ha,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),lt=async(e,t,r,n,i)=>Ja({bql:{raw:e},schema:t,draftSchema:r,config:n,handles:i,error:null});var Vi=async(e,t,r,n,i)=>{let o=Array.isArray(e)?e:[e],s=o.map(p=>Mr(p,true)),l=(await lt(s,t,r,n,i)).bql.res;return o.map((p,c)=>{let u=ne(t,p.$thing);return Wi({mut:p,node:l[c],schema:t,thing:u})})},zi=new Set(["$op","$bzId","$parentKey"]),Ya=new Set(["$relation","$entity","$id",...zi]),Mr=(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(zi.has(i)||Ya.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,...Mr(o[0],false)}):isObject(o)&&(r[i]={$path:i,...Mr(o,false)});}return n.$fields=Object.values(r),n},Wi=e=>{let{mut:t,node:r,schema:n,thing:i}=e,o=vi(i),s=Xa(r);if(Array.isArray(t))return t.map(l=>{let p=s[l.$id];return p?_i({mut:l,node:p,schema:n,thing:i,...o}):l});let a=s[t.$id];return _i({mut:t,node:a,schema:n,thing:i,...o})},_i=e=>{let{mut:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,{$fields:l,...p}=t;if(!r)return p;let c=Ui({$fields:t.$fields,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}),u={...p,[et]:c};for(let d in t){if(d.startsWith("$"))continue;let f=t[d];if(o[d]||!f||typeof f!="object"){u[d]=f;continue}let $=s[d]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[d]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${d}"`);let g=ne(n,$);u[d]=Wi({mut:f,schema:n,node:r[d],thing:g});}return u},Ui=e=>{let{$fields:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,l=t||Za(i),p={$id:r.$id};return l.forEach(c=>{let u=typeof c!="string",d=u?c.$path:c,f=r[d];if(o[d]){p[d]=f;return}let $=s[d]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[d]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${d}"`);if(!u){f&&(p[d]=Array.isArray(f)?f.map(ji):ji(f));return}let g=ne(n,$),m=vi(g);p[d]=Array.isArray(f)?f.map(E=>qi({...m,$fields:c.$fields,value:E,schema:n,thing:g})):qi({...m,$fields:c.$fields,value:f,schema:n,thing:g});}),p},Za=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},ji=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},qi=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 Ui({...e,node:t})},vi=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}},Xa=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 Hi=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(s,a)=>{if(!s?.$thing)return;let{$op:l,$bzId:p,$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 d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:h,usedRoleFields:$,usedRefFields:g}=$e(u,s);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let E={...fe(s,T=>![...$,...h,...g].includes(T)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[tt]:d}};r.things.push(E);}let m={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let E=fe(s,T=>isSymbol(T)||T.startsWith("$"));for(let T of $){if(isArray(s[T]))for(let w of s[T])n(w,{bzId:p,edgeField:T,tempId:c});else n(s[T],{bzId:p,edgeField:T,tempId:c});let y=(isArray(s[T])?s[T]:[s[T]]).filter(Boolean);for(let[w,M]of Object.entries(m)){let Q=y.filter(b=>M.includes(b.$op)).map(b=>b.$bzId);Q.length>0&&r.edges.push({...E,[T]:Q,$op:w});}}}if(h)for(let E of h){if(isArray(s[E]))for(let w of s[E])n(w,{bzId:p,edgeField:E,tempId:c});else n(s[E],{bzId:p,edgeField:E,tempId:c});let T=u.linkFields?.find(w=>w.path===E),y=isArray(s[E])?s[E]:[s[E]];if(T.target==="relation")for(let[w,M]of Object.entries(m)){let Q=y.filter(b=>M.includes(b.$op));for(let b of Q){let A=fe(b,k=>isSymbol(k)||k.startsWith("$"));r.edges.push({...A,[T.plays]:p,$op:w});}}if(T.target==="role"){let w={create:["link","create"],delete:["unlink","delete"],replace:["replace"]};for(let[M,Q]of Object.entries(w)){let b=y.filter(A=>Q.includes(A.$op));if(b.length!==0)for(let A of b){let k={$thing:T.relation,$thingType:"relation",$bzId:`arc_${A.$bzId}`,[T.plays]:p,[T.oppositeLinkFieldsPlayedBy[0].plays]:A.$bzId,$op:M};r.arcs.push(k);}}}}if(g)for(let E of g){if(isArray(s[E]))for(let M of s[E])n(M,{bzId:p,edgeField:E,tempId:c});else n(s[E],{bzId:p,edgeField:E,tempId:c});let T=(isArray(s[E])?s[E]:[s[E]]).filter(M=>M!=null),y=fe(s,M=>isSymbol(M)||M.startsWith("$")),w=T.map(M=>M.$op?`$\u27E8${M.$bzId}\u27E9`:Ge(M,"FLEX"));w.length>0&&r.references.push({...y,[E]:w,$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 Zi=async(e,t)=>{let r=c=>{let u=[],d=[],f=m=>{if(m.$id)return m.$id;let E=V(t,m),{idFields:T}=E;if(!T)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[y]=T;if(!y)throw new Error(`no idField: ${JSON.stringify(m)}`);let w=E.dataFields?.find(b=>b.path===y),M=nt({currentThing:m,fieldSchema:w,mandatoryDependencies:true}),Q=m[y]||m.$id||M;if(!Q)throw new Error(`no idValue: ${JSON.stringify(m)}`);return Q},h=m=>{if(m.$op==="create"){let E=f(m);if(u.find(T=>T.$id===E&&T.$op==="create"))throw new Error(`Duplicate id ${E} for node ${JSON.stringify(m)}`);u.push({...m,$id:E});return}m.$tempId&&m.$op==="match"||u.push(m);},$=m=>{if(m.$op==="create"){let E=f(m);if(u.find(T=>T.$id===E&&T.$op==="create"))throw new Error(`Duplicate id ${E} for edge ${JSON.stringify(m)}`);d.push({...m,$id:E});return}d.push(m);};return traverse(c,({value:m,parent:E,meta:T})=>{if(!isObject(m))return;let y=m;if(!T.nodePath?.includes(".$filter")&&y.$thing){if(!y.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(y)}`);if(!y.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(y)}`);let w=V(t,y),{dataFields:M,roleFields:Q,linkFields:b,refFields:A,usedFields:k}=$e(w,y),j=()=>{if(y.$op==="create"||y.$op==="delete")return y.$op;if(y.$op==="update"){let N=k.filter(S=>M?.includes(S)),z=k.filter(S=>Q?.includes(S)),L=k.filter(S=>b?.includes(S)),R=k.filter(S=>A?.includes(S));if(N.length>0)return "update";if(z.length>0||L.length>0||R.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(y)}`)}return "match"},G={...y.$id&&{$id:y.$id},...y.$tempId&&{$tempId:y.$tempId},...y.$filter&&{$filter:y.$filter},$thing:y.$thing,...y.$thingType&&{$thingType:y.$thingType},...shake(pick(y,M||[""])),$op:j(),$bzId:y.$bzId};h(G);let D=y[Me];if(D?.[J].fieldType==="linkField"){if((y.$op==="link"||y.$op==="unlink")&&(y.$id||y.$filter)){if(y.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...y,$op:"match"});}let N=D.$things.includes(y.$thing),z=N?y.$bzId:`LT_${v4()}`,R=Sn(c,E,T).$bzId;if(!R)throw new Error("No parent id found");let S=()=>y.$op==="delete"?N?"match":"delete":y.$op==="unlink"?N?"unlink":"delete":y.$op==="link"||y.$op==="create"?N?"link":"create":y.$op==="replace"?"replace":"match",B=V(t,{$thing:D.relation,$thingType:"relation"});if(!Object.keys(B.roles).includes(D.plays))throw new Error(`[Wrong format] Field ${D.plays} is not a role of relation ${D.relation}`);let O={$bzId:z,$thing:N?y.$thing:D.relation,$thingType:"relation",...y.$tempId?{$tempId:y.$tempId}:{},$op:S(),...N?{}:{[D.path]:y.$bzId},[D.plays]:R,[Me]:D,[ve]:"linkField"};$(O),(y.$op==="unlink"||S()==="unlink")&&N&&$({$thing:D.relation,$thingType:"relation",$bzId:z,$op:"match",[D.plays]:R,[Me]:D,[ve]:"linkField"});}if(y.$thingType==="relation"){let N=fe(y,(R,S)=>Q.includes(R)),z=mapEntries(N,(R,S)=>isArray(S)?[R,S]:isObject(S)?[R,S.$bzId]:[R,S]),L=fe(m,(R,S)=>R.startsWith("$")||R.startsWith("Symbol"));if(Object.keys(N).filter(R=>!R.startsWith("$")).length>0){if(y.$op==="create"||y.$op==="delete"){let R=()=>{if(y.$op==="create")return "link";if(y.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=V(t,y).roles,B=mapEntries(z,(O,C)=>{let W=S[O]?.cardinality;if(!W)throw new Error(`Role ${O} not found in schema`);return Array.isArray(C)?W==="ONE"?C.length>1?[O,C.map(P=>P.$bzId||P)]:[O,C[0].$bzId||C[0]]:[O,C.map(P=>P.$bzId||P)]:[O,C.$bzId||C]}),F={...L,$thing:y.$thing,$thingType:"relation",$op:R(),...B,$bzId:y.$bzId,[ve]:"roleField"};$(F);return}if(y.$op==="match"||y.$op==="update"&&Object.keys(N).length>0){Object.entries(N).forEach(([S,B])=>{let F=isArray(B)?B:[B],O=C=>C==="create"||C==="replace"?"link":C;F.forEach(C=>{if(!C)return;let W=O(C.$op);if(W==="replace")throw new Error("Not supported yet: replace on roleFields");let P={...L,$thing:y.$thing,$thingType:"relation",$op:W==="delete"?"unlink":W,[S]:C.$bzId,$bzId:y.$bzId,[ve]:"roleField"};$(P);});});}}}}}),[u,d]},[n,i]=r(e),o=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let d=c.findIndex(f=>f.$bzId===u.$bzId);if(d===-1)return [...c,u];if(c[d].$op==="create"&&u.$op==="match")return c;if(c[d].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,d),u,...c.slice(d+1)];if(c[d].$op==="update"&&u.$op==="update")return [...c.slice(0,d),{...c[d],...u},...c.slice(d+1)];if(c[d].$op==="update"&&u.$op==="match"||c[d].$op==="match"&&u.$op==="update")return [...c.slice(0,d),{...c[d],...u,$op:"update"},...c.slice(d+1)];if(c[d].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[d].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[d].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[d].$op}. Current: ${u.$op}`)},[]),s=i.reduce((c,u)=>{let d=c.find(f=>(f.$id&&f.$id===u.$id||f.$bzId&&f.$bzId===u.$bzId)&&f.$thing===u.$thing&&f.$op===u.$op);if(d){let f={...d};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=d[$],m=u[$];Array.isArray(g)&&Array.isArray(m)?f[$]=Array.from(new Set([...g,...m])):!Array.isArray(g)&&Array.isArray(m)?g!==void 0?f[$]=Array.from(new Set([g,...m])):f[$]=m:Array.isArray(g)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...g,m]))):g!==null&&m!==null&&g!==void 0&&m!==void 0?f[$]=Array.from(new Set([g,m])):g==null&&(f[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===u.$id||$.$bzId&&$.$bzId===u.$bzId)&&$.$thing===u.$thing&&$.$op===u.$op)),f]}return [...c,u]},[]),a=[...o,...s],l=new Set(a.filter(c=>c.$tempId).map(c=>c.$tempId)),p=Array.from(l).filter(c=>!a.some(u=>u.$tempId===c&&u.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:o,mergedEdges:s}};var Ar="___",il=Symbol.for("grandChildOfCreate"),Xi=async(e,t,r,n,i)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],s=(L,R)=>Object.keys(L).filter(S=>!S.startsWith("$")&&!o.includes(S)&&L[S]!==void 0?R?!V(t,L).dataFields?.find(F=>F.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:L,key:R,value:S})=>{L&&R&&!R.includes("$")&&!o.includes(R)&&isObject(L)?(Array.isArray(L[R])?L[R]:[L[R]]).forEach(F=>{if(isObject(F)){if(L.$op!=="create")a.includes(F.$op)||a.push(F.$op);else if(F.$op==="delete"||F.$op==="unlink")throw new Error(`Cannot ${F.$op} under a create`)}}):!L&&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 p=(L=>{let R=(S,B)=>{let F=[],O={},C=["$op","$bzId","$parentKey"],W=["$relation","$entity","$id",...C];for(let P in S)if(!C.includes(P)&&!(W.includes(P)&&!B))if(!P.includes("$")&&(isObject(S[P])||Array.isArray(S[P]))){let ae=ol(S[P]);if(Array.isArray(ae)&&ae.length>0)ae.forEach(Re=>{let Se={$path:P,...R(Re),...Re.$filter&&{$as:Re.$bzId}};F.find(te=>te.$path===Se.$path&&!te.$filter)||(F=[...F,Se]);});else {let Re={$path:P,...R(ae),...!ae.$filter&&{$as:ae.$bzId}};F=[...F,Re];}}else O[P]=S[P];return {...O,$fields:F}};return L.map(S=>R(S,true))})(Array.isArray(e)?e:[e]),u=(await lt(p,t,r,{...n,query:{...n.query,returnNulls:true}},i)).bql.res,d=(L,R)=>{let S=L.$id||L.id||L.$bzId;if(L.$objectPath){let{$objectPath:B}=L,F=B?.beforePath||"root",O=Array.isArray(B.ids)?`[${B.ids}]`:B.ids;return {beforePath:`${F}.${O}___${B.key}`,ids:S,key:R}}return {beforePath:"root",ids:S,key:R}},f=(L,R)=>{let S=L?.beforePath||"root";if(typeof S!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let B=(Array.isArray(L?.ids)?`[${L?.ids}]`:L?.ids);return `${S}.${B}___${L?.key}`},h=L=>{if(L.includes("[")&&L.includes("]")){let[R,S,B]=L.split(/[[\]]/);return S.split(",").map(O=>`${R}${O}${B}`)}return [L]},$={};(L=>produce(L,R=>traverse(R,({key:S,parent:B})=>{if(B&&S&&B.$id&&!S.includes("$")){let F=d(B,S),O=f(F);if(Array.isArray(B[S])){let C=[];B[S].forEach(W=>{isObject(W)?(W.$objectPath=F,C.push(W.$id.toString())):W&&C.push(W.toString());}),$[O]={$objectPath:F,$ids:C};}else {let C=B[S];isObject(C)?($[O]={$objectPath:F,$ids:[C.$id.toString()]},C.$objectPath=F):C?$[O]={$objectPath:F,$ids:[C.toString()]}:C===null&&($[O]=null);}}})))(u||{});let m=L=>produce(L,R=>traverse(R,({key:S,value:B,parent:F})=>{F&&S&&!S.includes("$")&&(Array.isArray(B)||isObject(B))&&!Array.isArray(F)&&(Array.isArray(F[S])?F[S].forEach(O=>{typeof O!="string"&&(O.$objectPath=d(F,S),O.$parentIsCreate=F.$op==="create",O[il]=F.$parentIsCreate||F[Symbol.for("grandChildOfCreate")]);}):isObject(F[S])&&(F[S].$parentIsCreate=F.$op==="create",F[S][Symbol.for("grandChildOfCreate")]=F.$parentIsCreate||F[Symbol.for("grandChildOfCreate")],F[S].$objectPath=d(F,S)));})),E=m(e),T=L=>{let R=[];return L.forEach(B=>{if(!B.$id&&!B.id&&!B.$tempId)if(B.$filter){let F=f({...B.$objectPath,key:B.$bzId}),O=$[F];O&&(Array.isArray(O.$ids)?O.$ids:[O.$ids]).forEach(W=>{let P={...B,$id:W,$bzId:`T4_${v4()}`,$filterBzId:B.$bzId};R.push(P);});}else {let F=f(B.$objectPath),O=$[F];O?O?.$ids?.forEach(C=>{let W={...B,$id:C,$bzId:`T4_${v4()}`};R.push(W);}):R.push(B);}else R.push(B);}),R.map(B=>{let F={...B};return s(F,true).forEach(O=>{let C=Array.isArray(F[O])?F[O]:[F[O]],W=T(C);F[O]=W;}),F})},y=T(Array.isArray(E)?E:[E]),w=m(y),Q=(L=>{let R=S=>{let B=te=>{let ie=[],Y=[],q=[];return te.forEach(H=>{let he=s(H,true);if(he.length>0){let _=false;he.forEach(K=>{(Array.isArray(H[K])?H[K]:[H[K]]).filter(de=>!de.$id&&!de.id&&typeof H=="object").length&&(_=true);}),_?ie.push(H):Y.push(H);}else H.$id?q.push({...H,$bzId:H.$tempId||H.$bzId}):q.push({...H,$bzId:H.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ie,operationWithoutMultiples:Y,otherOps:q}},{operationWithMultiples:F,operationWithoutMultiples:O,otherOps:C}=B(S),W=te=>{let Y=(()=>{let K={};for(let me in te){let re=V(t,te);!me.startsWith("$")&&re.dataFields?.find(de=>de.path===me)&&(K[me]=te[me]);}return K})(),q=Object.keys(te),H=s(te,true),he=[],_=(K,me)=>{if(K===H.length){let de={...me};q.forEach(ye=>{ye.startsWith("$")&&(de[ye]=te[ye]);}),he.push({...de,...Y});return}let re={...me,[H[K]]:te[H[K]],...xe(me),...Y};_(K+1,re),_(K+1,me);};return _(0,{...xe(te)}),he},P=[];return F.forEach(te=>{let ie=W(te),Y=[];ie.forEach(q=>{let H=s(q,true);if(q.$op==="create")Y.push(q);else if(q.$id){let he=f(q.$objectPath),_=[];if(H.forEach(K=>{let me=`${he.includes("undefined")?"root":he}.${q.$id}${Ar}${K}`,re=$[me];q[K].filter(ye=>ye.$op==="unlink"||ye.$op==="delete"||ye.$op==="update").length>0?re?.$ids&&_.push({key:K,ids:re.$ids}):_.push({key:K,ids:[""]});}),_.length===H.length&&!Y.find(K=>K.$id===q.$id))Y.push(q);else {let K={...q,$bzId:q.$tempId||`T4_${v4()}`};H.forEach(re=>{let de=q[re].filter(ye=>ye.$id);de.length>0?K[re]=de:K[re]=void 0;}),s(K,true).length>0&&Y.push(K);}}else if(q.$objectPath){let he=f(q.$objectPath),_=$[he]?.$ids||[];_.forEach(K=>{let me=[];H.forEach(re=>{let de=`${he}.${K}${Ar}${re}`,ye=$[de];ye&&me.push({key:re,ids:ye.$ids});}),H.length===0?_.filter(de=>!Y.find(ye=>ye.$id===de)).forEach(de=>{Y.push({...q,$id:de,$bzId:q.$tempId||`PQT2_${v4()}`});}):me.length===H.length&&!Y.find(re=>re.$id===K)&&(H.forEach(re=>{let de=`${f(q.$objectPath)}.${K}${Ar}${re}`,ye=$[de]?.$ids||[],Eo=q[re].find(Xe=>!Xe.$id),xr=[...ye.map(Xe=>({...Eo,$id:Xe,$objectPath:{beforePath:q.$objectPath.beforePath,ids:Xe,key:re}})),...q[re].filter(Xe=>Xe.$id)];xr.length>0&&(q[re]=xr);}),Y.push({...q,$id:K,$bzId:q.$tempId||`PQ3_${v4()}`}));});}else Y.push(q);}),Y.forEach(q=>{P.push(q);});}),[...P,...O,...C].filter(te=>s(te).length>0?true:te.$op!=="update").map(te=>{let ie={...te};return s(ie,true).forEach(Y=>{let q=Array.isArray(ie[Y])?ie[Y]:[ie[Y]],H=R(q);ie[Y]=H;}),ie})};return R(L)})(Array.isArray(w)?w:[w]),b=L=>L.map(R=>{let S=s(R,true),B={...R};return S.forEach(F=>{let O=Array.isArray(R[F])?R[F]:[R[F]],C=[],W=[],P=[],ae={},Re=nr(t,R,F);O.filter(_=>_).forEach(_=>{_.$op==="replace"&&_.$id?(ae=_,Array.isArray(_.$id)?W=[...W,..._.$id]:W.push(_.$id)):_.$op==="create"&&Re==="ONE"&&_.id?(ae=_,Array.isArray(_.id)?P=[...W,..._.id]:P.push(_.id)):C.push(_);});let Se=f(ae.$objectPath),ie=h(Se).map(_=>$[_]),Y=[];ie.filter(_=>_!=null).forEach(_=>{Y=[...Y,..._?.$ids||[]];});let q=Y.filter(_=>!W.includes(_)),H=W.filter(_=>!Y.includes(_)),he=xe(ae);q.length>0&&C.push({...ae,$op:"unlink",$id:q,$bzId:ae.$tempId||`T4_${v4()}`,id:void 0,...he}),H.length>0&&H.forEach(_=>{C.push({...ae,$op:"link",$id:_,$bzId:ae.$tempId||`T5_${v4()}`,...he});}),P.length>0&&P.forEach(_=>{C.push({...ae,$op:"create",id:_,$bzId:ae.$tempId||`T6_${v4()}`,...he});}),B[F]=b(C);}),B}),A=m(b(m(Q)));(L=>produce(L,R=>traverse(R,S=>{let{key:B,value:F,parent:O,meta:C}=S;B&&O&&!B?.includes("$")&&B!=="$filter"&&!C.nodePath?.includes(".$filter.")&&(Array.isArray(F)||isObject(F))&&!Array.isArray(O)&&(Array.isArray(F)?F:[F]).forEach(P=>{let ae=P.$filter?{...P.$objectPath,key:P.$filterBzId}:P.$objectPath,Re=f(ae),Se=$[Re],te=(q,H)=>q.every(he=>H.includes(he)),ie=P.$id?Array.isArray(P.$id)?te(P.$id,Se?.$ids?Se.$ids:[]):Se?.$ids?.includes(P.$id):Se,Y=nr(t,O,P.$objectPath.key);if(P.$op==="link"&&ie&&Y==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${f(P.$objectPath)}" because it is already occupied.`);if(P.$op)switch(P.$op){case "delete":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${P.$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:"${P.$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:"${P.$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:"${P.$id}" because it is already linked to $id:"${O.$id}"`);break;}});})))(A);let G=(L=>produce(L,R=>traverse(R,S=>{let{value:B,meta:F}=S;isObject(B)&&(B[Symbol.for("path")]=F.nodePath,B.$objectPath=void 0,B.$parentIsCreate=void 0);})))(A);return [...Array.isArray(G)?G:[G]].sort((L,R)=>L.$op==="create"&&R.$op!=="create"?-1:L.$op!=="create"&&R.$op==="create"?1:0)},ol=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Gi=(e,t)=>produce(e,n=>qt(t,n)),qt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){for(let i of t)qt(e,i,r);return}let n=ne(e,r||t.$entity||t.$relation||t.$thing);for(let[i]of Object.entries(t))i.startsWith("$")||i.startsWith("%")||al(e,t,i,n);},al=(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;qt(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[p]=l.playedBy||[];if(!p)throw new Error(`Role ${l.path} in ${n} is not played by anything`);qt(e,i,p.thing);}};var Et={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Bt=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(s=>{let l=Object.keys(s).reduce((p,c)=>{let u=s[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...p,[c]:void 0,[Et[c]]:Bt(u,t,r)};if(c==="$id")return {...p,$id:void 0,[Et[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return p;if(c==="$exists")return {...p,$exists:void 0,[Et[c]]:u};if(c==="$eq")return {...p,$eq:void 0,[Et[c]]:u};if(c==="$in")return {...p,$in:void 0,[Et[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let d=t in r.entities?r.entities[t]:r.relations[t],[f,h]=Rt(d,c);if(f==="idField"){if(d.idFields.length>1)throw new Error("Multiple id fields not supported");return {...p,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(f==="dataField")return {...p,[c]:Bt(u,t,r)};if(f==="linkField"||f==="roleField"){let g=h[He].queryPath;return {...p,[g]:Bt(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return n?o:o[0]},ze=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=>ze(a)):[ze(i)];o==="!"?r.push(`!(${s.join(" AND ")})`):r.push(`(${s.join(` ${o} `)})`);continue}if(isObject(i))if(n.includes("<-")||n.includes("->")){let o=ze(i);r.push(`${n}[WHERE ${o}]`);}else if(n.startsWith("$parent.[")){let o=ze(i),s=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`array::flatten([${s}])[WHERE id && ${o}]`);}else if(n.startsWith("$parent")){let o=ze(i),s=n.replace("$parent.","");r.push(`array::flatten([${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(p=>p===null?"NONE":`'${p}'`).join(", ")}]`);else if(isObject(a)){let p=ze(a);r.push(`${n} ${l} ${p}`);}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 ")};var to=async(e,t)=>{let r=c=>{let u=Be(c);return u!==c?u:`\u27E8${c}\u27E9`},n=c=>{let{$filter:u,$thing:d,$bzId:f,$op:h,$id:$,$tempId:g}=c,m=ne(t,d),{usedDataFields:E}=$e(m,c),{idFields:T}=m,y=$||c[T[0]],w=(isArray(d)?d:[d]).map(oe),M=fe(c,B=>B.startsWith("$")),Q=fe(c,B=>!B.startsWith("$")),b=JSON.stringify(Q),A=Object.entries(M).map(([B,F])=>B==="$tempId"?`'$tempId': '_:${F}'`:`'${B}': '${F}'`).join(","),k=c[tt],j=E.filter(B=>!T.includes(B)).map(B=>{let F=m.dataFields?.find(C=>C.path===B||C.dbPath===B);if(!F)throw new Error(`Data field schema not found for ${B}`);let O=c[B];return O===null?`${B} = NONE`:`${B} = ${Ge(O,F.contentType,t)}`}).filter(Boolean),G=`$\u27E8${g||f}\u27E9`,D=`$\u27E8${g||f}_pre\u27E9`,N=k?.bzId?`array::flatten($\u27E8${k.bzId}_pre\u27E9.${r(k.edgeField)} || []).filter(|$v| $v != NONE).len`:y?isArray(y)?w.flatMap(B=>y.map(F=>`${B}:\u27E8${F}\u27E9`)).join(", "):w.map(B=>`${B}:\u27E8${y}\u27E9`).join(", "):true,z=(()=>{if(k?.bzId){let B=`array::flatten($\u27E8${k.bzId}_pre\u27E9.${r(k.edgeField)} || []).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)?w.flatMap(B=>y.map(F=>`${B}:\u27E8${F}\u27E9`)).join(", "):w.map(B=>`${B}:\u27E8${y}\u27E9`).join(", "):w.join(", ")})(),L=u?`WHERE ${ze(Bt(u,d,t))}`:"",R=j.length>0?`SET ${j.join(", ")}`:"",S=`VALUE (CREATE ONLY Delta SET input = ${b}, meta = {${A}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`;if(["link","unlink","replace"].includes(h))throw new Error("Edge ops don't belong to things");if(c.$op==="match")return g?"":`LET ${G} = (SELECT VALUE id FROM ${z} ${L});
92
+ LET ${D} = (SELECT * FROM ${z} ${L});`;if(c.$op==="create"){if(isArray(y))throw new Error("Cannot create multiple things at once");let B=oe(d);return `LET ${G} = (CREATE ONLY ${B}:\u27E8${y}\u27E9 ${R} RETURN ${S});
93
+ LET ${D} = ${G};`}if(c.$op==="update")return `LET ${D} = IF (${N}) { (SELECT * FROM ${z} ${L}) };
94
+ LET ${G} = IF (${N}) { (UPDATE ${z} ${R} ${L} RETURN ${S}) };`;if(c.$op==="delete")return [`LET ${D} = IF (${N}) { (SELECT * FROM ${z} ${L}) };`,`LET ${G} = IF (${D}) { array::flatten([${z}]) };`,`IF (${D}) { DELETE ${z} ${L} };`].join(`
95
+ `);throw new Error(`Unsupported operation ${c.$op}`)},i=c=>{let{$thing:u,$bzId:d,$op:f,$tempId:h}=c,$=ne(t,u),{usedRoleFields:g}=$e($,c),m=`$\u27E8${h||d}\u27E9`,E=oe(u),T=[],y="roles"in $?g.flatMap(b=>{let A=$.roles[b];if(!A)throw new Error(`Role field schema not found for ${b}`);let{cardinality:k}=A,j=isArray(c[b])?c[b].map(D=>`$\u27E8${D}\u27E9`):[`$\u27E8${c[b]}\u27E9`];if(A.playedBy?.some(D=>D.cardinality==="ONE")&&f==="link"){if(k==="ONE"){let D=j.length>1?`(array::filter(array::flatten([${j}]), |$v| !!$v)[0])`:`(((type::is_array(${j[0]}) && array::len(${j[0]})==1) && ${j[0]}[0]) || ${j[0]})`;T.push(`UPDATE ${E} SET ${b} = NONE WHERE ${b} = ${D}`);}else if(k==="MANY"){let D=`array::flatten([${j}])`;T.push(`UPDATE ${E} SET ${b} -= ${D} WHERE ${b} CONTAINSANY ${D}`);}}if(k==="ONE"){if(j.length>1){let D=`array::filter(array::flatten([${j}]), |$v| !!$v)`;switch(f){case "link":case "replace":return `${b} = ${D}[0]`;case "unlink":return `${b} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}switch(f){case "link":case "replace":return `${b} = ((type::is_array(${j[0]}) && array::len(${j[0]})==1) && ${j[0]}[0]) || ${j[0]}`;case "unlink":return `${b} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}if(k==="MANY"){let D=`array::flatten([${j}])`;switch(f){case "link":return `${b} += ${D}`;case "unlink":return `${b} -= ${D}`;case "replace":return `${b} = ${D}`;default:throw new Error(`Unsupported operation ${f} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${k}`)}):[],w=y.length>0?`${y.join(", ")}`:"",M=w?`SET ${w}`:"";return `${T.length>0?`${T.join(`;
111
96
  `)};
112
- COMMIT TRANSACTION;`;return G("query",`query/batchedQuery
113
- `,o),n.query?.debugger&&ee(`batchedQuery[${te}]`,JSON.stringify({batchedQuery:o})),await t.query(o,i)};var Ji=async(e,t,r,n)=>{let i=nanoid(3);if(e.length===0)return [];let o=performance.now(),s=e.map(g=>bi.parse(g));G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/bqlQueries"],`> runSurrealDbQueryMachine2/bqlQueries ${i}
114
- `,JSON.stringify(s));let a=s.map(g=>Ti(g,t,!r.query?.noMetadata));G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/logicalQueries"],`> runSurrealDbQueryMachine2/logicalQueries ${i}
115
- `,JSON.stringify(a));let l=a.map(g=>qi(g,t));G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/optimizedQueries"],`> runSurrealDbQueryMachine2/optimizedQueries ${i}
116
- `,JSON.stringify(l));let d={},c=l.map(g=>Ai(g,d));G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/params"],`> runSurrealDbQueryMachine2/params ${i}
117
- `,JSON.stringify(d)),G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/surqlQueries"],`> runSurrealDbQueryMachine2/surqlQueries ${i}
118
- `,JSON.stringify(c));let u=performance.now(),p=await vi({client:n,queries:c,config:r,params:d}),f=performance.now();G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/queryDuration"],`> runSurrealDbQueryMachine2/queryDuration ${i}
119
- `,`${(f-u).toFixed(2)}ms`),G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/result"],`> runSurrealDbQueryMachine2/result ${i}
120
- `,JSON.stringify(p));let h=Hi({batch:s,results:p,schema:t,metadata:!r.query?.noMetadata,returnNulls:!!r.query?.returnNulls});G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/finalResult"],`> runSurrealDbQueryMachine2/finalResult ${i}
121
- `,h);let $=performance.now();return G(["runSurrealDbQueryMachine2","runSurrealDbQueryMachine2/duration"],`> runSurrealDbQueryMachine2/duration ${i}
122
- `,`${($-o).toFixed(2)}ms`),h};var zt=e=>{let{$filter:t,$var:r,$thing:n,schema:i,depth:o}=e,s=dl(t,re(i,n)),{$not:a,...l}=s,d=[];if(Rr(a)){let u=wr(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=wr(l,r,n,i,o,false);return d.push(...c),d.join(`
123
- `)},wr=(e,t,r,n,i,o)=>{let s=re(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(g=>{if(Rr(g))return wr(g,t,r,n,i+1,o).join(`
124
- `);throw new Error(`Invalid subfilter in ${p}: ${JSON.stringify(g)}`)}),$=h.join(p==="$and"?`
125
- `:" } or { ");p==="$or"&&h.length>1?a.push(M(`{ ${$} };`,i)):a.push(M($,i));continue}continue}if(s.dataFields?.find(p=>p.dbPath===l||p.path===l)){let p=al(l,d,t,i,o);a.push(...p);continue}let u=s.linkFields?.find(p=>p.path===l);if(u){let p=ll(u,d,t,n,i,o);a.push(...p);continue}if(s.thingType==="relation"){let p=s.roles[l];if(p){let f=cl(p,d,t,r,n,i,o);a.push(...f);continue}}throw new Error(`"${r}" does not have property "${l}"`)}return a},al=(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=Ft(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(M(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(M(d,n));}else if(isArray(t)){let s=t.map(l=>`$${r} has ${e} ${Se(l)};`),a=Ft(s);a&&(i&&(a=`not { ${a} };`),o.push(M(a,n)));}else {let s=`$${r} has ${e} ${Se(t)};`;i&&(s=`not { ${s} };`),o.push(M(s,n));}return o},ll=(e,t,r,n,i,o)=>{let s=[],[a]=e.oppositeLinkFieldsPlayedBy,d=re(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=Ft(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=Ft(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(M(u,i)),s},cl=(e,t,r,n,i,o,s)=>{let a=[],[l]=e.playedBy||[],c=re(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(M(`$${f} isa ${n};`,o));let h="";if(t===null)h=`$${f} (${l.plays}: ${u});`,s?a.push(M(h,o)):a.push(M(`not { ${h} };`,o));else if(isArray(t)){let $=t.map(g=>`$${u} isa ${l.thing}, has ${c} ${Se(g)}; $${f} (${l.plays}: $${u});`);h=Ft($),s?a.push(M(`not { ${h} };`,o)):a.push(M(h,o));}else h=`$${u} isa ${l.thing}, has ${c} ${Se(t)}; $${f} (${l.plays}: $${u});`,s?a.push(M(`not { ${h} };`,o)):a.push(M(h,o));return a.push(M(`$${r} is $${f};`,o)),a},Ft=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}`)},dl=(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=Ki(i,r);return n&&Rr(n)&&(o.$not=Ki(n,r)),o},Ki=(e,t)=>{let r={};return Object.entries(e).forEach(([n,i])=>{let o=t[n]||n;r[o]=i;}),r},Rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Lr="___",Xi=async e=>{let{queries:t,schema:r}=e;return t.map(n=>ul({query:n,schema:r}))},ul=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[le];if(u.push("match"),u.push(`$${n} isa ${i};`),o||c){let $=Dt(r,t),g={...o,...c?{[$]:c}:{}},y=zt({$filter:g,$var:n,$thing:i,schema:r,depth:0});u.push(`
126
- ${y}`);}let f=Ar({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(...Mr($,n,0));let g=s.filter(m=>m.$fieldType==="link");g&&g.length>0&&u.push(...Dr(g,n,n,0,r));let y=s.filter(m=>m.$fieldType==="role");y&&y.length>0&&u.push(...Qr(y,n,n,0,r));}return f&&u.push(f.sort),typeof l=="number"&&u.push(`
127
- offset ${l};`),typeof d=="number"&&u.push(`
128
- limit ${d};`),u.join(`
129
- `)},Mr=(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=[M(`$${t} as "${t}.${l}.$dataFields": ${s};`,r)];return o.length>0&&o.forEach(c=>{d.push(M(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),d},Qr=(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:g}=a,y=a[le],m=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(M(`"${r}.${m}.${a.$var}": {`,n)),s.push(M("match",o));let F=`${t}${Lr}${a.$var}`;if(s.push(M(`$${F} isa ${a.$thing};`,o)),s.push(M(`$${t} (${a.$var}: $${t}${Lr}${a.$var}) isa ${a.$intermediary};`,o)),a.$filter||a.$id){let w=Dt(i,a),S=a.$id?{[w]:a.$id}:{},Q={...a.$filter,...S};s.push(zt({$filter:Q,$var:F,$thing:a.$thing,schema:i,depth:o}));}let E=Ar({schema:i,$thing:f,$var:F,$sort:h,depth:o});if(E&&s.push(E.match),l){let w=`M_${v4()}`;s.push(M(`
130
- ?queryPath${w} = "${y}";`,o)),s.push(M("fetch",o)),s.push(M(`?queryPath${w} as "queryPath";`,o));let S=l?.filter(O=>O.$fieldType==="data");S&&S.length>0&&s.push(...Mr(S,F,o));let Q=l?.filter(O=>O.$fieldType==="link");Q&&Q.length>0&&s.push(...Dr(Q,F,`${t}.${a.$var}`,o,i));let L=l?.filter(O=>O.$fieldType==="role");L&&L.length>0&&s.push(...Qr(L,F,`${t}.${a.$var}`,o,i));}E&&s.push(E.sort),typeof $=="number"&&s.push(M(`offset ${$};`,o)),typeof g=="number"&&s.push(M(`limit ${g};`,o)),s.push(M("};",n));}return s},Dr=(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:g,$limit:y}=a,m=a[le],F=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(M(`"${r}.${F}.${a.$var}": {`,n)),s.push(M("match",o));let E=`${t}${Lr}${a.$var}`;if(s.push(M(`$${E} isa ${a.$thing};`,o)),a.$filter||a.$id){let S=Dt(i,a),Q=a.$id?{[S]:a.$id}:{},L={...a.$filter,...Q};s.push(zt({$filter:L,$var:E,$thing:a.$thing,schema:i,depth:o}));}let w=Ar({schema:i,$thing:h,$var:E,$sort:$,depth:o});if(w&&s.push(w.match),a.$target==="role"?s.push(M(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${E}) isa ${a.$intermediary};`,o)):s.push(M(`$${E} (${a.$plays}: $${t});`,o)),l){let S=`M_${v4()}`;s.push(M(`?queryPath${S} = "${m}";`,o)),s.push(M("fetch",o)),s.push(M(`?queryPath${S} as "queryPath";`,o));let Q=l?.filter(H=>H.$fieldType==="data");Q&&Q.length>0&&s.push(...Mr(Q,E,o));let L=l?.filter(H=>H.$fieldType==="link");L&&L.length>0&&s.push(...Dr(L,E,`${t}.${a.$var}`,o,i));let O=l?.filter(H=>H.$fieldType==="role");O&&O.length>0&&s.push(...Qr(O,E,`${t}.${a.$var}`,o,i));}w&&s.push(w.sort),typeof g=="number"&&s.push(M(`offset ${g};`,o)),typeof y=="number"&&s.push(M(`limit ${y};`,o)),s.push(M("};",n));}return s},pl=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},Ar=e=>{let{$var:t,$thing:r,schema:n,$sort:i,depth:o}=e,s=re(n,r),a=[],l=[];if(i?.forEach(d=>{let c=pl(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(M("{",o)),a.push(M(`$${t} has ${u.dbPath} $${p}_1;`,o+1)),a.push(M("not {",o+1)),a.push(M(`$${t} has ${u.dbPath} $${p}_2;`,o+2)),a.push(M(`$${p}_2 < $${p}_1;`,o+2)),a.push(M("};",o+1)),a.push(M(`?${p}_ = $${p}_1;`,o+1)),a.push(M("} or {",o)),a.push(M(`not { $${t} has ${u.dbPath} $${p}_1; };`,o+1)),a.push(M(`?${p}_ = "~";`,o+1)),a.push(M("};",o)),a.push(M(`?${p} = ?${p}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${p} ${f}`);}),a.length!==0)return {match:a.join(""),sort:M(`sort ${l.join(", ")};`,o)}};var Gi=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 fl(s,l,d,n,i)})},fl=(e,t,r,n,i)=>e.length===0?null:r.$filterByUnique?Zi(e[0],t,n,i):e.map(o=>Zi(o,t,n,i)),Zi=(e,t,r,n)=>{let{dataFields:i,currentSchema:o,linkFields:s,roleFields:a,schemaValue:l}=Nr(e,r),d=Or(i,o,n),c=kr(s,r,n),u=Ir(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}},Nr=(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,[le]: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(g=>g.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}},Or=(e,t,r)=>{let{$metaData:n}=e,{as:i}=$l(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])},Ir=(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}=eo(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=Nr(f,t),F=Or(h,$,r);if(d==="T")return F.id;let E=kr(g,t,r),w=Ir(y,t,r),S={...F};if(c==="true"&&$?.idFields)for(let Q of $.idFields)delete S[Q];return {...S,...E,...w,...m}});p.length>0?n[l]=a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls&&(n[l]=null);}return n},kr=(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}=eo(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=Nr(f,t),F=Or(h,$,r);if(d==="T")return F.id;let E=kr(g,t,r),w=Ir(y,t,r),S={...F};if(c==="true")for(let Q of $.idFields??[])delete S[Q];return {...S,...E,...w,...m}});n[l]=p.length>0?a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls?null:void 0;}return n},eo=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}},$l=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 Ut=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 to=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,i=new TypeDBOptions;i.infer=true;let{session:o}=await Ut(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 Fl=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Cr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,bl=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Tl=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,dt=j("error","error",x((e,t)=>({...e,error:t.error}))),Sl=we("enrich",{enrich:U(async e=>(ee(`originalBQLQuery[${te}]`,JSON.stringify(e.bql.raw)),nt(e.bql.raw,e.schema)),j("done","build",x(Fl)),dt),build:U(async e=>Xi({queries:e.bql.queries??[],schema:e.schema}),j("done","run",x(bl)),dt),run:U(async e=>to({dbHandles:e.handles,tqlRequest:Ee(e.tql.queries),config:e.config}),j("done","parse",x(Tl)),dt),parse:U(async e=>Gi({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries??[],schema:e.schema,config:e.config,rawTqlRes:Ee(e.tql.res)}),j("done","postHooks",x(Cr)),dt),postHooks:U(async e=>qt(e.schema,Ee(e.bql.queries),Ee(e.bql.res)),j("done","clean",x(Cr)),dt),clean:U(async e=>Ct(e.config,Ee(e.bql.res)),j("done","success",x(Cr)),dt),success:me(),error:me()},e=>e),wl=async e=>new Promise((t,r)=>{Re(Sl,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)=>wl({bql:{raw:e},tql:{},schema:t,config:r,handles:n,error:null});var Rl=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Ll=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,no=j("error","error",x((e,t)=>({...e,error:t.error}))),Ml=we("enrich",{enrich:U(async e=>(ee(`originalBQLQuery[${te}]`,JSON.stringify(e.bql.raw)),nt(e.bql.raw,e.schema)),j("done","adapter",x(Rl)),no),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=re(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 ro(a.rawBql,e.schema,e.config,e.handles);if(a.db==="surrealDB")return e.config.query?.legacySurrealDBAdapter?Ei(a.rawBql,e.schema,e.config,a.client):Ji(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)},j("done","success",x(Ll)),no),success:me(),error:me()},e=>e),Ql=async e=>new Promise((t,r)=>{Re(Ml,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ut=async(e,t,r,n,i)=>Ql({bql:{raw:e},schema:t,draftSchema:r,config:n,handles:i,error:null});var ao=async(e,t,r,n,i)=>{let o=Array.isArray(e)?e:[e],s=o.map(d=>qr(d,true)),l=(await ut(s,t,r,n,i)).bql.res;return o.map((d,c)=>{let u=re(t,d.$thing);return co({mut:d,node:l[c],schema:t,thing:u})})},lo=new Set(["$op","$bzId","$parentKey"]),Al=new Set(["$relation","$entity","$id",...lo]),qr=(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(lo.has(i)||Al.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,...qr(o[0],false)}):isObject(o)&&(r[i]={$path:i,...qr(o,false)});}return n.$fields=Object.values(r),n},co=e=>{let{mut:t,node:r,schema:n,thing:i}=e,o=po(i),s=Ol(r);if(Array.isArray(t))return t.map(l=>{let d=s[l.$id];return d?io({mut:l,node:d,schema:n,thing:i,...o}):l});let a=s[t.$id];return io({mut:t,node:a,schema:n,thing:i,...o})},io=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=uo({$fields:t.$fields,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}),u={...d,[tt]: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 g=re(n,$);u[p]=co({mut:f,schema:n,node:r[p],thing:g});}return u},uo=e=>{let{$fields:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,l=t||Nl(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(oo):oo(f));return}let g=re(n,$),y=po(g);d[p]=Array.isArray(f)?f.map(m=>so({...y,$fields:c.$fields,value:m,schema:n,thing:g})):so({...y,$fields:c.$fields,value:f,schema:n,thing:g});}),d},Nl=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},oo=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},so=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 uo({...e,node:t})},po=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}},Ol=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 ho=(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:g}=ge(u,s);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let m={...ye(s,F=>![...$,...h,...g].includes(F)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[Lt]:p}};r.things.push(m);}let y={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let m=ye(s,F=>isSymbol(F)||F.startsWith("$"));for(let F of $){if(isArray(s[F]))for(let w of s[F])n(w,{bzId:d,edgeField:F,tempId:c});else n(s[F],{bzId:d,edgeField:F,tempId:c});let E=(isArray(s[F])?s[F]:[s[F]]).filter(Boolean);for(let[w,S]of Object.entries(y)){let Q=E.filter(L=>S.includes(L.$op)).map(L=>L.$bzId);Q.length>0&&r.edges.push({...m,[F]:Q,$op:w});}}}if(h)for(let m of h){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 F=u.linkFields?.find(w=>w.path===m),E=isArray(s[m])?s[m]:[s[m]];if(F.target==="relation")for(let[w,S]of Object.entries(y)){let Q=E.filter(L=>S.includes(L.$op));for(let L of Q){let O=ye(L,H=>isSymbol(H)||H.startsWith("$"));r.edges.push({...O,[F.plays]:d,$op:w});}}if(F.target==="role"){let w={create:["link","create"],delete:["unlink","delete"],replace:["replace"]};for(let[S,Q]of Object.entries(w)){let L=E.filter(O=>Q.includes(O.$op));if(L.length!==0)for(let O of L){let H={$thing:F.relation,$thingType:"relation",$bzId:`arc_${O.$bzId}`,[F.plays]:d,[F.oppositeLinkFieldsPlayedBy[0].plays]:O.$bzId,$op:S};r.arcs.push(H);}}}}if(g)for(let m of g){if(isArray(s[m]))for(let S of s[m])n(S,{bzId:d,edgeField:m,tempId:c});else n(s[m],{bzId:d,edgeField:m,tempId:c});let F=(isArray(s[m])?s[m]:[s[m]]).filter(S=>S!=null),E=ye(s,S=>isSymbol(S)||S.startsWith("$")),w=F.map(S=>S.$op?`$\u27E8${S.$bzId}\u27E9`:et(S,"FLEX"));w.length>0&&r.references.push({...E,[m]:w,$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 yo=async(e,t)=>{let r=c=>{let u=[],p=[],f=y=>{if(y.$id)return y.$id;let m=z(t,y),{idFields:F}=m;if(!F)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[E]=F;if(!E)throw new Error(`no idField: ${JSON.stringify(y)}`);let w=m.dataFields?.find(L=>L.path===E),S=it({currentThing:y,fieldSchema:w,mandatoryDependencies:true}),Q=y[E]||y.$id||S;if(!Q)throw new Error(`no idValue: ${JSON.stringify(y)}`);return Q},h=y=>{if(y.$op==="create"){let m=f(y);if(u.find(F=>F.$id===m&&F.$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(F=>F.$id===m&&F.$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:F})=>{if(!isObject(y))return;let E=y;if(!F.nodePath?.includes(".$filter")&&E.$thing){if(!E.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(E)}`);if(!E.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(E)}`);let w=z(t,E),{dataFields:S,roleFields:Q,linkFields:L,refFields:O,usedFields:H}=ge(w,E),oe=()=>{if(E.$op==="create"||E.$op==="delete")return E.$op;if(E.$op==="update"){let A=H.filter(T=>S?.includes(T)),X=H.filter(T=>Q?.includes(T)),b=H.filter(T=>L?.includes(T)),B=H.filter(T=>O?.includes(T));if(A.length>0)return "update";if(X.length>0||b.length>0||B.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(E)}`)}return "match"},ce={...E.$id&&{$id:E.$id},...E.$tempId&&{$tempId:E.$tempId},...E.$filter&&{$filter:E.$filter},$thing:E.$thing,...E.$thingType&&{$thingType:E.$thingType},...shake(pick(E,S||[""])),$op:oe(),$bzId:E.$bzId};h(ce);let k=E[Ne];if(k?.[v].fieldType==="linkField"){if((E.$op==="link"||E.$op==="unlink")&&(E.$id||E.$filter)){if(E.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...E,$op:"match"});}let A=k.$things.includes(E.$thing),X=A?E.$bzId:`LT_${v4()}`,B=In(c,m,F).$bzId;if(!B)throw new Error("No parent id found");let T=()=>E.$op==="delete"?A?"match":"delete":E.$op==="unlink"?A?"unlink":"delete":E.$op==="link"||E.$op==="create"?A?"link":"create":E.$op==="replace"?"replace":"match",D=z(t,{$thing:k.relation,$thingType:"relation"});if(!Object.keys(D.roles).includes(k.plays))throw new Error(`[Wrong format] Field ${k.plays} is not a role of relation ${k.relation}`);let N={$bzId:X,$thing:A?E.$thing:k.relation,$thingType:"relation",...E.$tempId?{$tempId:E.$tempId}:{},$op:T(),...A?{}:{[k.path]:E.$bzId},[k.plays]:B,[Ne]:k,[ve]:"linkField"};$(N),(E.$op==="unlink"||T()==="unlink")&&A&&$({$thing:k.relation,$thingType:"relation",$bzId:X,$op:"match",[k.plays]:B,[Ne]:k,[ve]:"linkField"});}if(E.$thingType==="relation"){let A=ye(E,(B,T)=>Q.includes(B)),X=mapEntries(A,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),b=ye(y,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(A).filter(B=>!B.startsWith("$")).length>0){if(E.$op==="create"||E.$op==="delete"){let B=()=>{if(E.$op==="create")return "link";if(E.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=z(t,E).roles,D=mapEntries(X,(N,C)=>{let V=T[N]?.cardinality;if(!V)throw new Error(`Role ${N} not found in schema`);return Array.isArray(C)?V==="ONE"?C.length>1?[N,C.map(q=>q.$bzId||q)]:[N,C[0].$bzId||C[0]]:[N,C.map(q=>q.$bzId||q)]:[N,C.$bzId||C]}),R={...b,$thing:E.$thing,$thingType:"relation",$op:B(),...D,$bzId:E.$bzId,[ve]:"roleField"};$(R);return}if(E.$op==="match"||E.$op==="update"&&Object.keys(A).length>0){Object.entries(A).forEach(([T,D])=>{let R=isArray(D)?D:[D],N=C=>C==="create"||C==="replace"?"link":C;R.forEach(C=>{if(!C)return;let V=N(C.$op);if(V==="replace")throw new Error("Not supported yet: replace on roleFields");let q={...b,$thing:E.$thing,$thingType:"relation",$op:V==="delete"?"unlink":V,[T]:C.$bzId,$bzId:E.$bzId,[ve]:"roleField"};$(q);});});}}}}}),[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 g=p[$],y=u[$];Array.isArray(g)&&Array.isArray(y)?f[$]=Array.from(new Set([...g,...y])):!Array.isArray(g)&&Array.isArray(y)?g!==void 0?f[$]=Array.from(new Set([g,...y])):f[$]=y:Array.isArray(g)&&!Array.isArray(y)?y!==void 0&&(f[$]=Array.from(new Set([...g,y]))):g!==null&&y!==null&&g!==void 0&&y!==void 0?f[$]=Array.from(new Set([g,y])):g==null&&(f[$]=y);}),[...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(kn(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 xr="___",xl=Symbol.for("grandChildOfCreate"),go=async(e,t,r,n,i)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],s=(b,B)=>Object.keys(b).filter(T=>!T.startsWith("$")&&!o.includes(T)&&b[T]!==void 0?B?!z(t,b).dataFields?.find(R=>R.path===T):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:B,value:T})=>{b&&B&&!B.includes("$")&&!o.includes(B)&&isObject(b)?(Array.isArray(b[B])?b[B]:[b[B]]).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(T)&&(a.includes(T.$op)||a.push(T.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let d=(b=>{let B=(T,D)=>{let R=[],N={},C=["$op","$bzId","$parentKey"],V=["$relation","$entity","$id",...C];for(let q in T)if(!C.includes(q)&&!(V.includes(q)&&!D))if(!q.includes("$")&&(isObject(T[q])||Array.isArray(T[q]))){let de=jl(T[q]);if(Array.isArray(de)&&de.length>0)de.forEach(De=>{let Ae={$path:q,...B(De),...De.$filter&&{$as:De.$bzId}};R.find(ne=>ne.$path===Ae.$path&&!ne.$filter)||(R=[...R,Ae]);});else {let De={$path:q,...B(de),...!de.$filter&&{$as:de.$bzId}};R=[...R,De];}}else N[q]=T[q];return {...N,$fields:R}};return b.map(T=>B(T,true))})(Array.isArray(e)?e:[e]),u=(await ut(d,t,r,{...n,query:{...n.query,returnNulls:true}},i)).bql.res,p=(b,B)=>{let T=b.$id||b.id||b.$bzId;if(b.$objectPath){let{$objectPath:D}=b,R=D?.beforePath||"root",N=Array.isArray(D.ids)?`[${D.ids}]`:D.ids;return {beforePath:`${R}.${N}___${D.key}`,ids:T,key:B}}return {beforePath:"root",ids:T,key:B}},f=(b,B)=>{let T=b?.beforePath||"root";if(typeof T!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let D=(Array.isArray(b?.ids)?`[${b?.ids}]`:b?.ids);return `${T}.${D}___${b?.key}`},h=b=>{if(b.includes("[")&&b.includes("]")){let[B,T,D]=b.split(/[[\]]/);return T.split(",").map(N=>`${B}${N}${D}`)}return [b]},$={};(b=>produce(b,B=>traverse(B,({key:T,parent:D})=>{if(D&&T&&D.$id&&!T.includes("$")){let R=p(D,T),N=f(R);if(Array.isArray(D[T])){let C=[];D[T].forEach(V=>{isObject(V)?(V.$objectPath=R,C.push(V.$id.toString())):V&&C.push(V.toString());}),$[N]={$objectPath:R,$ids:C};}else {let C=D[T];isObject(C)?($[N]={$objectPath:R,$ids:[C.$id.toString()]},C.$objectPath=R):C?$[N]={$objectPath:R,$ids:[C.toString()]}:C===null&&($[N]=null);}}})))(u||{});let y=b=>produce(b,B=>traverse(B,({key:T,value:D,parent:R})=>{R&&T&&!T.includes("$")&&(Array.isArray(D)||isObject(D))&&!Array.isArray(R)&&(Array.isArray(R[T])?R[T].forEach(N=>{typeof N!="string"&&(N.$objectPath=p(R,T),N.$parentIsCreate=R.$op==="create",N[xl]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")]);}):isObject(R[T])&&(R[T].$parentIsCreate=R.$op==="create",R[T][Symbol.for("grandChildOfCreate")]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")],R[T].$objectPath=p(R,T)));})),m=y(e),F=b=>{let B=[];return b.forEach(D=>{if(!D.$id&&!D.id&&!D.$tempId)if(D.$filter){let R=f({...D.$objectPath,key:D.$bzId}),N=$[R];N&&(Array.isArray(N.$ids)?N.$ids:[N.$ids]).forEach(V=>{let q={...D,$id:V,$bzId:`T4_${v4()}`,$filterBzId:D.$bzId};B.push(q);});}else {let R=f(D.$objectPath),N=$[R];N?N?.$ids?.forEach(C=>{let V={...D,$id:C,$bzId:`T4_${v4()}`};B.push(V);}):B.push(D);}else B.push(D);}),B.map(D=>{let R={...D};return s(R,true).forEach(N=>{let C=Array.isArray(R[N])?R[N]:[R[N]],V=F(C);R[N]=V;}),R})},E=F(Array.isArray(m)?m:[m]),w=y(E),Q=(b=>{let B=T=>{let D=ne=>{let ae=[],K=[],_=[];return ne.forEach(W=>{let $e=s(W,true);if($e.length>0){let P=false;$e.forEach(J=>{(Array.isArray(W[J])?W[J]:[W[J]]).filter(ue=>!ue.$id&&!ue.id&&typeof W=="object").length&&(P=true);}),P?ae.push(W):K.push(W);}else W.$id?_.push({...W,$bzId:W.$tempId||W.$bzId}):_.push({...W,$bzId:W.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ae,operationWithoutMultiples:K,otherOps:_}},{operationWithMultiples:R,operationWithoutMultiples:N,otherOps:C}=D(T),V=ne=>{let K=(()=>{let J={};for(let Be in ne){let ie=z(t,ne);!Be.startsWith("$")&&ie.dataFields?.find(ue=>ue.path===Be)&&(J[Be]=ne[Be]);}return J})(),_=Object.keys(ne),W=s(ne,true),$e=[],P=(J,Be)=>{if(J===W.length){let ue={...Be};_.forEach(Fe=>{Fe.startsWith("$")&&(ue[Fe]=ne[Fe]);}),$e.push({...ue,...K});return}let ie={...Be,[W[J]]:ne[W[J]],...xe(Be),...K};P(J+1,ie),P(J+1,Be);};return P(0,{...xe(ne)}),$e},q=[];return R.forEach(ne=>{let ae=V(ne),K=[];ae.forEach(_=>{let W=s(_,true);if(_.$op==="create")K.push(_);else if(_.$id){let $e=f(_.$objectPath),P=[];if(W.forEach(J=>{let Be=`${$e.includes("undefined")?"root":$e}.${_.$id}${xr}${J}`,ie=$[Be];_[J].filter(Fe=>Fe.$op==="unlink"||Fe.$op==="delete"||Fe.$op==="update").length>0?ie?.$ids&&P.push({key:J,ids:ie.$ids}):P.push({key:J,ids:[""]});}),P.length===W.length&&!K.find(J=>J.$id===_.$id))K.push(_);else {let J={..._,$bzId:_.$tempId||`T4_${v4()}`};W.forEach(ie=>{let ue=_[ie].filter(Fe=>Fe.$id);ue.length>0?J[ie]=ue:J[ie]=void 0;}),s(J,true).length>0&&K.push(J);}}else if(_.$objectPath){let $e=f(_.$objectPath),P=$[$e]?.$ids||[];P.forEach(J=>{let Be=[];W.forEach(ie=>{let ue=`${$e}.${J}${xr}${ie}`,Fe=$[ue];Fe&&Be.push({key:ie,ids:Fe.$ids});}),W.length===0?P.filter(ue=>!K.find(Fe=>Fe.$id===ue)).forEach(ue=>{K.push({..._,$id:ue,$bzId:_.$tempId||`PQT2_${v4()}`});}):Be.length===W.length&&!K.find(ie=>ie.$id===J)&&(W.forEach(ie=>{let ue=`${f(_.$objectPath)}.${J}${xr}${ie}`,Fe=$[ue]?.$ids||[],qo=_[ie].find(Ge=>!Ge.$id),Wr=[...Fe.map(Ge=>({...qo,$id:Ge,$objectPath:{beforePath:_.$objectPath.beforePath,ids:Ge,key:ie}})),..._[ie].filter(Ge=>Ge.$id)];Wr.length>0&&(_[ie]=Wr);}),K.push({..._,$id:J,$bzId:_.$tempId||`PQ3_${v4()}`}));});}else K.push(_);}),K.forEach(_=>{q.push(_);});}),[...q,...N,...C].filter(ne=>s(ne).length>0?true:ne.$op!=="update").map(ne=>{let ae={...ne};return s(ae,true).forEach(K=>{let _=Array.isArray(ae[K])?ae[K]:[ae[K]],W=B(_);ae[K]=W;}),ae})};return B(b)})(Array.isArray(w)?w:[w]),L=b=>b.map(B=>{let T=s(B,true),D={...B};return T.forEach(R=>{let N=Array.isArray(B[R])?B[R]:[B[R]],C=[],V=[],q=[],de={},De=lr(t,B,R);N.filter(P=>P).forEach(P=>{P.$op==="replace"&&P.$id?(de=P,Array.isArray(P.$id)?V=[...V,...P.$id]:V.push(P.$id)):P.$op==="create"&&De==="ONE"&&P.id?(de=P,Array.isArray(P.id)?q=[...V,...P.id]:q.push(P.id)):C.push(P);});let Ae=f(de.$objectPath),ae=h(Ae).map(P=>$[P]),K=[];ae.filter(P=>P!=null).forEach(P=>{K=[...K,...P?.$ids||[]];});let _=K.filter(P=>!V.includes(P)),W=V.filter(P=>!K.includes(P)),$e=xe(de);_.length>0&&C.push({...de,$op:"unlink",$id:_,$bzId:de.$tempId||`T4_${v4()}`,id:void 0,...$e}),W.length>0&&W.forEach(P=>{C.push({...de,$op:"link",$id:P,$bzId:de.$tempId||`T5_${v4()}`,...$e});}),q.length>0&&q.forEach(P=>{C.push({...de,$op:"create",id:P,$bzId:de.$tempId||`T6_${v4()}`,...$e});}),D[R]=L(C);}),D}),O=y(L(y(Q)));(b=>produce(b,B=>traverse(B,T=>{let{key:D,value:R,parent:N,meta:C}=T;D&&N&&!D?.includes("$")&&D!=="$filter"&&!C.nodePath?.includes(".$filter.")&&(Array.isArray(R)||isObject(R))&&!Array.isArray(N)&&(Array.isArray(R)?R:[R]).forEach(q=>{let de=q.$filter?{...q.$objectPath,key:q.$filterBzId}:q.$objectPath,De=f(de),Ae=$[De],ne=(_,W)=>_.every($e=>W.includes($e)),ae=q.$id?Array.isArray(q.$id)?ne(q.$id,Ae?.$ids?Ae.$ids:[]):Ae?.$ids?.includes(q.$id):Ae,K=lr(t,N,q.$objectPath.key);if(q.$op==="link"&&ae&&K==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${f(q.$objectPath)}" because it is already occupied.`);if(q.$op)switch(q.$op){case "delete":if(!ae&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${q.$id}" because it is not linked to $id:"${N.$id}"`);break;case "update":if(!ae&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${q.$id}" because it is not linked to $id:"${N.$id}"`);break;case "unlink":if(!ae&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${q.$id}" because it is not linked to $id:"${N.$id}"`);break;case "link":if(ae)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${q.$id}" because it is already linked to $id:"${N.$id}"`);break;}});})))(O);let ce=(b=>produce(b,B=>traverse(B,T=>{let{value:D,meta:R}=T;isObject(D)&&(D[Symbol.for("path")]=R.nodePath,D.$objectPath=void 0,D.$parentIsCreate=void 0);})))(O);return [...Array.isArray(ce)?ce:[ce]].sort((b,B)=>b.$op==="create"&&B.$op!=="create"?-1:b.$op!=="create"&&B.$op==="create"?1:0)},jl=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Eo=(e,t)=>produce(e,n=>Ht(t,n)),Ht=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){for(let i of t)Ht(e,i,r);return}let n=re(e,r||t.$entity||t.$relation||t.$thing);for(let[i]of Object.entries(t))i.startsWith("$")||i.startsWith("%")||zl(e,t,i,n);},zl=(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;Ht(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`);Ht(e,i,d.thing);}};var Bo=async(e,t)=>{let r=a=>{let{$filter:l,$thing:d,$bzId:c,$op:u,$id:p,$tempId:f}=a,h=re(t,d),{usedDataFields:$}=ge(h,a),{idFields:g}=h,y=p||a[g[0]],m=(isArray(d)?d:[d]).map(se),F=ye(a,b=>b.startsWith("$")),E=ye(a,b=>!b.startsWith("$")),w=JSON.stringify(E),S=Object.entries(F).map(([b,B])=>b==="$tempId"?`'$tempId': '_:${B}'`:`'${b}': '${B}'`).join(","),Q=a[Lt],L=$.filter(b=>!g.includes(b)).map(b=>{let B=h.dataFields?.find(D=>D.path===b||D.dbPath===b);if(!B)throw new Error(`Data field schema not found for ${b}`);let T=a[b];return T===null?`${b} = NONE`:`${b} = ${et(T,B.contentType,t)}`}).filter(Boolean),O=`$\u27E8${f||c}\u27E9`,H=Q?.bzId?`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:y?isArray(y)?m.flatMap(b=>y.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):true,oe=(()=>{if(Q?.bzId){let b=`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return y?isArray(y)?`${b}[? $this.id() IN [${y.map(B=>`'${B}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${y}'] ]`:b}return y?isArray(y)?m.flatMap(b=>y.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):m.join(", ")})(),ce=l?`WHERE ${be(Le(l,d,t))}`:"",k=L.length>0?`SET ${L.join(", ")}`:"",A=`VALUE (CREATE ONLY Delta SET input = ${w}, meta = {${S}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,X="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return f?"":`LET ${O} = (SELECT VALUE id FROM ${oe} ${ce});`;if(a.$op==="create"){if(isArray(y))throw new Error("Cannot create multiple things at once");let b=se(d);return `LET ${O} = (CREATE ONLY ${b}:\u27E8${y}\u27E9 ${k} RETURN ${A});`}if(a.$op==="update")return `LET ${O} = IF (${H}) THEN (UPDATE ${oe} ${k} ${ce} RETURN ${A}) END;`;if(a.$op==="delete")return `LET ${O} = IF (${H}) THEN (DELETE ${oe} ${ce} RETURN ${X}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=re(t,l),{usedRoleFields:f}=ge(p,a),h=`$\u27E8${u||d}\u27E9`,$="roles"in p?f.flatMap(m=>{let F=p.roles[m];if(!F)throw new Error(`Role field schema not found for ${m}`);let{cardinality:E}=F,w=isArray(a[m])?a[m].map(S=>`$\u27E8${S}\u27E9`):[`$\u27E8${a[m]}\u27E9`];if(E==="ONE"){if(w.length>1){let S=`array::filter(array::flatten([${w}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${m} = ((array::len(${S})==1) && ${S}[0]) || ${S}`;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(E==="MANY"){let S=`array::flatten([${w}])`;switch(c){case "link":return `${m} += ${S}`;case "unlink":return `${m} -= ${S}`;case "replace":return `${m} = ${S}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${E}`)}):[],g=$.length>0?`${$.join(", ")}`:"",y=g?`SET ${g}`:"";return `IF ${h} THEN (UPDATE ${h} ${y} RETURN VALUE id) END; ${h};`},i=a=>{let{$thing:l,$op:d}=a,c=re(t,l),u=se(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]],g=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,O=>!O.startsWith("$")),F=`(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 )`,w=c.roles[f].cardinality==="MANY",Q=c.roles[h].cardinality==="MANY";return [`
131
- ${w?"":`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; };`}
132
- ${Q?"":`IF array::len(array::filter(array::flatten([$\u27E8${g}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${h} is cardinality one and can link a single thing." + <string>$\u27E8${g}\u27E9; };`}
133
- FOR $node1 IN array::flatten([$\u27E8${$}\u27E9]) {
97
+ `:""}IF ${m} { (UPDATE ${m} ${M} RETURN VALUE id) }; ${m};`},o=c=>{let{$thing:u,$op:d}=c,f=ne(t,u),h=oe(u),{usedRoleFields:$}=$e(f,c);if(!["create","delete"].includes(d))throw new Error("Arcs can only be created or deleted");let[g,m]=$,E=isArray(c[g])?c[g]:[c[g]],T=isArray(c[m])?c[m]:[c[m]];if(d==="create"){if($.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let y=fe(c,G=>!G.startsWith("$")),M=`(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 )`,b=f.roles[g].cardinality==="MANY",k=f.roles[m].cardinality==="MANY";return [`
98
+ ${b?"":`IF array::len(array::filter(array::flatten([$\u27E8${E}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${g} is cardinality one and can link a single thing." + <string>$\u27E8${E}\u27E9; };`}
99
+ ${k?"":`IF array::len(array::filter(array::flatten([$\u27E8${T}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${m} is cardinality one and can link a single thing." + <string>$\u27E8${T}\u27E9; };`}
100
+ FOR $node1 IN array::flatten([$\u27E8${E}\u27E9]) {
134
101
  IF $node1 {
135
- FOR $node2 IN array::flatten([$\u27E8${g}\u27E9]) {
102
+ FOR $node2 IN array::flatten([$\u27E8${T}\u27E9]) {
136
103
  IF $node2 {
137
- CREATE ONLY ${u} SET
138
- ${f} = ${w?"array::flatten([$node1])":"$node1"},
139
- ${h} = ${Q?"array::flatten([$node2])":"$node2"}
140
- RETURN ${F};
104
+ CREATE ONLY ${h} SET
105
+ ${g} = ${b?"array::flatten([$node1])":"$node1"},
106
+ ${m} = ${k?"array::flatten([$node2])":"$node2"}
107
+ RETURN ${M};
141
108
  }
142
109
  }
143
110
  }
144
- }`]}if(d==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${h}) CONTAINSANY $\u27E8${g}\u27E9 RETURN BEFORE`},o=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=re(t,l),{usedRefFields:f}=ge(p,a),h=`$\u27E8${u||d}\u27E9`,$=f.flatMap(m=>{let F=p.refFields[m];if(!F)throw new Error(`ReferenceField schema not found for ${m}`);let{cardinality:E,contentType:w}=F;if(w==="REF"){let S=isArray(a[m])?a[m]:[`${a[m]}`];if(E==="ONE"){if(S.length>1){let Q=`array::filter(array::flatten([${S}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${m} = ((array::len(${Q})==1) && ${Q}[0]) || ${Q}`;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(${S[0]}) && array::len(${S[0]})==1) && ${S[0]}[0]) || ${S[0]}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(E==="MANY"){let Q=`array::flatten([${S}])`;switch(c){case "link":return `${m} += ${Q}`;case "unlink":return `${m} -= ${Q}`;case "replace":return `${m} = ${Q}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${E}`)}if(w==="FLEX"){if(E==="ONE")return `${m} = array::flatten([${a[m]}])[0]`;let Q=(isArray(a[m])?a[m]:[a[m]]).map(L=>typeof L=="string"&&L.startsWith("$")?`array::flatten([${L}])[0]`:L);return `${m} = [${Q.join(", ")}]`}throw new Error(`Unsupported contentType ${w}`)}),g=$.length>0?`${$.join(", ")}`:"",y=g?`SET ${g}`:"";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 So=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 bo(o,r)});if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return bo(i,r)})},bo=(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 wo=async(e,t)=>{let r=`
145
- BEGIN TRANSACTION;
111
+ }`]}if(d==="delete")return `DELETE FROM ${h} WHERE array::flatten([${g}]) CONTAINSANY $\u27E8${E}\u27E9 AND array::flatten([${m}]) CONTAINSANY $\u27E8${T}\u27E9 RETURN BEFORE`},s=c=>{let{$thing:u,$bzId:d,$op:f,$tempId:h}=c,$=ne(t,u),{usedRefFields:g}=$e($,c),m=`$\u27E8${h||d}\u27E9`,E=g.flatMap(w=>{let M=$.refFields[w];if(!M)throw new Error(`ReferenceField schema not found for ${w}`);let{cardinality:Q,contentType:b}=M;if(b==="REF"){let A=isArray(c[w])?c[w]:[`${c[w]}`];if(Q==="ONE"){if(A.length>1){let k=`array::filter(array::flatten([${A}]), |$v| !!$v)`;switch(f){case "link":case "replace":return `${w} = ${k}[0]`;case "unlink":return `${w} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}switch(f){case "link":case "replace":return `${w} = ((type::is_array(${A[0]}) && array::len(${A[0]})==1) && ${A[0]}[0]) || ${A[0]}`;case "unlink":return `${w} = NONE`;default:throw new Error(`Unsupported operation ${f} for ONE cardinality`)}}if(Q==="MANY"){let k=`array::flatten([${A}])`;switch(f){case "link":return `${w} += ${k}`;case "unlink":return `${w} -= ${k}`;case "replace":return `${w} = ${k}`;default:throw new Error(`Unsupported operation ${f} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${Q}`)}if(b==="FLEX"){if(Q==="ONE")return `${w} = array::flatten([${c[w]}])[0]`;let k=(isArray(c[w])?c[w]:[c[w]]).map(j=>typeof j=="string"&&j.startsWith("$")?`array::flatten([${j}])[0]`:j);return `${w} = [${k.join(", ")}]`}throw new Error(`Unsupported contentType ${b}`)}),T=E.length>0?`${E.join(", ")}`:"",y=T?`SET ${T}`:"";return `IF ${m} { (UPDATE ${m} ${y} RETURN VALUE id) }; ${m};`},a=e.things.filter(c=>c.$op==="match"&&!c[tt]?.bzId),l=e.things.filter(c=>!(c.$op==="match"&&!c[tt]?.bzId));return [...a.map(n),...l.map(n),...e.edges.map(i),...e.arcs.flatMap(o),...e.references.map(s)]};var oo=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(i=>isArray(i)?i.filter(o=>isObject(o)&&"meta"in o).map(o=>no(o,r)):!isObject(i)||!("meta"in i)?[]:no(i,r))},no=(e,t)=>{let r=mapEntries(e.after||{},(o,s)=>[o,o==="id"?s.id:isArray(s)&&s.length===0?void 0:s]),n=fe(e.input||{},(o,s)=>s===null),i={...r,...e.meta,...n};return t.mutation?.noMetadata?fe(i,o=>!o.startsWith("$")):i};var so=async(e,t)=>{let r=`
146
112
  ${t.join(";")};
147
113
  LET $DELTAS = SELECT * FROM Delta;
148
114
  DELETE Delta;
149
115
  RETURN $DELTAS;
150
-
151
- LET $LOGS = SELECT * FROM LOG;
152
- RETURN $LOGS;
153
- COMMIT TRANSACTION;
154
- `;ee(`>>> batchedMutation[${te}]`,JSON.stringify({batchedMutation:r}));try{return (await e.query(r)).filter(Boolean)}catch(n){let i=n instanceof Error?n.message:String(n);throw G("runSURQLMutation",`runSURQLMutation/batchedMutation
155
- `,r),G("runSURQLMutation",`runSURQLMutation/error
156
- `,n),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 Ul=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Wl=(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}}},Hl=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},jr=j("error","error",x((e,t)=>({...e,error:t.error}))),vl=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=>(ee(`>>> surqlMachine/buildMutation[${te}]`,JSON.stringify(e.bql.flat)),Bo(e.bql.flat,e.schema)),j("done","runMutation",x(Wl)),jr),runMutation:U(async e=>(ee(`>>> surqlMachine/runMutation[${te}]`,JSON.stringify(e.surql.mutations)),wo(vl(e.handles),e.surql.mutations)),j("done","parseMutation",x(Hl)),jr),parseMutation:U(async e=>(ee(`>>> surqlMachine/parseMutation[${te}]`,JSON.stringify(e.surql.res)),So({res:e.surql.res,config:e.config,schema:e.schema})),j("done","success",x(Ul)),jr),success:me(),error:me()},e=>e),Kl=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);}),Lo=async(e,t,r,n,i,o)=>Kl({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:i,handles:o,error:null});var _r=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 Qo=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:g,defaultDBConnector:y}=$,m=y?.path||p.$thing,F=p.$id,E=g?.[0],w=listify(p,(k,A)=>{if(k.startsWith("$")||k.startsWith("%")||k===E||A===void 0||A===null)return "";let X=$.dataFields?.find(T=>T.path===k);if(!X?.path)return "";let B=X.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(X.contentType))return `has ${B} '${A}'`;if(["NUMBER","BOOLEAN"].includes(X.contentType))return `has ${B} ${A}`;if(X.contentType==="DATE"){if(Number.isNaN(A.valueOf()))throw new Error("Invalid format, Nan Date");return A instanceof Date?`has ${B} ${A.toISOString().replace("Z","")}`:`has ${B} ${new Date(A).toISOString().replace("Z","")}`}if(X.contentType==="FLEX"){let T=`bza${je()}`,D=isArray(A)?A.map(R=>_r(R)):_r(A);if(Array.isArray(D))throw new Error("Array in FLEX fields not supported yet");return `has ${B} $${T}; $${T} '${T}' isa ${B}, has ${D.type}Attribute ${D.value}`}throw new Error(`Unsupported contentType ${X.contentType}`)}).filter(k=>k),S=`${h}-atts`,Q=listify(p,k=>{if(k.startsWith("$")||k.startsWith("%")||k===E)return "";let A=$.dataFields?.find(B=>B.path===k);if(!A?.path)return "";let b=A.dbPath;return `{${S} isa ${b};}`}).filter(k=>k),L=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,O=F?[`has ${E} ${L}`]:[],H=[...O,...w].filter(k=>k).join(","),oe=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[m,...O].filter(k=>k).join(",")};`;if(f==="update"){if(!Q.length)throw new Error("update without attributes");return `${h} isa ${[m,...O].filter(k=>k).join(",")}, has ${S};
157
- ${Q.join(" or ")};`}return ""},ce=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[m,...O].filter(k=>k).join(",")};`:"";if(At(p))return {op:f,deletionMatch:oe(),insertionMatch:ce(),insertion:f==="create"?`${h} isa ${[m,H].filter(k=>k).join(",")};`:f==="update"&&w.length?`${h} ${w.join(",")};`:"",deletion:f==="delete"?`${h} isa ${m};`:f==="update"&&Q.length?`${h} has ${S};`:""};throw new Error("in attributes")},i=p=>{let f=p.$op,h=z(r,p),$=`$${p.$bzId}`,g=p.$id,y=h.defaultDBConnector?.path||p.$thing,m="roles"in h?listify(h.roles,A=>A):[],F="roles"in h?mapEntries(h.roles,(A,X)=>[A,X.dbConnector?.path||A]):{},E=listify(p,(A,X)=>{if(!m.includes(A))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=F[A];return Array.isArray(X)?X.map(B=>({path:b,id:B})):{path:b,id:X}}).filter(A=>A).flat(),w=E.map(A=>{if(!A?.path)throw new Error("Object without path");return `${A.path}: $${A.id}`}),S=E.length>0?`( ${w.join(" , ")} )`:"",Q=p[ve];if(!Q)throw new Error("[internal error] Symbol edgeType not defined");let L=S?`${$} ${S} ${Q==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",O=`${$} ${Q==="linkField"||f==="delete"?`isa ${y}`:""}`,H=()=>L?f==="link"?`${L};`:f==="create"?`${L}, has id '${g}';`:"":"",oe=()=>L&&f==="match"?`${L};`:"",ce=()=>L?f==="delete"?`${L};`:f==="match"?`${L};`:"":"",k=()=>L?f==="delete"?`${O};`:f==="unlink"?`${$} ${S};`:"":"";return {deletionMatch:ce(),insertionMatch:oe(),deletion:k(),insertion:H(),op:""}},o=(p,f)=>{let h=f==="edges"?i:n;if(Array.isArray(p))return p.map(E=>{let{preDeletionBatch:w,insertionMatch:S,deletionMatch:Q,insertion:L,deletion:O}=h(E);return shake({preDeletionBatch:w,insertionMatch:S,deletionMatch:Q,insertion:L,deletion:O},H=>!H)}).filter(E=>E);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:m,deletion:F}=h(p);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:m,deletion:F},E=>!E)},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 Do=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?re(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,[$,g])=>{if(c?.dataFields?.find(m=>m.path===$)?.contentType==="JSON")return h[$]=JSON.parse(g),h;if(a.$thingType==="relation"){let m=o.filter(F=>F.$id&&F.$bzId===g);return m.length===1?(h[$]=m[0].$id,h):(h[$]=g,h)}return h[$]=g,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 Ao=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 Ut(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 ec=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),tc=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),rc=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),Vr=j("error","error",x((e,t)=>({...e,error:t.error}))),nc=we("buildMutation",{buildMutation:U(async e=>Qo(e.bql.things,e.bql.edges,e.schema),j("done","runMutation",x(tc)),Vr),runMutation:U(async e=>Ao(e.tql.mutation,e.handles,e.config),j("done","parseMutation",x(rc)),Vr),parseMutation:U(async e=>Do(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),j("done","success",x(ec)),Vr),success:me(),error:me()},e=>e),ic=async e=>new Promise((t,r)=>{Re(nc,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),No=async(e,t,r,n,i,o,s)=>ic({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 Oo=me,ht=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,oc=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),sc=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),ac=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),lc=async e=>(ee(`>>> mutationMachine/enrich[${te}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?mr(e.bql.enriched,e.schema,e.config):mr(e.bql.raw,e.schema,e.config)),cc=async e=>(ee(`>>> mutationMachine/preQuery[${te}]`,JSON.stringify(e.bql.enriched)),go(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),dc=async e=>(ee(`>>> mutationMachine/preQueryDependencies[${te}]`,JSON.stringify(e.bql.enriched)),ao(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),uc=async e=>(ee(`>>> mutationMachine/parseBQL[${te}]`,JSON.stringify(e.bql.enriched)),yo(e.bql.enriched,e.schema)),pc=async e=>(ee(`>>> mutationMachine/flattenBQL[${te}]`,JSON.stringify(e.bql.enriched)),ho(e.bql.enriched,e.schema)),hc=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}.`)},fc=e=>ot(e.bql.enriched),Ze=j("error","error",x((e,t)=>({...e,error:t.error}))),$c=we("stringify",{stringify:U(async e=>(ee(`>>> mutationMachine/stringify[${te}]`,JSON.stringify(e.bql.raw)),Eo(e.bql.raw,e.schema)),j("done","enrich",x(ht)),Ze),enrich:U(lc,j("done","preQuery",or(hc),x(ht)),j("done","parseBQL",x(ht)),Ze),preQuery:U(cc,j("done","preHookDependencies",or(fc),x(ht)),j("done","parseBQL",x(ht)),Ze),preHookDependencies:U(dc,j("done","enrich",x(ht)),Ze),parseBQL:U(uc,j("done","flattenBQL",x(oc)),Ze),flattenBQL:U(pc,j("done","adapter",x(sc)),Ze),adapter:U(async e=>{ee(`>>> mutationMachine/adapter[${te}]`,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 No(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return Lo(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",x(ac)),Ze),success:Oo(),error:Oo()},e=>e),mc=async e=>new Promise((t,r)=>{Re($c,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Io=async(e,t,r,n,i)=>mc({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 Ur=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 Tt({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:cn(this.schema),enrichedSchema:on(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 Gr(this.config,t.enrichedSchema,t.dbHandles)};query=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,query:{...Yt.query,...this.config.query,...r}},o=Array.isArray(t),s=o?t:[t],[a,l]=await tryit(ut)(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:{...Yt.mutation,...this.config.mutation,...r}},[o,s]=await tryit(Io)(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;}}},w$=Ur;//! 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
116
+ `;le(`>>> batchedMutation[${ce}]`,JSON.stringify({batchedMutation:r}));let n;try{n=await e.beginTransaction();let i=await n.query(r);return await n.commit(),i.filter(Boolean)}catch(i){await n?.cancel().catch(()=>{});let o=i instanceof Error?i.message:String(i);ee("runSURQLMutation",`runSURQLMutation/batchedMutation
117
+ `,r),ee("runSURQLMutation",`runSURQLMutation/error
118
+ `,i);let s=o.match(/Couldn't coerce value for field `(.+?)` of .+?: .+ but found `?NONE`?/);throw s&&(o=`Found NONE for field \`${s[1]}\``),o.startsWith("An error occurred: ")&&(o=`[{"result":"${o}"}]`),new Error(`Error running SURQL mutation: ${o}`)}};var dl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ul=(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}}},pl=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Or=v("error","error",U((e,t)=>({...e,error:t.error}))),hl=e=>{let t=e.surrealDB?.values().next().value;if(!t?.client)throw new Error("No SurrealDB client available");return t.client},fl=De("buildMutation",{buildMutation:X(async e=>(le(`>>> surqlMachine/buildMutation[${ce}]`,JSON.stringify(e.bql.flat)),to(e.bql.flat,e.schema)),v("done","runMutation",U(ul)),Or),runMutation:X(async e=>(le(`>>> surqlMachine/runMutation[${ce}]`,JSON.stringify(e.surql.mutations)),so(hl(e.handles),e.surql.mutations)),v("done","parseMutation",U(pl)),Or),parseMutation:X(async e=>(le(`>>> surqlMachine/parseMutation[${ce}]`,JSON.stringify(e.surql.res)),oo({res:e.surql.res,config:e.config,schema:e.schema})),v("done","success",U(dl)),Or),success:ge(),error:ge()},e=>e),$l=async e=>new Promise((t,r)=>{Ae(fl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),lo=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 Nr=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 uo=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=d=>{let f=d.$op,h=`$${d.$bzId}`,$=V(r,d),{idFields:g,defaultDBConnector:m}=$,E=m?.path||d.$thing,T=d.$id,y=g?.[0],w=listify(d,(D,N)=>{if(D.startsWith("$")||D.startsWith("%")||D===y||N===void 0||N===null)return "";let z=$.dataFields?.find(S=>S.path===D);if(!z?.path)return "";let R=z.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(z.contentType))return `has ${R} '${N}'`;if(["NUMBER","BOOLEAN"].includes(z.contentType))return `has ${R} ${N}`;if(z.contentType==="DATE"){if(Number.isNaN(N.valueOf()))throw new Error("Invalid format, Nan Date");return N instanceof Date?`has ${R} ${N.toISOString().replace("Z","")}`:`has ${R} ${new Date(N).toISOString().replace("Z","")}`}if(z.contentType==="FLEX"){let S=`bza${Pe()}`,B=isArray(N)?N.map(F=>Nr(F)):Nr(N);if(Array.isArray(B))throw new Error("Array in FLEX fields not supported yet");return `has ${R} $${S}; $${S} '${S}' isa ${R}, has ${B.type}Attribute ${B.value}`}throw new Error(`Unsupported contentType ${z.contentType}`)}).filter(D=>D),M=`${h}-atts`,Q=listify(d,D=>{if(D.startsWith("$")||D.startsWith("%")||D===y)return "";let N=$.dataFields?.find(R=>R.path===D);if(!N?.path)return "";let L=N.dbPath;return `{${M} isa ${L};}`}).filter(D=>D),b=isArray(T)?`like '${T.join("|")}'`:`'${T}'`,A=T?[`has ${y} ${b}`]:[],k=[...A,...w].filter(D=>D).join(","),j=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[E,...A].filter(D=>D).join(",")};`;if(f==="update"){if(!Q.length)throw new Error("update without attributes");return `${h} isa ${[E,...A].filter(D=>D).join(",")}, has ${M};
119
+ ${Q.join(" or ")};`}return ""},G=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[E,...A].filter(D=>D).join(",")};`:"";if(Lt(d))return {op:f,deletionMatch:j(),insertionMatch:G(),insertion:f==="create"?`${h} isa ${[E,k].filter(D=>D).join(",")};`:f==="update"&&w.length?`${h} ${w.join(",")};`:"",deletion:f==="delete"?`${h} isa ${E};`:f==="update"&&Q.length?`${h} has ${M};`:""};throw new Error("in attributes")},i=d=>{let f=d.$op,h=V(r,d),$=`$${d.$bzId}`,g=d.$id,m=h.defaultDBConnector?.path||d.$thing,E="roles"in h?listify(h.roles,N=>N):[],T="roles"in h?mapEntries(h.roles,(N,z)=>[N,z.dbConnector?.path||N]):{},y=listify(d,(N,z)=>{if(!E.includes(N))return null;if(!("roles"in h))throw new Error("This should have roles! ");let L=T[N];return Array.isArray(z)?z.map(R=>({path:L,id:R})):{path:L,id:z}}).filter(N=>N).flat(),w=y.map(N=>{if(!N?.path)throw new Error("Object without path");return `${N.path}: $${N.id}`}),M=y.length>0?`( ${w.join(" , ")} )`:"",Q=d[ve];if(!Q)throw new Error("[internal error] Symbol edgeType not defined");let b=M?`${$} ${M} ${Q==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",A=`${$} ${Q==="linkField"||f==="delete"?`isa ${m}`:""}`,k=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${g}';`:"":"",j=()=>b&&f==="match"?`${b};`:"",G=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",D=()=>b?f==="delete"?`${A};`:f==="unlink"?`${$} ${M};`:"":"";return {deletionMatch:G(),insertionMatch:j(),deletion:D(),insertion:k(),op:""}},o=(d,f)=>{let h=f==="edges"?i:n;if(Array.isArray(d))return d.map(y=>{let{preDeletionBatch:w,insertionMatch:M,deletionMatch:Q,insertion:b,deletion:A}=h(y);return shake({preDeletionBatch:w,insertionMatch:M,deletionMatch:Q,insertion:b,deletion:A},k=>!k)}).filter(y=>y);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:E,deletion:T}=h(d);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:m,insertion:E,deletion:T},y=>!y)},s=o(e),a=Array.isArray(s)?s:[s],l=o(t,"edges"),p=Array.isArray(l)?l:[l],c=[...a,...p];return shake({insertionMatches:c.map(d=>d.insertionMatch).join(" ").trim(),deletionMatches:c.map(d=>d.deletionMatch).join(" ").trim(),insertions:c.map(d=>d.insertion).join(" ").trim(),deletions:c.map(d=>d.deletion).join(" ").trim()},d=>!d)};var po=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}`),p=a.$thing||a.$relation||a.$entity,c=p?ne(n,p):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,d=Object.entries(a).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,g])=>{if(c?.dataFields?.find(E=>E.path===$)?.contentType==="JSON")return h[$]=JSON.parse(g),h;if(a.$thingType==="relation"){let E=o.filter(T=>T.$id&&T.$bzId===g);return E.length===1?(h[$]=E[0].$id,h):(h[$]=g,h)}return h[$]=g,h},{});if(i.mutation?.noMetadata)return d;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:u,...a,...d,[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 ho=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:n}=await _t(t,r),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 Bl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Fl=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),bl=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),kr=v("error","error",U((e,t)=>({...e,error:t.error}))),Tl=De("buildMutation",{buildMutation:X(async e=>uo(e.bql.things,e.bql.edges,e.schema),v("done","runMutation",U(Fl)),kr),runMutation:X(async e=>ho(e.tql.mutation,e.handles,e.config),v("done","parseMutation",U(bl)),kr),parseMutation:X(async e=>po(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),v("done","success",U(Bl)),kr),success:ge(),error:ge()},e=>e),wl=async e=>new Promise((t,r)=>{Ae(Tl,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,s)=>wl({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 $o=ge,dt=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Rl=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Sl=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Ll=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ml=async e=>(le(`>>> mutationMachine/enrich[${ce}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?ur(e.bql.enriched,e.schema,e.config):ur(e.bql.raw,e.schema,e.config)),Dl=async e=>(le(`>>> mutationMachine/preQuery[${ce}]`,JSON.stringify(e.bql.enriched)),Xi(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),Al=async e=>(le(`>>> mutationMachine/preQueryDependencies[${ce}]`,JSON.stringify(e.bql.enriched)),Vi(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),Ql=async e=>(le(`>>> mutationMachine/parseBQL[${ce}]`,JSON.stringify(e.bql.enriched)),Zi(e.bql.enriched,e.schema)),Ol=async e=>(le(`>>> mutationMachine/flattenBQL[${ce}]`,JSON.stringify(e.bql.enriched)),Hi(e.bql.enriched,e.schema)),Nl=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}.`)},Il=e=>it(e.bql.enriched),Ze=v("error","error",U((e,t)=>({...e,error:t.error}))),kl=De("stringify",{stringify:X(async e=>(le(`>>> mutationMachine/stringify[${ce}]`,JSON.stringify(e.bql.raw)),Gi(e.bql.raw,e.schema)),v("done","enrich",U(dt)),Ze),enrich:X(Ml,v("done","preQuery",er(Nl),U(dt)),v("done","parseBQL",U(dt)),Ze),preQuery:X(Dl,v("done","preHookDependencies",er(Il),U(dt)),v("done","parseBQL",U(dt)),Ze),preHookDependencies:X(Al,v("done","enrich",U(dt)),Ze),parseBQL:X(Ql,v("done","flattenBQL",U(Rl)),Ze),flattenBQL:X(Ol,v("done","adapter",U(Sl)),Ze),adapter:X(async e=>{le(`>>> mutationMachine/adapter[${ce}]`,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 fo(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return lo(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},v("done","success",U(Ll)),Ze),success:$o(),error:$o()},e=>e),Cl=async e=>new Promise((t,r)=>{Ae(kl,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)=>Cl({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 Cr=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 Ft({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});}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:en(this.schema),enrichedSchema:Kr(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 Wr(this.config,t.enrichedSchema,t.draftSchema,t.dbHandles)};query=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,query:{...Ut.query,...this.config.query,...r}},o=Array.isArray(t),s=o?t:[t],[a,l]=await tryit(lt)(s,n.enrichedSchema,n.draftSchema,i,n.dbHandles);if(a){let c=new Error(a.error);throw c.stack=a.error.stack,c}let p=l.bql.res;return o?p:p[0]};mutate=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,mutation:{...Ut.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;}}},yf=Cr;//! 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
158
120
  //! Todo: delete when this works with the new $thing and $thingType fields
159
121
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
160
122
  //! reads all the insertions and gets the first match. This means each id must be unique
161
123
  //!old
162
- export{w$ as default};//# sourceMappingURL=index.mjs.map
124
+ export{yf as default};//# sourceMappingURL=index.mjs.map
163
125
  //# sourceMappingURL=index.mjs.map